DEV Community

Sakshi Agarwal
Sakshi Agarwal

Posted on

Creating a Basic FastAPI Application with CRUD Operations

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

Enter fullscreen mode Exit fullscreen mode

πŸ—‚οΈ Project Structure

fastapi-crud/
β”‚
β”œβ”€β”€ main.py
└── models.py
Enter fullscreen mode Exit fullscreen mode

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

βš™οΈ 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"}
Enter fullscreen mode Exit fullscreen mode

▢️ Step 3: Run the Application

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

API will be available at:

http://127.0.0.1:8000
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Step 4: Test Using Swagger UI

FastAPI automatically provides beautiful interactive API docs.

Open:

http://127.0.0.1:8000/docs
Enter fullscreen mode Exit fullscreen mode

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)