Skip to content

Instantly share code, notes, and snippets.

@satendrakumar
Last active August 7, 2025 10:46
Show Gist options
  • Save satendrakumar/f59daeb6815c6d8366c5db90671d789a to your computer and use it in GitHub Desktop.
Save satendrakumar/f59daeb6815c6d8366c5db90671d789a to your computer and use it in GitHub Desktop.
FAST API on AWS Lambda

Deploying a FastAPI app on AWS Lambda using AWS SAM

Step 1: Initialize a SAM Project

Create a new SAM project:

     sam init --runtime python3.11 --name fastapi-lambda
     Choose the Quick Start: Hello World Example template.
     Delete the default app.py and create your FastAPI app

Step 2: Create FastAPI App with Mangum

FastAPI requires an ASGI adapter to work with AWS Lambda. Use Mangum to bridge FastAPI and Lambda.

app.py:
      from fastapi import FastAPI
      from mangum import Mangum

      app = FastAPI()

      @app.get("/")
      def read_root():
          return {"message": "Hello from FastAPI on Lambda!"}

      @app.get("/items/{item_id}")
      def read_item(item_id: int, q: str = None):
          return {"item_id": item_id, "q": q}

      # Mangum handler for Lambda
      handler = Mangum(app)

Install dependencies:

    pip install fastapi mangum
    pip freeze > requirements.txt

Step 3: Update SAM Template

Modify template.yaml to define the Lambda function and API Gateway:

  AWSTemplateFormatVersion: '2010-09-09'
  Transform: AWS::Serverless-2016-10-31
  Description: FastAPI on AWS Lambda with SAM
  Resources:
    FastAPIFunction:
      Type: AWS::Serverless::Function
      Properties:
        CodeUri: .
        Handler: app.handler  # Points to the Mangum handler
        Runtime: python3.11
        Timeout: 30  # Increase timeout if needed
        MemorySize: 512
        Events:
          ApiEvent:
            Type: Api
            Properties:
              Path: /{proxy+}
              Method: ANY
              RestApiId: !Ref FastAPIApi

    FastAPIApi:
      Type: AWS::Serverless::Api
      Properties:
        StageName: prod
        Cors:  # Optional: Enable CORS
          AllowMethods: "'*'"
          AllowHeaders: "'*'"
          AllowOrigin: "'*'"

  Outputs:
    ApiUrl:
      Description: API Gateway endpoint URL
      Value: !Sub "https://${FastAPIApi}.execute-api.${AWS::Region}.amazonaws.com/prod/"

Step 4: Build and Test Locally

Build the SAM project:

      sam build

Test locally:

      sam local start-api
  
      Visit http://localhost:3000/ or http://localhost:3000/items/42?q=test to test.

Step 5: Deploy to AWS

First-time deployment (guided):

    sam deploy --guided
    Follow prompts to name your stack and select AWS region.

Subsequent deployments:

    sam build && sam deploy --no-confirm-changeset

Step 6: Verify Deployment

Check the ApiUrl output from the SAM deployment logs.

  Test the endpoints:
    curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/
    curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/items/5?q=test
  Key Notes
     Cold Starts: Lambda may have cold starts. Use Provisioned Concurrency for critical APIs.

   Dependencies: Ensure all dependencies (like fastapi, mangum) are in requirements.txt.
   Layers: For large dependencies, use Lambda Layers.

   Logs: Check CloudWatch Logs for debugging:
      sam logs -n FastAPIFunction --stack-name <stack-name> --tail

Example Project Structure:

  fastapi-lambda/
  ├── app.py
  ├── requirements.txt
  ├── template.yaml
  └── tests/

This setup allows you to deploy a scalable, serverless FastAPI app on AWS Lambda with minimal overhead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment