Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Beginner ⏱ 35 min

⚡ Build a REST API with FastAPI

🎯 What You'll Build

A fully working REST API with GET, POST, PUT, and DELETE endpoints — complete with automatic interactive documentation at /docs.

📋 What You'll Need

1

Install FastAPI and Uvicorn

FastAPI is the framework. Uvicorn is the server that runs it.

pip install fastapi uvicorn
2

Create your first endpoint

Create a file called main.py and add a basic GET route. FastAPI reads your type hints to validate data automatically.

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello from FastAPI!"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}
💡 Tip: Run it with: uvicorn main:app --reload — the --reload flag auto-restarts whenever you save.
3

Run the server and test it

Start the server, then open your browser. FastAPI auto-generates interactive docs.

uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000
INFO:     Started reloader process
INFO:     Application startup complete.
💡 Tip: Open http://127.0.0.1:8000/docs in your browser — you get a full interactive API explorer for free. No extra code needed.
4

Add a data model with POST

Use Pydantic models to define the shape of incoming data. FastAPI validates it automatically and returns clear error messages if the data is wrong.

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

# In-memory store (use a database in production)
items = {}

class Item(BaseModel):
    name: str
    price: float
    in_stock: bool = True
    description: Optional[str] = None

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

@app.post("/items/{item_id}")
def create_item(item_id: int, item: Item):
    items[item_id] = item
    return {"message": "Created", "item": item}
5

Add PUT and DELETE

Complete the CRUD API with update and delete endpoints.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional

app = FastAPI()
items = {}

class Item(BaseModel):
    name: str
    price: float
    in_stock: bool = True
    description: Optional[str] = None

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

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

@app.post("/items/{item_id}")
def create_item(item_id: int, item: Item):
    items[item_id] = item
    return {"message": "Created", "item": item}

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    items[item_id] = item
    return {"message": "Updated", "item": item}

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]
    return {"message": "Deleted"}
# POST /items/1  with body: {"name": "Laptop", "price": 999.99}
{"message": "Created", "item": {"name": "Laptop", "price": 999.99, "in_stock": true, "description": null}}

# GET /items/1
{"name": "Laptop", "price": 999.99, "in_stock": true, "description": null}

# DELETE /items/1
{"message": "Deleted"}
💡 Tip: Test all your endpoints right from the browser at http://127.0.0.1:8000/docs — no Postman needed. For a real app, swap the in-memory dict for a database like SQLite using SQLAlchemy.

🎉 You Did It!

You built a full CRUD REST API with automatic validation and interactive documentation. FastAPI is one of the fastest Python frameworks — and the /docs page alone makes it worth learning.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.