Table of Contents
Python has become one of the most popular programming languages for web development, especially when building REST APIs. FastAPI and SQLAlchemy are two powerful libraries that simplify this process, allowing developers to create efficient, scalable, and maintainable APIs.
Introduction to FastAPI and SQLAlchemy
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. SQLAlchemy is an SQL toolkit and Object-Relational Mapper (ORM) that provides a full suite of well-designed APIs for working with databases.
Setting Up the Environment
To get started, install the necessary libraries using pip:
- fastapi
- uvicorn
- sqlalchemy
- databases
- pydantic
Use the following command:
pip install fastapi uvicorn sqlalchemy databases pydantic
Creating a Simple REST API
Let's build a basic API for managing a list of items. We'll define our database models, create endpoints, and connect everything together.
Database Setup
First, define the database connection and models:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Item(Base):
__tablename__ = 'items'
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
description = Column(String)
Creating FastAPI Endpoints
Next, set up the FastAPI app and define routes for CRUD operations:
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
from databases import Database
DATABASE_URL = "sqlite:///./test.db"
database = Database(DATABASE_URL)
app = FastAPI()
from sqlalchemy import create_engine
engine = create_engine(DATABASE_URL)
Base.metadata.create_all(bind=engine)
def get_db():
db = Session(bind=engine)
try:
yield db
finally:
db.close()
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
@app.post("/items/")
def create_item(item: Item, db: Session = Depends(get_db)):
db_item = Item(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/items/{item_id}")
def read_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
items = db.query(Item).offset(skip).limit(limit).all()
return items
Testing the API
You can run the API server using Uvicorn:
uvicorn main:app --reload
Then, access http://127.0.0.1:8000/docs to see the automatically generated Swagger UI, where you can test your endpoints interactively.
Conclusion
Using FastAPI with SQLAlchemy provides a powerful combination for building REST APIs in Python. It simplifies database interactions, speeds up development, and offers excellent performance. With these tools, developers can create robust APIs suitable for production environments.