I need to show the installation line: pip install "fastapi[standard]" sqlalchemy uvicorn since it's the recommended way as of 2024. Should I mention Alembic for migrations? Maybe not. The user might want RESTful endpoints like /items/ for GET and POST, and /items/{id} for GET, PUT, DELETE. I should manage CORS but, again, maybe it's not necessary. I need to keep the answer concise and code-focused, so I’ll outline it carefully. Let's get started!Creating main.py for FastAPI
I'm structuring the main.py file for a FastAPI application. It includes necessary imports and database setup using SQLAlchemy. The database URL points to a local SQLite database. I’m defining the Item model and data schemas for creating, updating, and reading items.
I’ll add code for creating tables and initializing the FastAPI app. Also, I need to include endpoints for creating and listing items, ensuring that responses adhere to specified models. This approach provides a clear foundation for the Items API.Completing FastAPI endpoints
I’m finalizing my FastAPI application with CRUD operations for items. For listing items, I’m using offset(skip).limit(limit).all() to return the specified items.
I’ve added get_item, update_item, and delete_item endpoints. If an item isn’t found, I raise a 404 HTTPException. For delete_item, I see that returning a JSONResponse with a 204 status is optional since FastAPI returns it by default. Instead, I'll simplify it to return just an empty Response with a 204 status. That keeps things clean!Clarifying FastAPI response behavior
I’m realizing that FastAPI will set the status code from the decorator when returning something, but returning None results in a default 200 status. For path operations with explicit status codes and no response_model, if nothing is returned, it defaults to a 204 with an empty body. To clarify, I’ll explicitly return Response(status_code=status.HTTP_204_NO_CONTENT) and make sure to import it.
I also need to remember to use Python 3.10+ typing, like list[ItemRead], and mention how to run the application using uvicorn main:app --reload. I'll include some quick curl examples and point out the interactive docs available at /docs. Finally, focusing on synchronous functions is best here due to the blocking DB context.Setting up Pydantic and SQLAlchemy in FastAPI
I need to carefully consider the imports for Pydantic. For Pydantic v2, I’ll use this: from pydantic import BaseModel, ConfigDict. The ItemRead class will leverage model_config = ConfigDict(from_attributes=True).
Since FastAPI now installs Pydantic v2 with pip install fastapi[standard], it should work without issues. If someone uses v1, they'll hit an import error, but I’ll just include List[ItemRead] for Python 3.10+ compatibility and a fallback to List from typing for older versions.
Additionally, I must ensure imports follow the 2.x style with declarative_base. I’ll also create sections like "1. Install dependencies" for clarity in my markdown structure. Below is a minimal but complete example of a REST API built with FastAPI and SQLAlchemy, using SQLite as the database and implementing full CRUD for a simple Item resource.
If you want, I can next show a more structured layout (app/ package with models.py, schemas.py, database.py, routers/ etc.) or extend this with authentication, pagination, or relationships between models.
from typing import List, Optional
from fastapi import Depends, FastAPI, HTTPException, Response, status
from pydantic import BaseModel, ConfigDict
from sqlalchemy import Column, Integer, String, Text, create_engine
from sqlalchemy.orm import Session, declarative_base, sessionmaker
# ---------------------------------------------------------------------------
# Database setup
# ---------------------------------------------------------------------------
DATABASE_URL = "sqlite:///./test.db" # For demo; change to your DB as needed
engine = create_engine(
DATABASE_URL,
connect_args={"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {},
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# ---------------------------------------------------------------------------
# SQLAlchemy models
# ---------------------------------------------------------------------------
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(100), nullable=False, index=True)
description = Column(Text, nullable=True)
# Create tables (for demo; in production use Alembic migrations)
Base.metadata.create_all(bind=engine)
# ---------------------------------------------------------------------------
# Pydantic schemas
# ---------------------------------------------------------------------------
class ItemCreate(BaseModel):
title: str
description: Optional[str] = None
class ItemUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
class ItemRead(BaseModel):
id: int
title: str
description: Optional[str] = None
# Pydantic v2: allow reading from ORM objects
model_config = ConfigDict(from_attributes=True)
# ---------------------------------------------------------------------------
# FastAPI app & dependencies
# ---------------------------------------------------------------------------
app = FastAPI(title="Items API", version="1.0.0")
def get_db() -> Session:
db = SessionLocal()
try:
yield db
finally:
db.close()
# ---------------------------------------------------------------------------
# CRUD endpoints
# ---------------------------------------------------------------------------
@app.post("/items/", response_model=ItemRead, status_code=status.HTTP_201_CREATED)
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
db_item = Item(title=item.title, description=item.description)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/items/", response_model=List[ItemRead])
def list_items(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db),
):
items = db.query(Item).offset(skip).limit(limit).all()
return items
@app.get("/items/{item_id}", response_model=ItemRead)
def get_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@app.put("/items/{item_id}", response_model=ItemRead)
def update_item(
item_id: int,
item_update: ItemUpdate,
db: Session = Depends(get_db),
):
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if item_update.title is not None:
item.title = item_update.title
if item_update.description is not None:
item.description = item_update.description
db.commit()
db.refresh(item)
return item
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
db.delete(item)
db.commit()
# 204: No content
return Response(status_code=status.HTTP_204_NO_CONTENT)