Introduction
FastAPI is one of the fastest and most modern Python frameworks for building APIs. It is designed to be simple, fast, and developer-friendly. One of its biggest advantages is native support for async and await, which helps build highly scalable APIs that run efficiently under heavy load.
When combined with an async database library such as SQLModel, Tortoise ORM, or Async SQLAlchemy, you can build a truly high-performance backend.
This article will guide you step-by-step through building a REST API with FastAPI using async database operations, explained in simple and natural language.
1. Installing FastAPI and Uvicorn
Before building the API, install the required libraries.
pip install fastapi uvicorn
pip install sqlmodel[asyncio]
FastAPI → API framework
Uvicorn → ASGI web server for running FastAPI
SQLModel/Async SQLAlchemy → Async database layer
2. Creating the FastAPI Application
Create a file main.py.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {"message": "FastAPI is running!"}Run the server
uvicorn main:app --reloadFastAPI automatically generates documentation at:
/docs(Swagger UI)/redoc
3. Setting Up the Async Database
We will use SQLModel for async database operations.
Create a database connection file: database.py
from sqlmodel import SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
engine = create_async_engine(DATABASE_URL, echo=True)
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def init_db():
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)Explanation
Async engine allows non-blocking database operations
AsyncSessionis required for async CRUD
4. Creating Database Models with SQLModel
Create models.py.
from sqlmodel import SQLModel, Field
from typing import Optional
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
email: strWhy SQLModel?
Combines Pydantic + SQLAlchemy
Easy model creation
Async support
5. Creating CRUD Routes (Async Operations)
Create routes_user.py.
from fastapi import APIRouter, Depends
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.future import select
from models import User
from database import async_session
router = APIRouter()
async def get_session():
async with async_session() as session:
yield session
@router.post("/users")
async def create_user(user: User, session: AsyncSession = Depends(get_session)):
session.add(user)
await session.commit()
await session.refresh(user)
return user
@router.get("/users")
async def list_users(session: AsyncSession = Depends(get_session)):
result = await session.execute(select(User))
return result.all()
@router.get("/users/{user_id}")
async def get_user(user_id: int, session: AsyncSession = Depends(get_session)):
result = await session.execute(select(User).where(User.id == user_id))
return result.first()
@router.delete("/users/{user_id}")
async def delete_user(user_id: int, session: AsyncSession = Depends(get_session)):
result = await session.execute(select(User).where(User.id == user_id))
user = result.first()[0]
await session.delete(user)
await session.commit()
return {"message": "User deleted"}Features
Async CRUD operations
Dependency injection using
Depends()Efficient async queries
6. Include Routes in Main Application
Update main.py.
Join the conversation! Your thoughts help the community grow.