Deploy a Python FastAPI app with PostgreSQL

Build a small FastAPI service with SQLAlchemy 2 and Alembic, then run it with uvicorn on Launchpad from GitHub or a zip file.

A terracotta lightning bolt standing on a stack of cream discs

FastAPI makes it quick to build an API. Putting it online is where small details bite: the start command, the port, the database driver name and the order in which migrations run.

This tutorial is for Python developers who want a FastAPI service backed by PostgreSQL running in production. You will build a small notes API, manage its schema with Alembic, and deploy it to Launchpad either from GitHub or by uploading a zip file.

The code assumes Python 3.12, FastAPI 0.115 or later, SQLAlchemy 2.x, psycopg 3 and Alembic 1.13 or later.

How Launchpad runs a Python app

Launchpad recognises a Python project from requirements.txt (or pyproject.toml). It has default start commands for Django and Flask, but FastAPI is not one of them, so you must say how to start the app. You do that with a Procfile containing a web: line.

Three other things matter:

  • Python version. Read from .python-version or runtime.txt. Without either, Python 3.12 is assumed.
  • Port. Python apps are assumed to listen on port 8000. Launchpad sets the PORT variable to the app's port, so read $PORT rather than hard-coding a number.
  • Health check. A deploy only goes live after the health check path answers with a 2xx status. The default path is /, so either serve / or change the path to /health.

Step by step: build the app

  1. Create the project and a virtual environment:
Terminal
mkdir example-api && cd example-api
python3.12 -m venv .venv
source .venv/bin/activate
echo "3.12" > .python-version
  1. Create requirements.txt. These ranges keep you on current major versions; run pip freeze later if you want exact pins:
Text
fastapi>=0.115,<1
uvicorn[standard]>=0.30
sqlalchemy>=2.0,<3
psycopg[binary]>=3.2,<4
alembic>=1.13
Terminal
pip install -r requirements.txt
  1. Create db.py. It holds the database connection and the model, so both the app and Alembic can import it:
Python
import os
from datetime import datetime

from sqlalchemy import DateTime, String, create_engine, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker


def database_url() -> str:
    url = os.environ.get("DATABASE_URL", "postgresql://postgres:postgres@localhost:5432/app")
    # SQLAlchemy needs the driver in the scheme: postgresql+psycopg://
    for prefix in ("postgres://", "postgresql://"):
        if url.startswith(prefix):
            return "postgresql+psycopg://" + url.removeprefix(prefix)
    return url


engine = create_engine(database_url(), pool_size=5, max_overflow=5, pool_pre_ping=True)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)


class Base(DeclarativeBase):
    pass


class Note(Base):
    __tablename__ = "notes"

    id: Mapped[int] = mapped_column(primary_key=True)
    body: Mapped[str] = mapped_column(String(500))
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
  1. Create main.py:
Python
from collections.abc import Iterator
from datetime import datetime

from fastapi import Depends, FastAPI
from pydantic import BaseModel, ConfigDict
from sqlalchemy import select
from sqlalchemy.orm import Session

from db import Note, SessionLocal


class NoteIn(BaseModel):
    body: str


class NoteOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    body: str
    created_at: datetime


def get_db() -> Iterator[Session]:
    with SessionLocal() as session:
        yield session


app = FastAPI(title="Example API")


@app.get("/")
def index() -> dict[str, str]:
    return {"message": "Example API"}


@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}


@app.get("/notes", response_model=list[NoteOut])
def list_notes(db: Session = Depends(get_db)):
    return db.scalars(select(Note).order_by(Note.id.desc()).limit(50)).all()


@app.post("/notes", response_model=NoteOut, status_code=201)
def create_note(note: NoteIn, db: Session = Depends(get_db)):
    row = Note(body=note.body)
    db.add(row)
    db.commit()
    db.refresh(row)
    return row

The routes are plain def functions. FastAPI runs them in a thread pool, which suits the synchronous SQLAlchemy session and keeps the code simple.

  1. Create the Procfile (no file extension):
Text
web: uvicorn main:app --host 0.0.0.0 --port $PORT
  1. Add .gitignore and .env.example:
Text
.venv/
__pycache__/
.env
Config
DATABASE_URL=

Why the URL conversion matters

Connection strings from hosting platforms usually start with postgres:// or postgresql://. SQLAlchemy 2 rejects postgres:// outright, and for postgresql:// it picks the psycopg2 driver, which you haven't installed. Rewriting the scheme to postgresql+psycopg:// tells it to use psycopg 3.

The function only touches the prefix, so usernames, passwords and query options such as ?sslmode=require pass through unchanged. Pass the result to create_engine as a string. If you ever build a URL object instead, don't call str() on it: SQLAlchemy 2 hides the password in that output.

