Skip to main content

FastAPI and Database Integration


How to Integrate a Database with FastAPI: A Step-by-Step Guide

Learn how to bridge your FastAPI backend with professional databases like MySQL and PostgreSQL using SQLAlchemy ORM.

When building a backend with FastAPI, choosing the right database strategy is crucial for performance and scalability. While local SQLite is excellent for development and testing, production environments usually require robust systems like MySQL or PostgreSQL.

In this guide, I will show you how to connect a FastAPI application to a MySQL database using SQLAlchemy, an Object-Relational Mapper (ORM) that allows you to interact with your database using Python classes instead of writing raw SQL commands.

Prerequisites

Run this command in your terminal first:

pip install fastapi sqlalchemy pymysql pydantic[email] uvicorn
1

Define Database Configuration (database.py)

The first step is to establish the connection. We use create_engine to define the database URL and sessionmaker to handle database transactions.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

# Database URL Format: mysql+pymysql://username:password@host:port/database_name
# For SQLite, use: "sqlite:///./test.db"
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://user:password@localhost:3306/db_name"

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

# Dependency to get the database session in routes
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
2

Define Database Models (models.py)

Models represent the structure of your database tables. Here, we define a User table and a Profile table linked by a foreign key.

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from .database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True)
    password = Column(String(255))
    role = Column(String(50))

    # Relationship to Profile
    profile = relationship("Profile", back_populates="user", uselist=False)

class Profile(Base):
    __tablename__ = "profiles"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    email = Column(String(255), nullable=False)
    description = Column(String(500), nullable=False)

    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)

    # Back-reference to User
    user = relationship("User", back_populates="profile")
3

Define Pydantic Schemas (schemas.py)

While Models define the database, Schemas validate the data coming in from the client and the data sent back as a response.

from pydantic import BaseModel, EmailStr

class ProfileBase(BaseModel):
    name: str
    email: EmailStr
    description: str

class ProfileCreate(ProfileBase):
    pass

class SignupRequest(BaseModel):
    username: str
    password: str

    model_config = {
        "from_attributes": True
    }
4

Integrate with Main Application (main.py)

Finally, connect everything in your main script. This script initializes the tables and defines the API endpoints using the get_db dependency.

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
import models, schemas
from database import engine, get_db

# Create the database tables on startup
models.Base.metadata.create_all(bind=engine)

app = FastAPI()

