Deploying a FastAPI Application with PostgreSQL: A Practical Step-by-Step Guide

spyboy's avatarPosted by

Introduction

Building a Python REST API locally is only half the job. Taking it from your laptop to a live, HTTPS-secured endpoint backed by a managed PostgreSQL database is where extra friction usually appears: choosing a runtime, configuring an application server, provisioning a database, and passing credentials securely between services.

In this walkthrough, we’ll build seenode-demo-api—a clean Task Manager REST API using FastAPI, SQLAlchemy, and PostgreSQL—and take it all the way from local development to a live HTTPS deployment. For hosting both the Python service and the managed PostgreSQL database in one workspace, we’ll use Seenode, which lets you deploy directly from a Git repository or Docker image without managing servers or TLS certificates manually.

This is a focused demonstration project designed to walk through the complete build, database wiring, deployment, and troubleshooting workflow step by step.

What We’re Building

The demo is a REST API that creates and retrieves tasks stored in PostgreSQL. It is intentionally small, but it exercises the important parts of a typical backend deployment: application startup, database connectivity, inserts, queries, and API responses.

EndpointPurpose
GET /Returns a welcome message and links to the documentation and health endpoint
GET /healthRuns SELECT 1 to check database connectivity
POST /tasksCreates a task
GET /tasksLists tasks
GET /tasks/{task_id}Retrieves one task by ID
DELETE /tasks/{task_id}Deletes a task by ID
GET /docsOpens FastAPI’s interactive Swagger UI

Technology stack

  • Python 3.14 — runtime used for the deployed service
  • FastAPI and Uvicorn — API framework and ASGI application server
  • SQLAlchemy 2.1.9 — database toolkit and ORM version resolved during deployment
  • psycopg2-binary — PostgreSQL driver used by the application
  • PostgreSQL 18.6 — managed database instance
  • GitHub — source-code hosting and deployment source

The complete demo source code is available in the seenode-demo-api GitHub repository.

Before You Start

You will need:

  • A GitHub account and a repository containing your Python application.
  • A Seenode account (with a 7-day free trial, no credit card required).
  • A FastAPI application with a working start command.
  • A PostgreSQL connection URL, which we will obtain after provisioning the database.

For this walkthrough, the API uses the following dependency list (requirements.txt):

fastapi>=0.115.0
uvicorn[standard]>=0.32.0
sqlalchemy>=2.0.36
psycopg2-binary>=2.9.10

These are the requirements used for the demo. For a longer-lived project, pin the exact dependency versions that you have tested so a later build does not silently resolve to a newer release.

Step 1: Prepare the FastAPI Application

The application is split into a few small modules:

  • main.py defines the FastAPI app and its routes.
  • database.py creates the SQLAlchemy engine and database sessions.
  • models.py defines the Task database model.
  • schemas.py defines the request and response models.
  • requirements.txt lists the Python dependencies.

The database configuration reads its connection string from an environment variable. For local development, the project also includes a SQLite fallback:

