FastAPI is one of the fastest-growing Python frameworks for building modern APIs. It is fast, easy to use, and comes with built-in data validation using Pydantic.
π What We Will Build
A simple API that manages Items with the following fields:
- id
- name
- description
- price
- in_stock
We will implement:
- Create an item
- Read all items / single item
- Update an item
- Delete an item
π¦ Project Setup
Ensure you have Python 3.8+ installed.
Install FastAPI & Uvicorn
pip install fastapi uvicorn
ποΈ Project Structure
fastapi-crud/
β
βββ main.py
βββ models.py
π§± Step 1: Create the Pydantic Model (models.py)
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
description: str | None = None
price: float
in_stock: bool = True
βοΈ Step 2: Build FastAPI CRUD Endpoints (main.py)
from fastapi import FastAPI, HTTPException
from models import Item
app = FastAPI()
# Temporary in-memory database
items_db = {}
# Create an Item
@app.post("/items", status_code=201)
def create_item(item: Item):
if item.id in items_db:
raise HTTPException(status_code=400, detail="Item already exists")
items_db[item.id] = item
return {"message": "Item created successfully", "item": item}
# Read All Items
@app.get("/items")
def get_items():
return list(items_db.values())
# Read Single Item
@app.get("/items/{item_id}")
def get_item(item_id: int):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
return items_db[item_id]
# Update Item
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
items_db[item_id] = item
return {"message": "Item updated", "item": item}
# Delete Item
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
del items_db[item_id]
return {"message": "Item deleted"}
βΆοΈ Step 3: Run the Application
uvicorn main:app --reload
API will be available at:
http://127.0.0.1:8000
π§ͺ Step 4: Test Using Swagger UI
FastAPI automatically provides beautiful interactive API docs.
Open:
http://127.0.0.1:8000/docs
You can test all CRUD operations directly there.
π― Summary
We learned how to build a clean FastAPI application with:
- Pydantic models
- CRUD Routes
- In-memory storage
- Automatic interactive API documentatio n
Top comments (0)