Creating a Standalone HTTP API with the Genai-Stack

Scenario: A developer wants to create a standalone HTTP API using the Genai-Stack. In this example, we will create a new service named api in the docker-compose.yml file and configure it as an HTTP API.

First, let’s create a new directory for the API service within the project:

mkdir api

Next, navigate to the new directory and create a Dockerfile:

cd api
touch Dockerfile

Now, let’s define the api service in the docker-compose.yml file:

version: '3.8'

services:
# ... (existing services)

api:
build:
context: ./api
dockerfile: Dockerfile
ports:
- "5000:5000"
depends_on:
- db
environment:
- DATABASE_URL=postgresql://user:password@db:5432/database
volumes:
- ./api:/app

# ... (existing volumes and networks)

Now, let’s create a simple Flask application within the api directory:

touch api.py

Add the following code to api.py:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello():
return jsonify({'message': 'Hello, World!'})

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

Now, update the Dockerfile to build the application:

FROM python:3.9

WORKDIR /app
COPY . /app
RUN pip install flask

CMD ["flask", "run", "--host=0.0.0.0"]

To test the API locally, run the following command:

docker-compose up -d api

Now, you can access the API by visiting http://localhost:5000 in your web browser or using a tool like curl.

Tests:

  1. Verify the API is running by visiting http://localhost:5000 in your web browser or using curl http://localhost:5000. The response should be: {"message": "Hello, World!"}.
  2. Verify the API is accessible from other services by visiting http://api:5000 from another service or container within the network.
  3. Create additional API endpoints and test them using the same approach.

For more information on creating APIs with the Genai-Stack, refer to the following resources: