Skip to content

FastAPI

FastAPI is a framework for building APIs in Python.

The FastAPI generator creates a new FastAPI with AWS CDK or Terraform infrastructure setup. The generated backend is exposed via an AWS API Gateway API. It sets up AWS Lambda Powertools for observability, including structured logging and CloudWatch metrics.

infra ≠ http-ecs

The backend uses AWS Lambda for serverless deployment, and AWS X-Ray tracing is set up too.

infra = http-ecs

Your API runs as a long-lived uvicorn server in a container on Amazon ECS, behind an API Gateway HTTP API, rather than in a Lambda function. See Running on Amazon ECS for what that changes, including why X-Ray tracing produces no traces there.

You can generate a new FastAPI in two ways:

Run this generator@aws/nx-plugin:py#api

pnpm nx g @aws/nx-plugin:py#api --framework=fastapi
Build your command11

Required

Generator Options11 options
nameRequiredstring

Name of the API project to generate

frameworkenumDefault: fastapi

The API framework to use.

fastapi
integrationPatternenum

How API Gateway integrations are generated for the API. Choose between isolated and shared. Defaults to isolated. The http-ecs infrastructure always uses shared, since one container service answers every operation, so isolated is ignored there with a warning.

isolatedshared
authenumDefault: iam

The method used to authenticate with your API. Choose between iam (default), cognito or custom.

iamcognitocustom
directorystringDefault: packages

The directory to store the application in.

iacenumDefault: inherit

The preferred IaC provider. By default this is inherited from your initial selection.

inheritcdkterraform
infraenumDefault: rest-lambda

The type of infrastructure to use to deploy this API. http-ecs (experimental) runs the API as a container service on Amazon ECS behind an API Gateway HTTP API, and requires the CDK IaC provider. It always uses integrationPattern shared, since one container service answers every operation.

rest-lambdahttp-lambdahttp-ecsnone
subDirectorystring

The sub directory the project is placed in. By default this is the project name.

moduleNamestring

Python module name

architectureenum

The CPU architecture your container image is built for and its ECS task runs on. Applies to the http-ecs infrastructure. ARM64 runs on AWS Graviton, which costs less per task on AWS Fargate. By default this is the architecture of the machine you run the generator on, and re-running keeps the architecture already generated.

ARM64X86_64
preferInstallDependenciesbooleanDefault: true

Whether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.

infra = http-ecs

The generator will create the following project structure in the <directory>/<api-name> directory:

  • project.json Project configuration and build targets
  • pyproject.toml Python project configuration and dependencies
  • run.sh Lambda Web Adapter bootstrap script to start the FastAPI app via uvicorn
  • Directory<module_name>
    • __init__.py Module initialisation
    • init.py Sets the up FastAPI app and configures powertools middleware
    • main.py API implementation
  • Directoryscripts
    • generate_open_api.py Script to generate an OpenAPI schema from the FastAPI app
infra = http-ecs

With infra set to http-ecs the API runs as its own HTTP server rather than behind the Lambda Web Adapter, so run.sh is not generated. In its place you get a container folder inside your module, named after your API:

  • Directory<module_name>
    • Directory<api_name>_container
      • main.py Entry point: adds GET /health, writes out the metrics the API collects, and starts uvicorn on HOST and PORT. The bundle, the image and the serve target all start from this file
      • Dockerfile Container image definition
      • .dockerignore Files left out of the image build context

Your init.py, main.py and the operations you add to them are the same for every infra value.

Since this generator vends infrastructure as code based on your chosen iac, it will create a project in packages/common which includes the relevant CDK constructs or Terraform modules.

The common infrastructure as code project is structured as follows:

  • Directorypackages/common/constructs
    • Directorysrc
      • Directoryapp/ Constructs for infrastructure specific to a project/generator
        • …
      • Directorycore/ Generic constructs which are reused by constructs in app
        • …
      • index.ts Entry point exporting constructs from app
    • project.json Project build targets and configuration

For deploying your API, the following files are generated:

  • Directorypackages/common/constructs/src
    • Directoryapp
      • Directoryapis
        • <project-name>.ts CDK construct for deploying your API
    • Directorycore
      • Directoryapi
        • http-api.ts CDK construct for deploying an HTTP API (if you selected to deploy an HTTP API)
        • rest-api.ts CDK construct for deploying a REST API (if you selected to deploy a REST API)
        • utils.ts Utilities for the API constructs

The deployed application has the following architecture: an API Gateway API in front of a Lambda function running your handler.

Loading the diagram…

REST APIs include an AWS WAFv2 Web ACL in front of the API Gateway stage with the AWS managed default ruleset enabled.

The main API implementation is in main.py. This is where you define your API routes and their implementations. Here’s an example:

from pydantic import BaseModel
from .init import app, tracer
class Item(BaseModel):
name: str
@app.get("/items/{item_id}")
@tracer.capture_method
def get_item(item_id: int) -> Item:
return Item(name=f"Item {item_id}")
@app.post("/items")
@tracer.capture_method
def create_item(item: Item) -> Item:
return item

The generator sets up several features automatically:

  1. AWS Lambda Powertools integration for observability
  2. Error handling middleware
  3. Request/response correlation
  4. Metrics collection
infra ≠ http-ecs

Type-safe streaming is set up too, for the rest-lambda infrastructure only.

infra ≠ http-ecs

The app is served in a Lambda function by the Lambda Web Adapter running uvicorn.

infra = http-ecs

The app is served by uvicorn in the container, with no Lambda Web Adapter. See Running on Amazon ECS.

The generator configures structured logging using AWS Lambda Powertools. You can access the logger in your route handlers:

from .init import app, logger
@app.get("/items/{item_id}")
def read_item(item_id: int):
logger.info("Fetching item", extra={"item_id": item_id})
return {"item_id": item_id}

The logger automatically includes:

  • Correlation IDs for request tracing
  • Request path, matched route and method

AWS X-Ray tracing is configured automatically. You can add custom subsegments to your traces:

from .init import app, tracer
@app.get("/items/{item_id}")
@tracer.capture_method
def read_item(item_id: int):
# Creates a new subsegment
with tracer.provider.in_subsegment("fetch-item-details"):
# Your logic here
return {"item_id": item_id}
infra = http-ecs

CloudWatch metrics are collected automatically for each request. You can add custom metrics:

from .init import app, metrics
from aws_lambda_powertools.metrics import MetricUnit
@app.get("/items/{item_id}")
def read_item(item_id: int):
metrics.add_metric(name="ItemViewed", unit=MetricUnit.Count, value=1)
return {"item_id": item_id}

Default metrics include:

  • Request counts
  • Success/failure counts
  • Per-route metrics (via a route dimension of <method> <path>)

The generator includes comprehensive error handling:

from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id < 0:
raise HTTPException(status_code=400, detail="Item ID must be positive")
return {"item_id": item_id}

Unhandled exceptions are caught by the middleware and:

  1. Log the full exception with stack trace
  2. Record a failure metric
  3. Return a safe 500 response to the client
  4. Preserve the correlation ID
infra = http-ecs

On ECS there is no Lambda Web Adapter and no API Gateway request context header: API Gateway does not forward the authorizer’s claims to a private load balancer integration. The authorizer still decides whether a request reaches the container at all, but your handlers cannot read the caller from the request as written below.

To read the caller’s identity in an operation, map the authorizer’s context onto a request header in your API construct, and read that header from the FastAPI Request.

infra ≠ http-ecs

When your API is protected by authentication, your route handlers often need to know who is calling. The generated FastAPI runs inside AWS Lambda via the Lambda Web Adapter, which forwards the API Gateway request context as JSON on the x-amzn-request-context header. You can read it from the FastAPI Request to extract the caller’s identity.

As an example, let’s add a /me endpoint that returns details about the calling user. We’ll implement the extraction as a FastAPI dependency so it can be reused across routes. The shape of the request context — and therefore how you extract the identity — depends on both your selected auth method and whether you deployed a REST or HTTP API.

auth = iam

For IAM authentication, we look up the caller in Cognito using the sub extracted from the API Gateway request context, which requires boto3. Add it to your API project:

Terminal window
pnpm nx run my-api:add boto3==1.44.15

Create identity.py alongside main.py:

import json
import os
from typing import Annotated
from boto3 import client
from fastapi import Depends, HTTPException, Request
from pydantic import BaseModel
cognito = client("cognito-idp")
class Identity(BaseModel):
sub: str
username: str
def get_identity(request: Request) -> Identity:
# The Lambda Web Adapter forwards the API Gateway request context as JSON
request_context_header = request.headers.get("x-amzn-request-context")
if not request_context_header:
raise HTTPException(status_code=403, detail="Unable to determine calling user")
request_context = json.loads(request_context_header)
provider = request_context.get("identity", {}).get("cognitoAuthenticationProvider")
sub = provider.split(":")[-1] if provider else None
if not sub:
raise HTTPException(status_code=403, detail="Unable to determine calling user")
users = cognito.list_users(
# Assumes user pool id is configured in lambda environment
UserPoolId=os.environ["USER_POOL_ID"],
Limit=1,
Filter=f'sub="{sub}"',
).get("Users", [])
if len(users) != 1:
raise HTTPException(status_code=403, detail=f"No user found with subjectId {sub}")
return Identity(sub=sub, username=users[0]["Username"])
CurrentUser = Annotated[Identity, Depends(get_identity)]
auth = cognito

With auth: 'cognito', the API Gateway Cognito User Pools authorizer verifies the JWT that the caller supplies in the Authorization header and places the verified claims on the request context.

Create identity.py alongside main.py:

import json
from typing import Annotated
from fastapi import Depends, HTTPException, Request
from pydantic import BaseModel
class Identity(BaseModel):
sub: str
username: str
def get_identity(request: Request) -> Identity:
# The Lambda Web Adapter forwards the API Gateway request context as JSON
request_context_header = request.headers.get("x-amzn-request-context")
if not request_context_header:
raise HTTPException(status_code=403, detail="Unable to determine calling user")
request_context = json.loads(request_context_header)
claims = request_context.get("authorizer", {}).get("claims", {})
sub = claims.get("sub")
username = claims.get("username")
if not sub or not username:
raise HTTPException(status_code=403, detail="Unable to determine calling user")
return Identity(sub=sub, username=username)
CurrentUser = Annotated[Identity, Depends(get_identity)]

You can then inject the CurrentUser dependency into any route that needs the caller’s identity:

from .identity import CurrentUser, Identity
from .init import app, tracer
@app.get("/me")
@tracer.capture_method
def me(identity: CurrentUser) -> Identity:
return identity
infra = rest-lambda

The generated FastAPI supports streaming responses out of the box when using a REST API. The infrastructure is configured to use the AWS Lambda Web Adapter to run your FastAPI via uvicorn inside Lambda, with ResponseTransferMode.STREAM in API Gateway for all REST API operations, which enables streaming to work alongside non-streaming operations.

The generated init.py exports a JsonStreamingResponse class that provides type-safe streaming with proper OpenAPI schema generation. This ensures that the connection generator can produce correctly typed streaming client methods.

from pydantic import BaseModel
from .init import app, JsonStreamingResponse
class Chunk(BaseModel):
message: str
async def generate_chunks():
for i in range(100):
yield Chunk(message=f"This is chunk {i}")
@app.post(
"/stream",
response_class=JsonStreamingResponse,
responses={200: JsonStreamingResponse.openapi_response(Chunk, "Stream of chunks")},
)
async def my_stream() -> JsonStreamingResponse:
return JsonStreamingResponse(generate_chunks())

The JsonStreamingResponse class:

  1. Serializes Pydantic models to JSON Lines format (application/jsonl)
  2. Provides an openapi_response helper that generates the correct OpenAPI schema with itemSchema, enabling the connection generator to produce type-safe streaming client methods

To consume a stream of responses, you can make use of the connection generator which will provide a type-safe method for iterating over your streamed chunks.

The FastAPI generator creates CDK or Terraform infrastructure as code based on your selected iac. You can use this to deploy your FastAPI.

infra ≠ http-ecs

The CDK construct for deploying your API in the common/constructs folder. You can use this in a CDK application:

import { MyApi } from '@my-scope/common-constructs';
export class ExampleStack extends Stack {
constructor(scope: Construct, id: string) {
// Add the api to your stack
const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
});
}
}

This sets up:

  1. An AWS Lambda function for each operation in the FastAPI application
  2. API Gateway HTTP/REST API as the function trigger
  3. IAM roles and permissions
  4. CloudWatch log group
  5. X-Ray tracing configuration
  6. CloudWatch metrics namespace
infra = http-ecs

defaultIntegrations takes the VPC your service runs in, and builds everything inside it: the ECS service, the internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through. The construct never creates a VPC, so you create or import one in your stack.

import { MyApi } from '@my-scope/common-constructs';
import { Stack } from 'aws-cdk-lib';
import { Vpc } from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';
export class ExampleStack extends Stack {
constructor(scope: Construct, id: string) {
super(scope, id);
const vpc = new Vpc(this, 'Vpc', { natGateways: 1 });
const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this, { vpc }).build(),
});
}
}

To use an existing VPC, look it up with Vpc.fromLookup(this, 'Vpc', { vpcId: '<vpc-id>' }) and pass it as vpc.

Pass service to change the container service itself — its cpu, memoryLimitMiB, desiredCount, environment, or grantTaskRole to give the task role a permission:

MyApi.defaultIntegrations(this, {
vpc,
service: {
cpu: 512,
memoryLimitMiB: 1024,
grantTaskRole: (taskRole) => myTable.grantReadWriteData(taskRole),
},
}).build();

This sets up an AWS API Gateway HTTP API with authentication based on your chosen auth method, an Amazon ECS service running your container, an internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through.

auth = cognito
auth = custom
infra = rest-lambda

For REST APIs, the generated construct associates an AWS WAFv2 Web ACL with the API Gateway stage by default. The Web ACL uses the AWS managed default ruleset (AWSManagedRulesCommonRuleSet and AWSManagedRulesKnownBadInputsRuleSet), providing protection against common web exploits including the OWASP Top 10. WAF request logs are written to a CloudWatch Logs group.

You can edit the generated rest-api construct to add, remove, or adjust rules (for example, to add rate-based rules or additional managed rule groups).

To opt out (for example, to attach your own Web ACL), set enableWaf to false:

const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
enableWaf: false,
});
infra = rest-lambda

For REST APIs, the generated infrastructure enables access logging by default, writing one structured JSON line per request to a dedicated CloudWatch Logs group. The log group is encrypted with a customer-managed KMS key and retained for one year.

API Gateway writes access logs using an account-level CloudWatch Logs role. This role is configured on the AWS::ApiGateway::Account setting, which is a singleton per region per account — there is only one role for every REST API in the region. To manage this safely across multiple independently-deployed stacks, the generated infrastructure:

  • Creates a shared CloudWatch Logs role and configures it on the account only when no working role is already set, so deployments never overwrite a role another stack owns.
  • Leaves the account setting untouched on teardown, so destroying one stack never disables logging for other REST APIs in the region.

The account role is managed by the ApiGatewayAccount construct, a stack-scoped singleton resolved via ApiGatewayAccount.ensure(scope). Each REST API’s stage depends on it, and the role is configured by a Lambda-backed custom resource.

The access log format is set by the RestApi construct your API extends. To customise it, pass deployOptions through to super in the generated packages/common/constructs/src/app/apis/my-api.ts, keeping the tracingEnabled the construct already sets:

packages/common/constructs/src/app/apis/my-api.ts
super(scope, id, {
apiName: 'MyApi',
// ...
deployOptions: {
tracingEnabled: true,
accessLogFormat: AccessLogFormat.clf(),
},
...props,
});

AccessLogFormat is imported from aws-cdk-lib/aws-apigateway. Anything you leave unset keeps the construct’s default — a JSON format with the standard fields.

By default your API is served from the endpoint API Gateway generates for it (https://<id>.execute-api.<region>.amazonaws.com/...). To serve it from your own domain instead, supply your domain name and an ACM certificate for it. The custom domain uses a regional endpoint by default, so the certificate must be in the same region as your API. A minimum TLS version of 1.2 is used by default.

When a custom domain is configured, the API’s URL in Runtime Configuration is the custom domain URL, so your website and other clients call your domain rather than the generated endpoint.

Pass the domain through to super in the generated packages/common/constructs/src/app/apis/my-api.ts:

infra = rest-lambda
packages/common/constructs/src/app/apis/my-api.ts
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
super(scope, id, {
apiName: 'MyApi',
// ...
domainName: {
domainName: 'api.example.com',
certificate: Certificate.fromCertificateArn(
scope,
'MyApiCertificate',
'arn:aws:acm:<region>:123456789012:certificate/...',
),
},
...props,
});

The API is served at the root of the domain, without the stage path prefix (/prod/). To serve it under a path instead, set basePath on domainName; the URL in runtime configuration includes it. basePath is only available in CDK; the Terraform module always serves the API at the root of the domain.

infra = http-lambda
packages/common/constructs/src/app/apis/my-api.ts
import { DomainName } from 'aws-cdk-lib/aws-apigatewayv2';
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
super(scope, id, {
apiName: 'MyApi',
// ...
defaultDomainMapping: {
domainName: new DomainName(scope, 'MyApiDomainName', {
domainName: 'api.example.com',
certificate: Certificate.fromCertificateArn(
scope,
'MyApiCertificate',
'arn:aws:acm:<region>:123456789012:certificate/...',
),
}),
},
...props,
});

When a custom domain is configured, the stack outputs MyApiDomainNameAlias, the domain name to point your DNS record at, and MyApiDomainNameAliasHostedZoneId.

Finally, create a DNS record for your domain. With any DNS provider, create a CNAME record pointing your domain at the domain name output above. If your domain is hosted in Route 53, you can create an alias record instead, using the hosted zone ID output, which also works at the zone apex (e.g. example.com).

The REST/HTTP API CDK constructs are configured to provide a type-safe interface for defining integrations for each of your operations.

You can use the static defaultIntegrations to make use of the default pattern, which defines an individual AWS Lambda function for each operation:

new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
});

