Introduction
In this article, we will build a FastAPI application that connects to PostgreSQL, providing a foundation for more complex applications. Building a web API that interacts with a database is a core task for modern developers. In this article, we’ll walk through a simple FastAPI application that connects to PostgreSQL and calls a PL/pgSQL function. The goal is to demonstrate how to create a database function, expose it via FastAPI endpoints, and handle the interactions safely and efficiently. We’ll use a small example—a function that adds two numbers—to illustrate the full workflow, from SQL creation to API calls. Along the way, we’ll highlight best practices such as parameterized queries, context-managed connections, input validation, and error handling. By following this example, you’ll gain a practical pattern for building database-backed FastAPI applications.
Tech Stack used:
Python 3.14
Postgres SQL
PgAdmin 4
UV package manager for Python
Set up Project Packages
In this step, do the following activities,
We will create a virtual environment.
Install the 'psycopg' package to interact with PostgreSQL and Fast API to run a REST API
Create the main.py file and follow along.
If the uv package manager doesn't exists, use the command to set it up - pip install uv
uv venv
uv pip install "psycopg[binary]" "fastapi[standard]" Code Walkthrough
Part 1: Basic Ping Test
This FastAPI code defines a simple API with a single endpoint, /ping/sql. It first loads environment variables using dotenv to access the PostgreSQL connection string stored in PGCONNECTION. When the endpoint is called, it imports the psycopg module and establishes a connection to the database. Within the connection context, it opens a cursor to execute SQL commands. The code runs a basic query, SELECT 2+2, fetches the result using fetchone(), and assigns it to result. Finally, the endpoint returns this result as the API response, serving as a minimal SQL connectivity test through FastAPI.
from typing import Union
import os
from fastapi import FastAPI
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
@app.get("/ping/sql")
def ping_sql():
result = None
import psycopg
# Connect to an existing database
with psycopg.connect(os.getenv("PGCONNECTION")) as conn:
# Open a cursor to perform database operations
with conn.cursor() as cur:
cur.execute("SELECT 2+2")
result = cur.fetchone()
return resultTo start the application we will run below command
uv run fastapi dev main.pyOutput:

Takeaways:




Join the conversation! Your thoughts help the community grow.