DATABASE_URL = os.getenv(“DATABASE_URL”, “sqlite:///./tasks.db”)

if DATABASE_URL.startswith(“postgres://”):
DATABASE_URL = DATABASE_URL.replace(“postgres://”, “postgresql://”, 1)

connect_args = (
{“check_same_thread”: False}
if DATABASE_URL.startswith(“sqlite”)
else {}
)

engine = create_engine(
DATABASE_URL,
connect_args=connect_args,
pool_pre_ping=True,
)

The pool_pre_ping=True option checks a pooled connection before using it, which helps SQLAlchemy detect stale connections. The SQLite fallback is useful for local testing; in production, we set DATABASE_URL to our managed PostgreSQL connection string.

The API creates the demo table when the application starts using SQLAlchemy’s Base.metadata.create_all(). That keeps this small demonstration easy to run. For a production application with evolving schemas, use a migration tool such as Alembic rather than relying on create_all() to manage schema changes. Also avoid returning raw database exception messages to public clients: log the detailed exception on the server and return a generic error response instead.

Push the project to GitHub

After testing the API locally, push the source files to GitHub:

Keep .env files, credentials, virtual environments, cache directories, and local database files out of the repository. A simple .gitignore should include entries such as:

.env
.venv/
__pycache__/
*.py[cod]
*.db
.pytest_cache/

Step 2: Connect GitHub and Deploy the Web Service

Once your code is on GitHub, the next step is connecting the repository to a web service. After signing in to Seenode, we selected Create new → Web and authorized the Seenode GitHub App to access our demo repository.

GitHub connected to Seenode

We selected the main branch and configured the service with the following values:

SettingValue
Service typeWeb
Repositorythisisshubhamkumar/seenode-demo-api
Branchmain
RuntimePython 3.14
Build commandpip install -r requirements.txt
Start commanduvicorn main:app –host 0.0.0.0 –port 80
Container port80
InstanceBasic — 0.5 GB RAM, 0.25 vCPU
Regioneu-central

Web service build and start configuration

The host and port in the start command matter. Your ASGI server must listen on 0.0.0.0 and on the same container port configured in the dashboard. In our deployment, both were set to port 80 so public HTTP/HTTPS traffic routes straight to Uvicorn.

We then started the seven-day trial and watched the deployment logs. The platform built the container image (1,379.7 MB), uploaded it, and started Uvicorn. The service became available at:

Successful build and deployment logs

At this point the web service was live. Next, we needed to provision PostgreSQL and connect it to the API.

Step 3: Provision a Managed PostgreSQL Database

From the dashboard sidebar, we opened Database → Create new and spun up a managed PostgreSQL instance in the same region:

SettingValue
Namebold-kare2
EnginePostgreSQL
Version18.6
InstanceBasic
Storage1 GB
Connections20
Regioneu-central

Creating a managed PostgreSQL 18.6 database

After provisioning, the database overview showed its status and connection details. The Connection tab provided the host, port, database name, username, password controls, and a URI format ready for our application.

Managed PostgreSQL database overview and Connection tab

Keep connection credentials private. Never paste a complete connection URI containing a password into an article, screenshot, source file, or public issue.

Step 4: Connect PostgreSQL via Environment Variables

Creating a database does not automatically inject its credentials into your web service. We copied the PostgreSQL connection URI from the database’s Connection tab, opened our web service’s Envs tab, added DATABASE_URL, marked it as Secret, and applied the change.

Environment variables tab showing DATABASE_URL marked as Secret

Applying the environment variable restarted the service so the application could read the new value and switch from the local SQLite fallback to PostgreSQL.

A PostgreSQL driver gotcha to watch out for

Our first database connection attempt exposed a SQLAlchemy 2.1 compatibility detail worth noting. The project installed psycopg2-binary, while the resolved SQLAlchemy version was 2.1.9. In SQLAlchemy 2.1, a URL written simply as postgresql://… uses the psycopg (version 3) driver by default instead of psycopg2.

Because only psycopg2-binary was installed, the application initially failed on startup with ModuleNotFoundError: No module named ‘psycopg’.

We fixed this by explicitly specifying the installed driver in the connection URL:

postgresql+psycopg2://username:password@hostname:port/database

There are two valid ways to handle this in any Python + SQLAlchemy 2.1+ project:

  • Keep psycopg2-binary installed and use postgresql+psycopg2:// in DATABASE_URL.
  • Install psycopg[binary] and use postgresql+psycopg://.

The key is making sure the driver in your SQLAlchemy URL matches the driver installed in your environment. See the SQLAlchemy 2.1 migration notes for details.

After updating DATABASE_URL to postgresql+psycopg2://… and applying the change, the API booted cleanly and connected to PostgreSQL.

Step 5: Test the Live API

With the database connected, we opened the public HTTPS URL and verified the endpoints.

Check the root endpoint

Opening the service URL returned the API welcome response:

{
“message”: “Welcome to the Seenode Demo Task API”,
“docs”: “/docs”,
“health”: “/health”
}

Live root endpoint JSON response over HTTPS

Check database connectivity

We then opened /health. The endpoint executes SELECT 1 against PostgreSQL and returned:

{
“status”: “ok”,
“database”: “connected”
}

Live /health endpoint confirming PostgreSQL connectivity

Create and retrieve a task

Next, we sent a POST /tasks request to create a sample task and received:

{
“id”: 1,
“title”: “Deploy FastAPI on Seenode”,
“description”: “Connected to managed PostgreSQL 18.6”,
“completed”: false,
“created_at”: “2026-12-03T07:23:25.333554Z”
}

Calling GET /tasks returned the persisted task from PostgreSQL, and FastAPI’s interactive Swagger UI was available out of the box at /docs.

The deployed API is live at seenode-demo-api.seenode.app.

Hosting Costs and Trial Notes

Seenode uses a prepaid credit balance: services have fixed monthly package rates, with charges deducted daily while active (unrelated to request volume).

During our test, the dashboard offered a seven-day trial without requiring a credit card. Creating the web service started the workspace trial, and creating the database a day into testing showed six days remaining on that same workspace trial.

The Basic resources used in this walkthrough are listed at the following published rates (checked December 3, 2026):

ResourceIncluded configurationPublished price
Basic web application0.5 GB RAM, 0.25 vCPU$4/month
Basic PostgreSQL database1 GB storage, 20 connections$4/month
Combined estimateOne Basic app + one Basic database$8/month

That works out to roughly $0.262 per day for both Basic resources running continuously, before any larger instances, replicas, persistent volumes, or applicable taxes.

Workspace Billing tab showing Credit balance during the free trial

For current rates and trial terms, check Seenode’s pricing documentation.

Gotchas and Platform Limits to Keep in Mind

The deployment worked smoothly once configured, though a few practical details are worth keeping in mind for real projects:

  1. Handle database passwords carefully:

After creation, the Connection tab displays <password> as a placeholder inside the URI. Use the dashboard’s password visibility control or rotate the password if needed before copying it into DATABASE_URL.

  • Match your SQLAlchemy URL scheme to your driver:

With SQLAlchemy 2.1+, postgresql:// defaults to psycopg (v3). Use postgresql+psycopg2:// if you install psycopg2-binary, or install psycopg[binary].

  • Filter logs by category when debugging:

The Logs view separates Build, Runtime, and Request logs. Python startup tracebacks appear under Runtime, whereas pip install and Docker image output appear under Build.

  • Container filesystems are ephemeral:

Files written locally inside the web container can be lost on redeploy or restart. Always store persistent data in a managed database or attached persistent storage.

  • Scaling is manual, not automatic:

You can adjust instance size and replica count in the dashboard, though replicas are configured manually rather than autoscaled on traffic spikes.

  • Basic tier sizing:

The Basic tier (0.5 GB RAM / 0.25 vCPU for the app and 1 GB storage for PostgreSQL) is well suited for prototypes and small APIs; monitor usage before running heavier production workloads.

More details on container behavior and scaling are covered in Seenode’s web services guide.

Wrapping Up

Taking a FastAPI service and PostgreSQL database from local code to a live HTTPS endpoint doesn’t have to require complex infrastructure setup. Using Seenode, we connected a GitHub repository, provisioned PostgreSQL 18.6 in the same workspace, wired up DATABASE_URL as a secret, and verified live persistence over HTTPS in minutes—with predictable Basic-tier pricing ($8/month combined) and a no-card trial to test everything first.

Tested on December 3, 2026. Prices and platform features can change; refer to official documentation for current details.


Discover more from Spyboy blog

Subscribe to get the latest posts sent to your email.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.