You can access the underlying AWS Lambda functions via the API construct’s integrations property, in a type-safe manner. For example, if your API defines an operation named sayHello and you need to add some permissions to this function, you can do so as follows:

const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
});
// sayHello is typed to the operations defined in your API
api.integrations.sayHello.handler.addToRolePolicy(new PolicyStatement({
effect: Effect.ALLOW,
actions: [...],
resources: [...],
}));

If your API uses the shared pattern, the shared router Lambda is exposed as api.integrations.$router:

const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
});
api.integrations.$router.handler.addEnvironment('LOG_LEVEL', 'DEBUG');

Note that $router is no longer available if you override every operation via withOverrides, since no operation is left using the default router integration.

If you would like to customise the options used when creating the Lambda function for each default integration, you can use the withDefaultOptions method. For example, if you would like all of your Lambda functions to reside in a Vpc:

const vpc = new Vpc(this, 'Vpc', ...);
new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this)
.withDefaultOptions({
vpc,
})
.build(),
});

To customise the options used to create the default integration for specific operations (without affecting the others), you can use the withOperationOptions method. For example, if you would like to increase the Lambda function timeout for just one operation:

const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this)
.withOperationOptions({
sayHello: {
timeout: Duration.seconds(60),
},
})
.build(),
});
// The selected operations remain default integrations, so they're still typed accordingly:
api.integrations.sayHello.handler.addToRolePolicy(new PolicyStatement({ ... }));

The options you specify are merged with the default integration options (and any options set via withDefaultOptions). Note that you cannot specify options for operations which you have replaced via withOverrides, since these no longer use the default integration.

You will encounter a type error if the same operation is targeted by both withOperationOptions and withOverrides, regardless of the order in which you call them.

You can also override integrations for specific operations using the withOverrides method. Each override must specify an integration property which is typed to the appropriate CDK integration construct for the HTTP or REST API. The withOverrides method is also type-safe. For example, if you would like to override a getDocumentation API to point to documentation hosted by some external website you could achieve this as follows:

new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this)
.withOverrides({
getDocumentation: {
integration: new HttpIntegration('https://example.com/documentation'),
},
})
.build(),
});

You will also notice that the overridden integration no longer has a handler property when accessing it via api.integrations.getDocumentation.

You can add additional properties to an integration which will also be typed accordingly, allowing for other types of integration to be abstracted but remain type-safe, for example if you have created an S3 integration for a REST API and later wish to reference the bucket for a particular operation, you can do so as follows:

const storageBucket = new Bucket(this, 'Bucket', { ... });
const apiGatewayRole = new Role(this, 'ApiGatewayS3Role', {
assumedBy: new ServicePrincipal('apigateway.amazonaws.com'),
});
storageBucket.grantRead(apiGatewayRole);
const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this)
.withOverrides({
getFile: {
bucket: storageBucket,
integration: new AwsIntegration({
service: 's3',
integrationHttpMethod: 'GET',
path: `${storageBucket.bucketName}/{fileName}`,
options: {
credentialsRole: apiGatewayRole,
requestParameters: {
'integration.request.path.fileName': 'method.request.querystring.fileName',
},
integrationResponses: [{ statusCode: '200' }],
},
}),
options: {
requestParameters: {
'method.request.querystring.fileName': true,
},
methodResponses: [{
statusCode: '200',
}],
}
},
})
.build(),
});
// Later, perhaps in another file, you can access the bucket property we defined
// in a type-safe manner
api.integrations.getFile.bucket.grantRead(...);

You can also supply options in your integration to override particular method options such as authorizers, for example if you wished to use Cognito authentication for your getDocumentation operation:

new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this)
.withOverrides({
getDocumentation: {
integration: new HttpIntegration('https://example.com/documentation'),
options: {
authorizer: new CognitoUserPoolsAuthorizer(...) // for REST, or HttpUserPoolAuthorizer for an HTTP API
}
},
})
.build(),
});

If you prefer, you can choose not to use the default integrations and instead directly supply one for each operation. This is useful if, for example, each operation needs to use a different type of integration or you would like to receive a type error when adding new operations:

new MyApi(this, 'MyApi', {
integrations: {
sayHello: {
integration: new LambdaIntegration(...),
},
getDocumentation: {
integration: new HttpIntegration(...),
},
},
});

Generated APIs support two integration patterns:

  • isolated creates one Lambda function per operation. This is the default and recommended option for APIs.
  • shared creates a single default router Lambda and reuses it for every operation unless you override specific integrations.

isolated gives you finer-grained permissions and configuration per operation, as well as better separation for logs and traces. shared reduces the likelihood of encountering cold-starts for low-usage APIs.

The integration pattern can be changed at any time in CDK by updating your API construct. For example, setting pattern to 'shared' creates a single function instead of one per integration:

packages/common/constructs/src/app/apis/my-api.ts
export class MyApi<...> extends ... {
public static defaultIntegrations = (scope: Construct) => {
...
return IntegrationBuilder.rest({
pattern: 'shared',
...
});
};
}
iac = terraform, infra = rest-lambda

Since operations in FastAPI are defined in Python and CDK infrastructure in TypeScript, we instrument code-generation to supply metadata to the CDK construct to provide a type-safe interface for integrations.

A generate:<ApiName>-metadata target is added to the common constructs project.json to facilitate this code generation, which emits a file such as packages/common/constructs/src/generated/my-api/metadata.gen.ts. Since this is generated at build time, it is ignored in version control.

auth = iam

If you selected to use IAM authentication, you can use the grantInvokeAccess method to grant access to your API:

api.grantInvokeAccess(myIdentityPool.authenticatedRole);

The generator configures a local development server that you can run with:

Terminal window
pnpm nx serve <project-name>
infra ≠ http-ecs

This starts a local FastAPI development server with:

  • Auto-reload on code changes
  • Interactive API documentation at /docs or /redoc
  • OpenAPI schema at /openapi.json
infra = http-ecs

This starts the container’s entry point, the same file the image runs, with:

  • GET /health, answering as it does for the load balancer
  • Interactive API documentation at /docs or /redoc
  • OpenAPI schema at /openapi.json

The server binds 127.0.0.1, so it answers only on your own machine. It reloads nothing: restart it to pick up a code change. To reach it from another machine, a VM or a container, set HOST=0.0.0.0 on the serve target — which makes the API reachable by anything that can reach your machine, unauthenticated.

infra = http-ecs

With infra set to http-ecs, your API runs as a long-lived uvicorn server in a container rather than in a Lambda function behind the Lambda Web Adapter. A request takes this path:

  1. A caller signs a request to the API Gateway HTTP API, which is the only public entry point. Every route carries the authorizer for the auth you chose, so an unauthenticated request is rejected at the edge.
  2. API Gateway forwards the request through a VPC link, which is its private path into your VPC.
  3. The VPC link reaches an internal load balancer. The load balancer has no public address, and its only inbound rule allows the VPC link’s security group on the listener port.
  4. The load balancer forwards the request to a task. The tasks’ only inbound rule allows the load balancer’s security group on the container port, so nothing else in the VPC can open a connection to them.

The tasks run in private subnets and never get a public IP address. Nothing in this path allows an address range inbound.

By default the service, the load balancer and the VPC link go in the VPC’s PRIVATE_WITH_EGRESS subnets, which reach AWS through a NAT gateway. Passing vpcSubnets: { subnetType: SubnetType.PRIVATE_ISOLATED } to defaultIntegrations drops the NAT gateway and its hourly charge, but isolated subnets have no route out, so the VPC then needs four VPC endpoints for the tasks to start at all: interface endpoints for ecr.api and ecr.dkr to pull the image, an S3 gateway endpoint because the image layers are S3 objects, and an interface endpoint for logs so the awslogs driver can write. Without them a task cannot pull its image and ECS rolls the deployment back on the circuit breaker without saying why.