@app.post("/signup")
def create_user(user: schemas.SignupRequest, db: Session = Depends(get_db)):
    db_user = models.User(username=user.username, password=user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return {"message": "User created successfully", "id": db_user.id}

Conclusion

Using SQLAlchemy ORM with FastAPI is the industry standard because it significantly reduces complexity. Instead of writing raw SQL strings, you interact with data using Python objects, making your code safer, cleaner, and easier to scale.

People are good at skipping over material they already know!

View Related Topics to







Contact Us

Name

Email *

Message *

Popular Posts

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...(MATLAB Code + Simulator)

Bit Error Rate (BER) & SNR Guide Analyze communication system performance with our interactive simulators and MATLAB tools. 📘 Theory 🧮 Simulators 💻 MATLAB Code 📚 Resources BER Definition SNR Formula BER Calculator MATLAB Comparison 📂 Explore M-ary QAM, PSK, and QPSK Topics ▼ 🧮 Constellation Simulator: M-ary QAM 🧮 Constellation Simulator: M-ary PSK 🧮 BER calculation for ASK, FSK, and PSK 🧮 Approaches to BER vs SNR What is Bit Error Rate (BER)? The BER indicates how many corrupted bits are received compared to the total number of bits sent. It is the primary figure of merit for a...

Constellation Diagrams of ASK, PSK, and FSK (with MATLAB Code + Simulator)

Constellation Diagrams: ASK, FSK, and PSK Comprehensive guide to signal space representation, including interactive simulators and MATLAB implementations. 📘 Overview 🧮 Simulator ⚖️ Theory 📚 Resources Definitions Constellation Tool Key Points MATLAB Code 📂 Other Topics: M-ary PSK & QAM Diagrams ▼ 🧮 Simulator for M-ary PSK Constellation 🧮 Simulator for M-ary QAM Constellation BASK (Binary ASK) Modulation Transmits one of two signals: 0 or -√Eb, where Eb​ is the energy per bit. These signals represent binary 0 and 1. BFSK (Binary FSK) Modulation Transmits one ...

Simulation of ASK, FSK, and PSK using MATLAB Simulink (with Online Simulator)

📘 Overview 🧮 How to use MATLAB Simulink 🧮 Simulation of ASK using MATLAB Simulink 🧮 Simulation of FSK using MATLAB Simulink 🧮 Simulation of PSK using MATLAB Simulink 🧮 Simulator for ASK, FSK, and PSK 🧮 Digital Signal Processing Simulator 📚 Further Reading ASK, FSK & PSK HomePage MATLAB Simulation Simulation of Amplitude Shift Keying (ASK) using MATLAB Simulink In Simulink, we pick different components/elements from MATLAB Simulink Library. Then we connect the components and perform a particular operation. Result A sine wave source, a pulse generator, a product block, a mux, and a scope are shown in the diagram above. The pulse generator generates the '1' and '0' bit sequences. Sine wave sources produce a specific amplitude and frequency. The scope displays the modulated signal as well as the original bit sequence created by the pulse generator. Mux i...

Online Simulator for ASK, FSK, and PSK

Try our new Digital Signal Processing Simulator!   •   Interactive ASK, FSK, and BPSK tools updated for 2025. Start Now Interactive Modulation Simulators Visualize binary modulation techniques (ASK, FSK, BPSK) in real-time with adjustable carrier and sampling parameters. 📡 ASK Simulator 📶 FSK Simulator 🎚️ BPSK Simulator 📚 More Topics ASK Modulator FSK Modulator BPSK Modulator More Topics Simulator for Binary ASK Modulation Digital Message Bits Carrier Freq (Hz) Sampling Rate (...

Coherence Bandwidth and Coherence Time (with MATLAB + Simulator)

🧮 Coherence Bandwidth 🧮 Coherence Time 🧮 MATLAB Code s 📚 Further Reading For Doppler Delay or Multi-path Delay Coherence time T coh ∝ 1 / v max (For slow fading, coherence time T coh is greater than the signaling interval.) Coherence bandwidth W coh ∝ 1 / Ï„ max (For frequency-flat fading, coherence bandwidth W coh is greater than the signaling bandwidth.) Where: T coh = coherence time W coh = coherence bandwidth v max = maximum Doppler frequency (or maximum Doppler shift) Ï„ max = maximum excess delay (maximum time delay spread) Notes: The notation v max −1 and Ï„ max −1 indicate inverse proportionality. Doppler spread refers to the range of frequency shifts caused by relative motion, determining T coh . Delay spread (or multipath delay spread) determines W coh . Frequency-flat fading occurs when W coh is greater than the signaling bandwidth. Coherence Bandwidth Coherence bandwidth is...

ASK, FSK, and PSK (with MATLAB + Online Simulator)

📘 ASK Theory 📘 FSK Theory 📘 PSK Theory 📊 Comparison 🧮 MATLAB Codes 🎮 Simulator ASK or OFF ON Keying ASK is a simple (less complex) Digital Modulation Scheme where we vary the modulation signal's amplitude or voltage by the message signal's amplitude or voltage. We select two levels (two different voltage levels) for transmitting modulated message signals. Example: "+5 Volt" (upper level) and "0 Volt" (lower level). To transmit binary bit "1", the transmitter sends "+5 Volts", and for bit "0", it sends no power. The receiver uses filters to detect whether a binary "1" or "0" was transmitted. Fig 1: Output of ASK, FSK, and PSK modulation using MATLAB for a data stream "1 1 0 0 1 0 1 0" ( Get MATLAB Code ) ...

DFTs-OFDM vs OFDM: Why DFT-Spread OFDM Reduces PAPR Effectively (with MATLAB Code)

DFT-spread OFDM (DFTs-OFDM) has lower Peak-to-Average Power Ratio (PAPR) because it "spreads" the data in the frequency domain before applying IFFT, making the time-domain signal behave more like a single-carrier signal rather than a multi-carrier one like OFDM. Deeper Explanation: Aspect OFDM DFTs-OFDM Signal Type Multi-carrier Single-carrier-like Process IFFT of QAM directly QAM → DFT → IFFT PAPR Level High (due to many carriers adding up constructively) Low (less fluctuation in amplitude) Why PAPR is High Subcarriers can add in phase, causing spikes DFT "pre-spreads" data, smoothing it Used in Wi-Fi, LTE downlink LTE uplink (as SC-FDMA) In OFDM, all subcarriers can...