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:
- Verify the API is running by visiting
http://localhost:5000
in your web browser or usingcurl http://localhost:5000
. The response should be:{"message": "Hello, World!"}
. - Verify the API is accessible from other services by visiting
http://api:5000
from another service or container within the network. - 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:
- Grafana documentation Developers HTTP API Library Element: https://grafana.com/docs/grafana/latest/developers/http_api/library_element
- Grafana documentation Developers HTTP API Alerting Provisioning: https://grafana.com/docs/grafana/latest/developers/http_api/alerting_provisioning
- Java Serverless Functions: https://opensource.com/article/21/6/java-serverless-functions
- Grafana documentation Developers HTTP API: https://grafana.com/docs/grafana/latest/developers/http_api
- Grafana OnCall HTTP API reference: https://grafana.com/docs/oncall/latest/oncall-api-reference
- Grafana documentation Developers HTTP API Team: https://grafana.com/docs/grafana/latest/developers/http_api/team
- Microservices Authentication with Kubernetes: https://learnk8s.io/microservices-authentication-kubernetes
- FaaS on Kubernetes from AWS Lambda to Knative Kong API Gateway: https://pmbanugo.me/faas-on-kubernetes-from-aws-lambda-api-gateway-to-knative-kong-api-gateway
- Building RESTful API: https://www.educative.io/blog/building-restful-api