The VPC link, the load balancer, its listener, the target group and the bucket the load balancer writes its access logs to are created by one construct, core/api/ecs-http-endpoint.ts in common/constructs, which every API hosted on ECS shares. Your API’s own construct names its container service and routes every operation to that endpoint.

<module_name>/<api_name>_container/main.py imports the app from your main.py, so every operation you write is served exactly as it is on Lambda. It adds two things of its own:

  • GET /health, which the load balancer’s target group and the container health check call. It is declared include_in_schema=False, so it stays out of your OpenAPI spec and therefore out of the API Gateway routes and the generated clients. It is also left out of the request metrics, so the target group’s call every 15 seconds does not count as an API request.
  • A middleware that writes out the metrics the API’s own middleware collects. On Lambda the handler does that at the end of each invocation; this server lives across requests, so it flushes them itself.

The API Gateway routes still come from your OpenAPI spec, so an operation you add is deployed once nx build has regenerated the spec.

Logs and metrics work as they do on Lambda: the container writes to its own CloudWatch log group, and metrics are written in the embedded metric format for CloudWatch Logs to extract.

One thing about metrics is different here, and it is worth knowing before you read a dashboard or add a metric of your own. metrics, the object the Metrics section above tells you to import from .init, is a Powertools Metrics, and every Metrics object in a process shares one metric store. On Lambda one invocation owns that store from start to finish. A uvicorn server handles requests at the same time, and both the API’s own per-request metrics and any you add go to that one store, so two requests in flight together can have their metrics written out in one document and attributed to whichever route was added first. The other request’s document can come out with no route dimension at all, holding only the metrics added after the first flush, and Powertools logs PowertoolsUserWarning: Dimension 'route' has already been added when it happens. Under light traffic, where requests rarely overlap, you will not see it.

So treat RequestCount and Success per route as approximate on ECS. If you need a metric attributed to exactly one request, add it to an EphemeralMetrics you create in the request and flush before returning, which keeps a store of its own:

from aws_lambda_powertools.metrics import EphemeralMetrics, MetricUnit
@app.get("/items/{item_id}")
def read_item(item_id: int):
request_metrics = EphemeralMetrics()
request_metrics.add_metric(name="ItemViewed", unit=MetricUnit.Count, value=1)
request_metrics.flush_metrics()
return {"item_id": item_id}

AWS X-Ray tracing does not. @tracer.capture_method is a no-op outside Lambda, and there is no X-Ray daemon in the task to receive segments either. Add one as a sidecar in your container service if you need traces.

The API Gateway HTTP API’s access log records every request that reaches the API. The load balancer writes its own access logs to a bucket the EcsHttpEndpoint construct creates, which is where you can see which task served a request and what it answered.

The container generator vends the image targets, named after your API:

  • <api-name>-container-docker builds an image for the CPU architecture in the architecture option, linux/arm64 or linux/amd64. The option defaults to the architecture of the machine you run the generator on, and you set it with --architecture. The target runs the matching bundle target first, bundle-arm or bundle-x86, so the image holds your package and its dependencies built for that architecture.
  • <api-name>-container-trivy scans that image for vulnerabilities.

See Python Container Service for how the image is built, and Docker Bundling for how it is published at deploy time.

deploy-sandbox deploys in CloudFormation express mode, which returns once each resource’s configuration is applied rather than waiting for the ECS service to reach a steady state. So the target can finish while the first task is still starting, and until a task has passed two health checks fifteen seconds apart the load balancer has no target to send a request to and answers 503. Expect about a minute of that after the deploy returns. Wait a minute or two and call again. A 503 that never clears is a real failure rather than a slow start: the service’s deployment circuit breaker rolls it back when no task becomes healthy.

ECS runs a health check of its own inside the container. It calls GET /health every 30 seconds, and failures in the first 30 seconds after a task starts do not count against it. Until that check first reports, aws ecs describe-tasks gives the task a healthStatus of UNKNOWN, which turns to HEALTHY once it passes. UNKNOWN means the check has not reported yet rather than that it failed.

