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.

Contact Us

Name

Email *

Message *

Popular Posts

UGC NET Electronic Science Previous Year Question Papers with Solutions

Home / Engineering & Other Exams / UGC NET 2026 PYQ ⬇️ Download Papers and Solutions 📋 Exam Pattern 💡 Preparation Tips ❓ FAQs 📊 Exam Highlights: Electronic Science (88) Feature Details Junior Research Fellowship (JRF) ₹37,000 + HRA per month Eligibility M.Sc/M.Tech in Electronics (55%) Validity of Certificate JRF (3 Years) | Lectureship (Lifetime) 📥 Download UGC NET Electronics PDFs Complete collection of previous year question papers, answer keys and explanations for Subject Code 88. Start Downloading 📂 View All Question Papers June 2025 - Question Paper Download PDF June 2025 - Solved Paper + Explanation ...

UGC NET Electronic Science June 2025 Question Paper with Answer Key & Detailed Solutions

Home / UGC NET PYQ / June 2025 Solved UGC NET Electronic Science June 2025 Question Paper with Answer Key and Full Explanations 📥 Download Question Paper (PDF) 2025 2024 2023 2022 2021 2020 Explanations 1.  Answer: Option (3) For forming a p-type semiconductor, the dopant must be a trivalent impurity (three valence electrons) so that it creates acceptor levels and holes become the majority carriers. Among the given elements, boron (B) is a group-III element (trivalent). Arsenic (As) and phosphorus (P) are group-V (pentavalent) donors that produce n-type material, and germanium (Ge) is a group-IV element usually used as the semiconductor, not as an acceptor dopant. Hence, doping an intrinsic semiconductor with B produces a p-type semiconductor. 2.  Answer: Option (4) The ohmic resistance of a JFET at zero gate bias is given by the standard relation: R DS(on) = V P / I DSS ...

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 f...

Online Simulator for ASK, FSK, and PSK

Interactive Digital Signal Processing (DSP) Tutorial and Simulator for ASK, FSK, and BPSK modulation techniques. Try our new Digital Signal Processing Simulator!   •   Interactive ASK, FSK, and BPSK tools updated for 2025. Start Now Digital Modulation Visualizer: ASK, FSK, & BPSK Simulator Learn and visualize binary modulation techniques (ASK, FSK, BPSK) in real-time with adjustable carrier and sampling parameters. Perfect for DSP students and engineers. 📡 ASK Simulator 📶 FSK Simulator 🎚️ BPSK Simulator 📚 More Topics ASK Modulator FSK Modulator BPSK Modulator More Topics 1. ASK (Amplitude Shift Keying) Simulat...

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 Q-function 📚 Resources 📂 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 of two signals: +√Eb​ (On the y-axis, the phas...

UGC NET Electronic Science December 2024 Question Paper with Answer Key & Detailed Solutions

Home / UGC NET PYQ / June 2025 Solved UGC NET Electronic Science December 2024 Question Paper with Answer Key and Full Explanations 📥 Download Question Paper (PDF) 2025 2024 2023 2022 2021 2020 Q.1 Answer: Option (3) Q.2 Answer: Option (3) Solution 1. JMP SHORT LABEL Intrasegment (within the same code segment). Direct jump. ❌ Not intersegment indirect. 2. JMP 5000H:2000H Intersegment (far jump because both CS and IP are specified). Direct jump (address is explicitly given). ❌ Not indirect. 3. JMP [2000H] The destination address is taken from memory location 2000H. This is indirect. In 8086, a far indirect jump can use a memory operand containing both IP and CS (depending on operand size), making it an intersegment indirect jump. ✅ Correct answer. 4. JMP [BX] Indirect jump through memory addressed by BX. Usually intrasegment (near indirect jump). ❌ Not in...

Theoretical BER vs SNR for binary ASK, FSK, and PSK (with MATLAB Code + Simulator)

📘 Overview & Theory 🧮 MATLAB Codes 🧮 Q-function 📚 Further Reading Bit Error Rate (BER) Equations In ASK, noise directly affects the signal amplitude, making it the most vulnerable since the data is carried in amplitude changes. In FSK, data is represented by frequency variations, and because noise typically impacts amplitude more than frequency, FSK is more robust than ASK. In PSK, data is encoded in the signal phase, and BPSK specifically uses 180-degree phase shifts, creating the greatest separation between signal points and therefore achieving the lowest bit error rate (BER) for the same power level. BER formulas for ASK, FSK, and PSK modulation schemes. ASK BER = 0.5 × erfc(0.5 × √SNR) FSK BER = 0.5 × erfc(√(SNR / 2)) PSK BER = 0.5 × erfc(√SNR) ...

MATLAB Code for ASK, FSK, and PSK (with Online Simulator)

MATLAB Code for ASK, FSK, and PSK Comprehensive implementation of digital modulation and demodulation techniques with simulation results. 📘 Theory 📡 ASK Code 📶 FSK Code 🎚️ PSK Code 🕹️ Simulator 📚 Further Reading Amplitude Shift Frequency Shift Phase Shift Live Simulator ASK, FSK & PSK HomePage MATLAB Code MATLAB Code for ASK Modulation and Demodulation COPY % The code is written by SalimWireless.Com clc; clear all; close all; % Parameters Tb = 1; fc = 10; N_bits = 10; Fs = 100 * fc; Ts = 1/Fs; samples_per_bit = Fs * Tb; rng(10); binar...