📘Introduction

FastAPI is a modern, high-performance web framework for building APIs with Python. In real-world applications, you'll often need to connect to a relational database like PostgreSQL to store and retrieve data. But building that connection securely and cleanly—especially across development, staging, and production environments—requires a well-structured setup.

In this tutorial, you'll learn how to connect FastAPI to a PostgreSQL database using SQLModel, a modern ORM built on top of SQLAlchemy and Pydantic. By the end, you'll have a working FastAPI project connected to a PostgreSQL database, ready to query data.

💡Why use SQLModel and BaseSettings in FastAPI?

SQLModel is a library created by the author of FastAPI that unifies the power of SQLAlchemy with the simplicity of Pydantic. With SQLModel, you define your data models only once and use them both for database operations and request/response validation. It’s fully type-annotated, integrates naturally with FastAPI, and reduces boilerplate compared to traditional ORMs.

BaseSettings from Pydantic makes managing environment variables clean and secure. Instead of hardcoding sensitive values like database passwords or connection strings, BaseSettings loads them from your environment or a .env file, validates their types, and makes them accessible throughout your codebase.

Together, SQLModel and BaseSettings offer:
✅ A single source of truth for your data models
✅ Automatic type validation
✅ Secure, environment-specific configuration
✅ Minimal boilerplate and high developer productivity

✅ Prerequisites

Before you begin, make sure you have:

  • Python 3.10+ installed
  • PostgreSQL running locally
  • A working Python environment

📦1️⃣ Install Required Libraries

Install the necessary dependencies:

 fastapi uvicorn sqlmodel psycopg2-binary pydantic-settings python-dotenv

🔑2️⃣ Create a .env File

In the root of your project, create a .env file with your PostgreSQL connection string:

DATABASE_URL=postgresql://postgres:yourpassword@localhost:5432/yourdatabase

⚙️3️⃣ Define Your Settings Class

Create a file named settings.py to load the environment variables using BaseSettings:

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"

settings = Settings()
💡
This reads the DATABASE_URL from .env and makes it available to your app.

🔌4️⃣ Set Up the Database Connection

Create a file named database.py to handle the database engine and session:

You can view this post with the tier: Academy Membership

Join academy now to read the post and get access to the full library of premium posts for academy members only.

Join Academy Already have an account? Sign In