ORM in FastAPI/Uvicorn
What is ORM?
ORM stands for Object Relational Mapper. It allows you to work with databases using Python objects instead of writing raw SQL queries.
Instead of writing:
SELECT * FROM users WHERE id = 1;
You can write:
user = session.get(User, 1)
Here, User is a Python class mapped to a database table.
Common ORMs Used with FastAPI
1. SQLAlchemy
SQLAlchemy is the most commonly used ORM with FastAPI.
from sqlalchemy import Column, Integer, String
from database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
2. SQLModel
SQLModel combines Pydantic and SQLAlchemy and is beginner-friendly.
from sqlmodel import SQLModel, Field
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
What is Uvicorn?
Uvicorn is an ASGI server used to run FastAPI applications.
Example:
uvicorn main:app --reload
main→ Python file name (main.py)app→ FastAPI instance--reload→ Auto reload during development
How They Work Together
Client Request
↓
Uvicorn (server)
↓
FastAPI (API framework)
↓
ORM (SQLAlchemy / SQLModel)
↓
Database (PostgreSQL/MySQL/SQLite)
Minimal FastAPI + ORM Example
from fastapi import FastAPI
from sqlmodel import SQLModel, Field
app = FastAPI()
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
@app.get("/")
def read_root():
return {"hello": "world"}
Run the application using:
uvicorn main:app --reload
Quick Summary
| Term | Description |
|---|---|
| FastAPI | API framework |
| Uvicorn | Server that runs FastAPI |
| ORM | Database abstraction layer |
| SQLAlchemy | Popular ORM |
| SQLModel | FastAPI-friendly ORM |