Step by step: migrations with Alembic

  1. Initialise Alembic in the project folder:
Terminal
alembic init migrations
  1. Open migrations/env.py and replace the line target_metadata = None with:
Python
from db import Base, database_url

# Escape % so Alembic's config parser accepts URL-encoded passwords
config.set_main_option("sqlalchemy.url", database_url().replace("%", "%%"))
target_metadata = Base.metadata
  1. Start a local PostgreSQL (for example with Docker), then generate and apply the first migration:
Terminal
docker run --name pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=app -p 5432:5432 -d postgres:17
alembic revision --autogenerate -m "create notes"
alembic upgrade head
uvicorn main:app --reload
  1. Review the generated file in migrations/versions/ before committing it. Autogenerate is a helper, not an oracle.

To run migrations on Launchpad, change the Procfile so they run before the server starts:

Text
web: alembic upgrade head && uvicorn main:app --host 0.0.0.0 --port $PORT

If a migration fails, the app never starts, the health check fails, and the previous version keeps serving traffic. Because the old version is still running while the new one migrates, keep migrations backwards compatible: add columns before code uses them, and remove them in a later release.

Step by step: deploy on Launchpad

From GitHub:

  1. Push the project to GitHub. In Launchpad, choose Deploy from GitHub and connect the repository.
  2. Use Step-by-step setup to check what was detected: Python 3.12, pip install -r requirements.txt as the install command and your Procfile line as the start command. Set Health check path to /health.
  3. Deploy. If you are warned that DATABASE_URL has no value, deploy anyway (with the migrations Procfile, this first deploy fails until the database exists, which is expected). Then open the app's Databases tab, choose New database, pick PostgreSQL and keep Connect it to this app ticked. DATABASE_URL is added for you.
  4. Press Redeploy now. The Procfile runs the migrations and starts uvicorn.

From a zip file: zip the contents of the folder so requirements.txt and Procfile sit at the top level:

Terminal
zip -r ../example-api.zip . -x ".venv/*" "*__pycache__*" ".env" ".git/*"

Then choose Upload files, upload the zip and follow steps 3 and 4. .env files are skipped anyway. The upload guide covers publishing new versions.

Common mistakes

  • No Procfile. FastAPI is not auto-detected like Django or Flask, so there is no start command. Fix: add the web: line.
  • --host 127.0.0.1 (uvicorn's default). The health check can't connect. Fix: --host 0.0.0.0.
  • --reload in production. It watches files and restarts on changes. Fix: use it only locally.
  • Using postgres:// directly. SQLAlchemy raises NoSuchModuleError. Fix: convert the scheme as shown.
  • Calling Base.metadata.create_all() on start-up. It never alters existing tables. Fix: let Alembic own the schema.

Security notes

  • Keep DATABASE_URL and API keys in Variables, which are encrypted and never written to logs. Don't commit .env.
  • Validate input with Pydantic models, as NoteIn does, and set length limits on strings that reach the database.
  • FastAPI publishes interactive docs at /docs. For a private API, disable them with FastAPI(docs_url=None, redoc_url=None, openapi_url=None).
  • Use SQLAlchemy queries or bound parameters; never format SQL strings with user input.

Troubleshooting

SymptomCauseFix
"We couldn't tell how to start this Python app"No Procfile, or no web: lineAdd Procfile at the top level
Deploy fails the health checkWrong host or port, or the path returns 404Use --host 0.0.0.0 --port $PORT; set the path to /health
NoSuchModuleError: postgresRaw platform URL passed to SQLAlchemyUse database_url()
relation "notes" does not existMigrations not runUse the Procfile with alembic upgrade head
connection refused on localhost:5432DATABASE_URL missing on LaunchpadConnect the database, then Redeploy now

Frequently asked questions

Should I use gunicorn instead of uvicorn?

For a small service, plain uvicorn is fine. To use more CPU cores, add --workers 2 to the uvicorn command. Each worker is a separate process with its own memory and connection pool, so size the pool to match.

Can I use async SQLAlchemy?

Yes. psycopg 3 supports async, so you would use create_async_engine with the same postgresql+psycopg:// URL and async def routes. The sync version above is easier to reason about and fast enough for most apps.

Does this work with pyproject.toml instead of requirements.txt?

Launchpad detects pyproject.toml too. A requirements.txt is the simplest route for zip uploads.

Is the database backed up?

Connected PostgreSQL databases are backed up daily. See Back up and restore.

Next steps

You now have a FastAPI service that starts on the right port, migrates its own schema and reports its health. From here, add tests and a custom domain.

Share this articleLinkedIn (opens in a new tab)X (opens in a new tab)Facebook (opens in a new tab)
Was this article helpful?

Get new guides in your inbox.

One email a month. Unsubscribe anytime.