Logo

dev-resources.site

for different kinds of informations.

๐Ÿš€ Building a User Management API with FastAPI and SQLite

Published at
12/8/2024
Categories
fastapi
python
sqlite
api
Author
blamsa0mine
Categories
4 categories in total
fastapi
open
python
open
sqlite
open
api
open
Author
11 person written this
blamsa0mine
open
๐Ÿš€ 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": "[email protected]", "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": "[email protected]", "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! ๐Ÿ‘จโ€๐Ÿ’ป๐Ÿ‘ฉโ€๐Ÿ’ป

sqlite Article's
30 articles in total
Favicon
Android SQLite Crud Tutorial
Favicon
๐Ÿš€ Building a User Management API with FastAPI and SQLite
Favicon
How to Use SQLite in Vue 3: Complete Guide to Offline-First Web Apps
Favicon
Building a Simple SQLite Library Manager in Python
Favicon
MySQL vs SQLite ุฃูŠู‡ู…ุง ุฃูุถู„ ุŸ
Favicon
How to setup Ghost in a VPS using Docker, Mailgun and SQLite
Favicon
Java JDBC + IntelliJ + SQLite - A Beginner's Walkthrough
Favicon
Cloudflare D1 and Prisma: Not a Good Combination (For Now)
Favicon
How to Query CSV Files with SQLite
Favicon
Deploy FastAPI application with SQLite on Fly.io
Favicon
How to import excel into sqlite only 1 step
Favicon
PostgreSQL vs. SQLite: read & write in multithreaded environment
Favicon
PostgreSQL vs. SQLite: ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ์˜ ์ฝ๊ธฐ-์“ฐ๊ธฐ
Favicon
Sometimes it's the little things
Favicon
Tauri 2.0 - Sqlite DB - React
Favicon
SQLite Database Recovery
Favicon
Streamlining Your Rails 8 App: Migrating from Postgres to SQLite
Favicon
I still prefer SQLite for little things you know.
Favicon
How to Build Lightweight GraphRAG with SQLite
Favicon
Can You Create a Product That Makes Money with Wasm?
Favicon
Building a cache in Python
Favicon
Building a RESTful API with Laravel 11, A Completeย Guide
Favicon
In-Memory Database with SQLite
Favicon
Build your own SQLite, Part 2: Scanning large tables
Favicon
Fundamentos para Web APIs com .NET: Uma Introduรงรฃo ao Essencial com Entity Framework
Favicon
Multitenant Database Schemas
Favicon
Use SQLite as a Celery broker in Django
Favicon
Build your own SQLite, Part 1: Listing tables
Favicon
Hosting a simple Laravel application using Turso on Laravel Forge
Favicon
Introducing vectorlite: A Fast and Tunable Vector Search Extension for SQLite

Featured ones: