DEV Community

A0mineTV
A0mineTV

Posted on

πŸš€ 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
Enter fullscreen mode Exit fullscreen mode

πŸ“œ The Project Structure

Here’s what we’ll build:

  1. SQLite Database: Store user data using SQLAlchemy.
  2. CRUD Operations: Endpoints to manage users.
  3. 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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Retrieve All Users

@app.get("/users/", response_model=list[UserResponse])
def get_users(db: Session = Depends(get_db)):
    return db.query(User).all()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"}
Enter fullscreen mode Exit fullscreen mode

5️⃣ Run the Application

Run your application using Uvicorn:

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

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:

  1. 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}'
Enter fullscreen mode Exit fullscreen mode
  1. Get All Users:
   curl -X GET "http://127.0.0.1:8000/users/"
Enter fullscreen mode Exit fullscreen mode
  1. 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}'
Enter fullscreen mode Exit fullscreen mode
  1. Delete a User:
   curl -X DELETE "http://127.0.0.1:8000/users/1"
Enter fullscreen mode Exit fullscreen mode

🌟 Key Features of This Example

  1. FastAPI's Speed and Simplicity:

    • FastAPI automatically validates data and generates interactive documentation.
  2. SQLAlchemy Integration:

    • SQLAlchemy makes database management seamless with its ORM.
  3. 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)