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 py#fast-api project
  2. A py#rdb project
  1. Install the Nx Console VSCode Plugin if you haven't already
  2. Open the Nx Console in VSCode
  3. Click Generate (UI) in the "Common Nx Commands" section
  4. Search for @aws/nx-plugin - connection
  5. Fill in the required parameters
    • Click Generate

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

    ParameterTypeDefaultDescription
    sourceProject Requiredstring-The source project
    targetProject Requiredstring-The target project to connect to
    sourceComponent string-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.
    targetComponent string-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.
    preferInstallDependencies booleantrueWhether 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))).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.

    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.