โšก

API with FastAPI

๐Ÿง‘โ€๐Ÿณ Cookโฑ๏ธ 30 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขBasic Python
  • โ€ขREST APIs

What you'll build

A modern API with FastAPI in Python. Includes automatic documentation, data validation with Pydantic, and async support. FastAPI is Python's fastest API framework, ideal for AI backends and high-performance applications.


Installation

# With uv
uv init my-api
cd my-api
uv add fastapi uvicorn

# Or with pip
pip install fastapi uvicorn

Step 1: Ask an AI for the API

I need a REST API with FastAPI that:
- Full CRUD of items (create, read, update, delete)
- Validation with Pydantic
- Automatic documentation at /docs
- In-memory storage (list)
- 404 error handling
- Full typing

Give me the complete code in main.py.

Typical code

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    price: float

items: list[Item] = []

@app.get("/items")
def get_items():
    return items

@app.post("/items")
def create_item(item: Item):
    items.append(item)
    return item

@app.get("/items/{item_id}")
def get_item(item_id: int):
    for item in items:
        if item.id == item_id:
            return item
    raise HTTPException(status_code=404, detail="Item not found")

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    for i, item in enumerate(items):
        if item.id == item_id:
            return items.pop(i)
    raise HTTPException(status_code=404, detail="Item not found")

Run

uvicorn main:app --reload

Open http://localhost:8000/docs to see interactive documentation.


Next step

โ†’ Basic Web Scraper