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-versionorruntime.txt. Without either, Python 3.12 is assumed. - Port. Python apps are assumed to listen on port 8000. Launchpad sets the
PORTvariable to the app's port, so read$PORTrather 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
- Create the project and a virtual environment:
mkdir example-api && cd example-api
python3.12 -m venv .venv
source .venv/bin/activate
echo "3.12" > .python-version- Create
requirements.txt. These ranges keep you on current major versions; runpip freezelater if you want exact pins:
fastapi>=0.115,<1
uvicorn[standard]>=0.30
sqlalchemy>=2.0,<3
psycopg[binary]>=3.2,<4
alembic>=1.13pip install -r requirements.txt- Create
db.py. It holds the database connection and the model, so both the app and Alembic can import it:
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()
)- Create
main.py:
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 rowThe routes are plain def functions. FastAPI runs them in a thread pool, which suits the synchronous SQLAlchemy session and keeps the code simple.
- Create the
Procfile(no file extension):
web: uvicorn main:app --host 0.0.0.0 --port $PORT- Add
.gitignoreand.env.example:
.venv/
__pycache__/
.envDATABASE_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
- Initialise Alembic in the project folder:
alembic init migrations- Open
migrations/env.pyand replace the linetarget_metadata = Nonewith:
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- Start a local PostgreSQL (for example with Docker), then generate and apply the first migration:
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- 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:
web: alembic upgrade head && uvicorn main:app --host 0.0.0.0 --port $PORTIf 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:
- Push the project to GitHub. In Launchpad, choose Deploy from GitHub and connect the repository.
- Use Step-by-step setup to check what was detected: Python 3.12,
pip install -r requirements.txtas the install command and your Procfile line as the start command. Set Health check path to/health. - Deploy. If you are warned that
DATABASE_URLhas 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_URLis added for you. - 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:
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.--reloadin production. It watches files and restarts on changes. Fix: use it only locally.- Using
postgres://directly. SQLAlchemy raisesNoSuchModuleError. 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_URLand API keys in Variables, which are encrypted and never written to logs. Don't commit.env. - Validate input with Pydantic models, as
NoteIndoes, and set length limits on strings that reach the database. - FastAPI publishes interactive docs at
/docs. For a private API, disable them withFastAPI(docs_url=None, redoc_url=None, openapi_url=None). - Use SQLAlchemy queries or bound parameters; never format SQL strings with user input.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| "We couldn't tell how to start this Python app" | No Procfile, or no web: line | Add Procfile at the top level |
| Deploy fails the health check | Wrong host or port, or the path returns 404 | Use --host 0.0.0.0 --port $PORT; set the path to /health |
NoSuchModuleError: postgres | Raw platform URL passed to SQLAlchemy | Use database_url() |
relation "notes" does not exist | Migrations not run | Use the Procfile with alembic upgrade head |
connection refused on localhost:5432 | DATABASE_URL missing on Launchpad | Connect 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.
- PostgreSQL vs MySQL: choosing a database
- CI/CD with GitHub Actions: test before you deploy
- Deployments, logs and rollbacks
- Deploy your first app
- Ready to put it online? Deploy it on Launchpad.