The API’s URL is a stack output, but not under the name you would guess. The CfnOutput is created inside your API construct and nothing overrides its logical ID, so CDK builds the output key from the construct’s path plus an eight-character hash: an API added as new MyApi(this, 'MyApi', …) outputs MyApiMyApiUrl and that hash, not MyApiUrl. cdk deploy prints the value, and a script should match on the suffix rather than the whole key:

Terminal window
aws cloudformation describe-stacks --stack-name <stack-name> \
--query "Stacks[0].Outputs[?contains(OutputKey, 'Url')].OutputValue" --output text

destroy-sandbox leaves the HTTP API’s access log group and the customer-managed KMS key that encrypts it behind. Neither sets a removal policy, so CDK’s default of Retain applies and CloudFormation skips them rather than deleting them. List them before you tear the stack down, since a deleted stack no longer reports its resources:

Terminal window
aws cloudformation describe-stack-resources --stack-name <stack-name> \
--query "StackResources[?contains(LogicalResourceId, 'AccessLogs') && (ResourceType=='AWS::Logs::LogGroup' || ResourceType=='AWS::KMS::Key')].[ResourceType,PhysicalResourceId]" \
--output text

Then remove them with aws logs delete-log-group --log-group-name <log-group-name> and aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7, seven days being the shortest window KMS accepts.

API Gateway accepts one VPC link deletion every 30 seconds per account, and that quota cannot be raised. Every http-ecs API in a stack that uses the same VPC shares one VPC link, so a stack deletes a single link however many of these APIs it holds. Nothing is shared across a stack boundary, and a nested stack counts as its own stack, so stacks torn down at the same time in one account can still clash. If a stack ends in DELETE_FAILED on a VPC link, wait 30 seconds and delete the stack again.

Upgrading from a release that gave each API its own link needs one check, if the stack already deployed three or more of these APIs on one VPC. The next deploy keeps the first API’s link and deletes the others in a single cleanup phase, so the second deletion goes out seconds after the first and API Gateway throttles it. The stack events then show DELETE_FAILED on a VPC link and on its security group, which cannot be deleted while the link still uses it, and the update takes about 20 minutes longer while CloudFormation retries both in the same cleanup. It deletes them on a later attempt and the update ends UPDATE_COMPLETE. Once it has completed, check the stack events, or the VPC links list in the API Gateway console, for a link still in DELETE_FAILED. Wait 30 seconds and delete any link in that state, then its security group. A link left behind counts against the ten-per-Region quota until it is gone; its security group does not.

  • Integration timeout. API Gateway HTTP APIs cap an integration at about 30 seconds. An operation that takes longer than that fails at the gateway however long the container keeps working.
  • No streaming. Streaming operations need the rest-lambda infrastructure. An HTTP API cannot stream a response.
  • Payload size. Requests and responses follow API Gateway’s 10 MB limit.
  • VPC links per Region. API Gateway allows ten VPC links per account per Region, raisable through Service Quotas. APIs sharing a stack and a VPC share one link, so what counts against the quota is stacks and VPCs rather than APIs.
  • One service for every operation. integrationPattern is shared: there is one container service, and every route is routed to it. The option always resolves to shared for this infrastructure, and isolated is ignored with a warning.

The load balancer is the new fixed cost compared with Lambda, where you pay per request and nothing when idle. Rough monthly figures in us-east-1, before data transfer:

ItemApproximately
Internal load balancer$16 plus load balancer capacity units
Fargate task, 0.25 vCPU / 0.5 GB$7 per task on ARM64, and more on X86_64, which Fargate bills at a higher rate per vCPU and per GB
NAT gateway, if your VPC has one$33
VPC linkno hourly charge
S3 storage for the load balancer’s access logscents per GB a month

So a one-task service costs roughly $23 a month on ARM64 before any traffic, and more if the VPC you pass in has a NAT gateway. The access logs grow with traffic: add a lifecycle rule to endpoint.accessLogsBucket to expire them. Check the Elastic Load Balancing and AWS Fargate pricing pages for current prices in your Region.

To invoke your API from a React website, you can use the connection generator.

Use the connection generator to integrate this project with others in your workspace. The following connections involve this project:

FastAPI
React to FastAPICall a Python FastAPI from a React website
FastAPIAmazon DynamoDBPython
FastAPI to Python DynamoDBConnect a FastAPI to a DynamoDB table