Skip to content

Deployment · By Rivtor · Updated

Deploy FastAPI with Postgres and Alembic

Run FastAPI with an ASGI server, load the Postgres URL from environment configuration and apply reviewed Alembic migrations before releasing code that expects a new schema.

See the Rivtor deployment workflow →

Package the right runtime

Include FastAPI, the ASGI server, database driver and migration tools in the API dependency manifest. Check that the module path in the server command matches the deployed directory. Import errors often come from a different working directory or a package omitted from runtime dependencies.

Match the connection to the driver

Read DATABASE_URL rather than hardcoding a local database. An asynchronous SQLAlchemy engine and a synchronous driver are not interchangeable; configure the URL scheme for the library actually installed. Never print the full connection string to diagnose a missing setting.

Keep migration history complete

Commit all Alembic revisions and confirm the environment configuration reads the intended database URL. Review destructive operations separately. Automatically running a migration does not establish that the operation preserves existing customer data or that a useful recovery point exists.

Check API behavior after release

Test health, request validation and a database-backed operation using synthetic data. If a frontend calls the API from a different origin, configure that origin explicitly in CORS. Authentication and record ownership checks remain necessary even when browser requests succeed.

Command reference

uvicorn main:app --host 0.0.0.0 --port 8000

These commands illustrate the documented workflow. Replace example addresses and identifiers with your own. Deployment and migration commands affect the selected project; confirm the target before running them.

Example API and dependency boundaries

Start with an API directory containing main.py, requirements.txt and committed Alembic configuration. Your dependencies need to include FastAPI, Uvicorn, SQLAlchemy, Alembic and the Postgres driver selected by the application. Pin compatible versions in your own dependency workflow.

import os
from fastapi import FastAPI
from sqlalchemy import create_engine, text

engine = create_engine(
    os.environ["DATABASE_URL"],
    pool_pre_ping=True,
    pool_size=3,
    max_overflow=2,
)
app = FastAPI()

@app.get("/health")
def health():
    with engine.connect() as connection:
        connection.execute(text("SELECT 1"))
    return {"ok": True}

This synchronous example assumes a SQLAlchemy-compatible synchronous driver URL. For psycopg 3, that normally means the postgresql+psycopg scheme. An asyncpg URL needs an asynchronous engine and awaited calls instead. Keep the full connection string out of error responses.

Apply schema changes as a release step

For an Alembic project, configure env.py to obtain the database URL from the server environment. Review the revision before applying it to a selected database:

alembic current
alembic heads
alembic upgrade head

The final command changes that database. Rehearse it on a disposable copy before a production release. Multiple heads, a missing parent revision and a connection failure are different conditions. Do not stamp a database or delete revisions merely to silence an error.

A health response from SELECT 1 cannot tell you whether a customer table has the expected columns. Add a synthetic request that exercises the schema used by your API. Read the failed migration guide when a release stops at this stage.

Diagnose startup versus request failures

Run Uvicorn with a module path that exists relative to the API service root. A bind to 127.0.0.1 only accepts local connections; use the listener settings required by your host. The error “could not import module” usually needs an entrypoint or dependency fix, while “connection refused” requires checking the destination and network path.

A healthy API that returns a browser CORS error needs the CORS investigation, rather than a change to database credentials. For the supported framework and data configuration, see Rivtor framework detection and data services.

Deployment questions

Does creating an engine create my tables?

No. An engine manages database connections. Alembic revisions or another explicit schema workflow must create and evolve application tables.

Can I use a local SQLite file unchanged?

A hosted Postgres database has a different driver, URL and SQL behavior. Exercise queries and migrations against Postgres before moving application data.

Sources: FastAPI deployment, SQLAlchemy engines, and Alembic tutorial.

Next steps

Read the Rivtor reference for supported configuration and limitations, and use the deployment quickstart when trying Rivtor for the first time. Validate workflows with synthetic data before connecting valuable production records.