Skip to content

FastAPI to Relational Database

The connection generator wires a FastAPI to a Python Relational Database project, injecting a typed SQLModel session into your route handlers via a FastAPI dependency.

Before using this generator, ensure you have:

  1. A FastAPI project (generated with py#api --framework=fastapi), see the py#api guide
  2. A py#rdb project

Run this generator@aws/nx-plugin:connection

pnpm nx g @aws/nx-plugin:connection
Build your command5

Required

Required

Select your FastAPI project as the source and your relational database project as the target.

Generator Options5 options
sourceProjectRequiredstring

The source project

targetProjectRequiredstring

The target project to connect to

sourceComponentstring

The source component to connect from (component name, path relative to source project root, or generator id). Use '.' to explicitly select the project as the source.

targetComponentstring

The target component to connect to (component name, path relative to target project root, or generator id). Use '.' to explicitly select the project as the target.

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.

The generator modifies your FastAPI project:

  • Directorypackages/my_api
    • project.json Adds a dependency from dev on the database’s dev target
    • pyproject.toml Adds the database package as a workspace dependency
    • Directorymy_api
      • Directorydependencies
        • my_db.py FastAPI MyDbSession dependency for the database session

This generator configures an injectable FastAPI Dependency which you can use in your route handlers:

packages/my_api/my_api/api.py
from sqlmodel import select
from my_api.dependencies.my_db import MyDbSession
from my_scope_my_db.models.example import ExampleModel
@app.get("/examples")
async def list_examples(my_db: MyDbSession):
return (await my_db.execute(select(ExampleModel))).scalars().all()
@app.post("/examples")
async def create_example(name: str, my_db: MyDbSession):
item = ExampleModel(name=name)
my_db.add(item)
await my_db.commit()
await my_db.refresh(item)
return item

FastAPI automatically opens a new session per request and closes it when the handler returns.

To allow the FastAPI Lambda function to connect to the database at runtime, it must be deployed into the same VPC as the database and granted network and IAM access.

In your application stack, deploy the API into the same VPC as the database, then call allowDefaultPortFrom and grantConnect to open the network path and grant IAM rds-db:connect permission to the Lambda handler:

packages/infra/src/stacks/application-stack.ts
import { MyDatabase } from '@my-scope/common-constructs';
const db = new MyDatabase(this, 'Db', { vpc, ... });
const api = new MyApi(this, 'Api', {
integrations: MyApi.defaultIntegrations(this)
.withDefaultOptions({
vpc,
vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS },
})
.build(),
});
Object.entries(api.integrations).forEach(([operation, integration]) => {
db.allowDefaultPortFrom(integration.handler, `Allow ${operation} to connect to the database`);
db.grantConnect(integration.handler);
});

Deploy the API Lambda functions into a private subnet with egress, not a private isolated subnet. At runtime, session_context() retrieves database configuration from AWS AppConfig, which is a public AWS service endpoint that requires outbound internet access.

SSL Requirements When Connecting Without RDS Proxy

Section titled “SSL Requirements When Connecting Without RDS Proxy”

The Amazon Linux 2023 Lambda execution environment’s built-in CA trust store includes the Amazon Root CAs used by RDS, so no additional configuration is needed.

When using RDS Proxy, you do not need to configure the RDS CA bundle in your Lambda function.

Terminal window
pnpm nx dev <project-name>

This starts the FastAPI and all connected databases. The LOCAL_DEV=true environment variable causes the database client to connect to its local Docker database instead of Aurora.