FastAPI has become one of the most popular Python web frameworks, thanks to its speed, simplicity, and intuitive design. In this article, weβll build a User Management API using FastAPI and SQLite. The API will include features like creating, retrieving, updating, and deleting users (CRUD).
Letβs dive in! πββοΈ
π Prerequisites
Before we start, ensure you have the following installed:
- Python 3.8+
- pip (Python package manager)
Install FastAPI and the ASGI server Uvicorn:
pip install fastapi uvicorn sqlalchemy pydantic
π The Project Structure
Hereβs what weβll build:
- SQLite Database: Store user data using SQLAlchemy.
- CRUD Operations: Endpoints to manage users.
- Validation: Ensure correct data is provided using Pydantic.
π Code Implementation
1οΈβ£ Database Setup with SQLAlchemy
Start by defining the database connection and user model:
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./users.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
Base = declarative_base()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# User model for SQLAlchemy
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True, nullable=False)
email = Column(String, unique=True, index=True, nullable=False)
age = Column(Integer, nullable=False)
# Create the database table
Base.metadata.create_all(bind=engine)
2οΈβ£ FastAPI App Initialization
Now, initialize your FastAPI application and define database session dependencies:
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
3οΈβ£ Define Pydantic Models
Pydantic is used for request validation and response formatting.
from pydantic import BaseModel
class UserCreate(BaseModel):
name: str
email: str
age: int
class UserResponse(BaseModel):
id: int
name: str
email: str
age: int
class Config:
orm_mode = True
4οΈβ£ CRUD Endpoints
Letβs implement the core features of our User Management API.
Create a New User
@app.post("/users/", response_model=UserResponse)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.email == user.email).first()
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
new_user = User(name=user.name, email=user.email, age=user.age)
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_user
Retrieve All Users
@app.get("/users/", response_model=list[UserResponse])
def get_users(db: Session = Depends(get_db)):
return db.query(User).all()
Update a User by ID
@app.put("/users/{user_id}", response_model=UserResponse)
def update_user(user_id: int, user: UserCreate, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.id == user_id).first()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
db_user.name = user.name
db_user.email = user.email
db_user.age = user.age
db.commit()
db.refresh(db_user)
return db_user
Delete a User by ID
@app.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.id == user_id).first()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
db.delete(db_user)
db.commit()
return {"message": "User deleted successfully"}
5οΈβ£ Run the Application
Run your application using Uvicorn
:
uvicorn main:app --reload
Visit http://127.0.0.1:8000/docs
to explore your API with the automatically generated Swagger UI.
π― Testing the API
Here are some examples to interact with the API:
- Create a User:
curl -X POST "http://127.0.0.1:8000/users/" \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com", "age": 30}'
- Get All Users:
curl -X GET "http://127.0.0.1:8000/users/"
- Update a User:
curl -X PUT "http://127.0.0.1:8000/users/1" \
-H "Content-Type: application/json" \
-d '{"name": "Jane Doe", "email": "jane@example.com", "age":
25}'
- Delete a User:
curl -X DELETE "http://127.0.0.1:8000/users/1"
π Key Features of This Example
-
FastAPI's Speed and Simplicity:
- FastAPI automatically validates data and generates interactive documentation.
-
SQLAlchemy Integration:
- SQLAlchemy makes database management seamless with its ORM.
-
Type Safety:
- Pydantic ensures all input and output data types are validated.
π Wrapping Up
This example demonstrates how easily you can build a scalable and efficient API with FastAPI. With its developer-friendly design, built-in validation, and performance, FastAPI is an excellent choice for modern Python web applications.
What feature would you add to this API? Let me know in the comments! π
Happy coding! π¨βπ»π©βπ»
Top comments (0)