dev-resources.site
for different kinds of informations.
๐ Building a User Management API with FastAPI and SQLite
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": "[email protected]", "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": "[email protected]", "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! ๐จโ๐ป๐ฉโ๐ป
Featured ones: