FastAPI Lambda with GraphQL & KafkaIntegration: Complete Solution
Step 1: Lambda Code (app.py
)
Step 2: Prepare Lambda Package
-
Create a
requirements.txt
file:
your-code.zip
file containing all the necessary code and dependencies.your-code.zip
file to an S3 bucket.Step 6: CloudFormation Template (CFT)
Here is the CloudFormation Template (CFT) for deploying the Lambda, API Gateway, and Load Balancer.
AWSTemplateFormatVersion: '2010-09-09'
Resources:
# Lambda Function
FastAPILambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Handler: 'app.handler'
Runtime: 'python3.8'
Code:
S3Bucket: 'your-bucket-name' # Replace with your S3 bucket name
S3Key: 'your-code.zip' # Replace with the path to your zip file in S3
MemorySize: 128
Timeout: 30
Environment:
Variables:
ENVIRONMENT: 'production'
# API Gateway (HTTP API)
ApiGateway:
Type: 'AWS::ApiGatewayV2::Api'
Properties:
ProtocolType: 'HTTP'
Target:
Fn::GetAtt:
- 'FastAPILambdaFunction'
- 'Arn'
# Load Balancer
LoadBalancer:
Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'
Properties:
Subnets:
- Ref: 'SubnetId'
SecurityGroups:
- Ref: 'SecurityGroupId'
Outputs:
FastAPIAppURL:
Description: 'URL of the FastAPI application'
Value: !Sub 'http://${LoadBalancer.DNSName}/graphql'
Key Parts of the CloudFormation Template:
-
Lambda Function (
FastAPILambdaFunction
): Defines the Lambda function that runs your FastAPI code. The.zip
file from S3 is used as the code source. -
API Gateway (
ApiGateway
): The HTTP API Gateway that triggers the Lambda function for HTTP requests. -
Load Balancer (
LoadBalancer
): An Application Load Balancer to distribute traffic.
Step 7: Deploying CloudFormation
-
Upload the CloudFormation Template to AWS CloudFormation via the AWS Console or AWS CLI.
-
Update the S3 bucket and
.zip
file paths in the template (your-bucket-name
andyour-code.zip
). -
Deploy the CloudFormation stack. This will automatically create:
-
The Lambda function with your FastAPI code.
-
The API Gateway to handle incoming HTTP requests.
-
The Load Balancer to distribute traffic.
Step 8: Example GraphQL Query
Once the stack is deployed, you can query your FastAPI app using GraphQL. The app is exposed through the Load Balancer's DNS name.
GraphQL Query Example (POST request to http://<your-load-balancer-dns-name>/graphql
):
{
"query": "query { trade(symbol: \"AAPL\", start_date: \"2024-03-01\", end_date: \"2024-03-10\") { feedmsgseq sourcetime symbol tradeid price volume tradecondition1 tradecondition2 marketid }}"
}
Summary
This document guides you through:
-
Lambda Code: Writing a FastAPI application integrated with GraphQL.
-
Packaging the Lambda: Installing dependencies and creating a deployable
.zip
file. -
CloudFormation Template: Automating the deployment of the Lambda function, API Gateway, and Load Balancer.
-
Deployment: Instructions on uploading the Lambda code to S3 and deploying with CloudFormation.
-
Querying: How to query the deployed FastAPI app via GraphQL.
No comments:
Post a Comment