Search code examples
pythonamazon-web-servicesaws-lambdaaws-api-gatewayfastapi

What is the JSON input format for a Lambda function for proxy integration?


I'm using AWS Lambda with an API Gateway proxy integration (AWS_PROXY) such that requests are passed directly without API Gateway imposing any routing.

Lambda is hosting a FastAPI application and Mangum is the intermediary that allows Lambda to respond to requests as a uvivorn server would.

My question is, how should the request be represented as JSON?

@app.get("/get-student/{student_id}")
def get_student(student_id: int):
    return students[student_id]

What should an inbound request look like? This is my naive guess. From Mangum documentation, I'm not yet clear on what is required.

{
   "httpMethod":"GET",
   "path":"/get-student/1"
}

Solution

  • In Lambda proxy integration, API Gateway maps the entire client request to the input event parameter of the Lambda function.

    This event parameter is the Lambda proxy integration request and the payload format depends on if you're using version 1 or version 2 of the payload; schemas for both versions are listed in the docs.

    REST APIs & WebSocket APIs only support sending v1 payloads to Lambda proxy integrations. HTTP APIs support sending both v1 and v2, but via the console, they are configured by default to send the latest version (currently, v2).

    Note to not confuse this with the namespaces that you'd see in the CLI, APIs, CloudFormation, SDKs, or AWS SAM. While the API V1 namespace represents REST APIs & API V2 represents WebSocket and HTTP APIs, the 'namespace versions' do not align with the payload versions.

    For a REST API (v1), a minimal request for your endpoint could look like this:

    {
      "version": "1.0", 
      "resource": "/get-student/{student_id}",
      "path": "/get-student/1",
      "httpMethod": "GET",
      "pathParameters": {
        "student_id": "1"
      }
    }
    

    And for a HTTP API (v2), a minimal request for your endpoint could look like this:

    {
      "version": "2.0",
      "routeKey": "GET /get-student/{student_id}",
      "rawPath": "/get-student/1",
      "pathParameters": {
        "student_id": "1"
      }
    }
    

    In most AWS SDKs, like the one for .NET, the proxy integration request is available as a class i.e. APIGatewayProxyRequest(v1) / APIGatewayHttpApiV2ProxyRequest (v2).