Framing the API Project
I've started to delineate the project's core objectives: crafting a Python REST API. My focus is on leveraging FastAPI for its speed and efficiency, and integrating SQLAlchemy for robust database handling. This involves a clear plan to map out the API's endpoints and data models. I'm now zeroing in on defining the essential components.
Defining Project Structure
I'm now breaking down the project into manageable steps. First, installation, and then database configuration are top priorities. I'll define data models using SQLAlchemy, followed by Pydantic schemas for API interactions. I'm leaning toward a User Management system for the example, as it encompasses CRUD operations effectively.
Planning the Implementation Flow
I'm presently outlining the practical steps, beginning with the groundwork: environment setup and library installations. Then, I'll focus on database models, choosing SQLAlchemy ORM for its structure. API endpoints, with data validation using Pydantic, will be constructed. A key consideration is the structuring of CRUD operations as utilities to maintain clean separation of concerns. The overall design prioritizes a straightforward, scalable approach.
Defining Code Structure
I'm now focusing on the practical coding aspects. I'll utilize a single-file approach for clarity, whilst still structuring the code logically for future expansion. This includes imports, database setup with SQLAlchemy, defining data models, and setting up Pydantic schemas. A key feature is the dependency injection for database sessions within FastAPI. I'm also now planning for essential API endpoints with full CRUD operations.
Evaluating Code Implementation
I'm now carefully examining the code implementation. My priority is ensuring it functions seamlessly, adheres to established coding standards, and is easily understood. Pydantic's data validation has been tested, and SQLAlchemy's interaction with the database is checked.
Addressing Implementation Details
I'm now diving deep into the code, and I've decided to implement a single-file structure for simplicity. The essential elements include the necessary imports, database setup using SQLAlchemy with SQLite, the model definitions, and the Pydantic schemas. I'm focusing on crafting the CRUD operations within the API endpoints, with special attention to dependency injection for database sessions to ensure a clean structure. I've chosen to use from_attributes = True with Pydantic for validation.
This is a complete, step-by-step guide to building a REST API using FastAPI (for the web framework), SQLAlchemy (for the database), and Pydantic (for data validation).
We will build a simple User Management System.
Prerequisites
First, install the required libraries:
pip install fastapi uvicorn sqlalchemy pydantic
The Code (main.py)
For simplicity, we will keep everything in a single file named main.py. In a real production app, you would split these into separate files (models.py, schemas.py, database.py, etc.).
from fastapi import FastAPI, HTTPException, Depends, status
from pydantic import BaseModel
from typing import List, Optional
from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
# ==========================
# 1. DATABASE SETUP
# ==========================
# We use SQLite for this example because it requires no setup.
# For PostgreSQL, use: "postgresql://user:password@localhost/dbname"
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# ==========================
# 2. DATABASE MODELS (SQLAlchemy)
# ==========================
class UserDB(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)
is_active = Column(Boolean, default=True)
# Create the tables in the database
Base.metadata.create_all(bind=engine)
# ==========================
# 3. PYDANTIC SCHEMAS (Validation)
# ==========================
# Base schema with common attributes
class UserBase(BaseModel):
username: str
email: str
is_active: bool = True
# Schema for creating a user (Passes only necessary data)
class UserCreate(UserBase):
pass
# Schema for reading a user (Returns data + ID)
class UserResponse(UserBase):
id: int
# This config allows Pydantic to read data from SQLAlchemy models
class Config:
from_attributes = True
# ==========================
# 4. DEPENDENCIES
# ==========================
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# ==========================
# 5. API INSTANCE
# ==========================
app = FastAPI()
# ==========================
# 6. API ENDPOINTS
# ==========================
@app.post("/users/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
# Check if user already exists
db_user = db.query(UserDB).filter(UserDB.email == user.email).first()
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
# Create new user instance
new_user = UserDB(
username=user.username,
email=user.email,
is_active=user.is_active
)
db.add(new_user)
db.commit()
db.refresh(new_user) # Refresh to get the ID generated by the DB
return new_user
@app.get("/users/", response_model=List[UserResponse])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
users = db.query(UserDB).offset(skip).limit(limit).all()
return users
@app.get("/users/{user_id}", response_model=UserResponse)
def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(UserDB).filter(UserDB.id == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.put("/users/{user_id}", response_model=UserResponse)
def update_user(user_id: int, user_update: UserCreate, db: Session = Depends(get_db)):
user = db.query(UserDB).filter(UserDB.id == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
user.username = user_update.username
user.email = user_update.email
user.is_active = user_update.is_active
db.commit()
db.refresh(user)
return user
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(UserDB).filter(UserDB.id == user_id).first()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
db.delete(user)
db.commit()
# Return nothing (204 No Content)
return
How to Run the API
- Save the code above into a file named
main.py.
- Open your terminal/command prompt.
- Run the application using
uvicorn:
uvicorn main:app --reload
(The --reload flag makes the server restart automatically when you save changes to code).
How to Use and Test
FastAPI automatically generates interactive documentation.
- Open your browser and go to:
http://127.0.0.1:8000/docs
- You will see the Swagger UI.
- Create User (POST): Click the POST
/users/ button -> "Try it out". Enter JSON:
{
"username": "john_doe",
"email": "john@example.com",
"is_active": true
}
- Get Users (GET): Execute the GET
/users/ endpoint to see the data you just saved.
Key Concepts Explained
-
SQLAlchemy ORM vs. Pydantic:
- SQLAlchemy (
UserDB): Defines how data looks in the Database (columns, keys).
- Pydantic (
UserCreate, UserResponse): Defines how data looks in the API Request/Response (validation, type checking).
from_attributes = True: This allows Pydantic to read data directly from a SQLAlchemy object, translating user.id (database object) into JSON automatically.
-
Dependency Injection (get_db):
- The
get_db function creates a database session for each request and closes it automatically when the request finishes.
db: Session = Depends(get_db) tells FastAPI to run this function and pass the result into your endpoint.
-
CRUD Logic:
- Create:
db.add(), db.commit(), db.refresh().
- Read:
db.query().filter().first().
- Update: Modify the object properties, then
db.commit().
- Delete:
db.delete(), db.commit().