Stop 13 · Choose a Path: Web, Data or AIWeb & APIs · 3/6

FastAPI & REST APIs

Part of the Python Roadmap

In short

Mobile apps, React front ends and other services all talk to backends through APIs. FastAPI lets you write one with plain type hints and get validation and live documentation for free.

FastAPI builds fast REST APIs using type hints and Pydantic models for automatic validation, and it generates interactive documentation at /docs. It also supports async endpoints out of the box.

The jaadu stands at a busy food court counter checking a customer's order slip against a big illustrated menu board before sliding a steaming tray across.

Think of it like this

Ordering at a restaurant counter

A food court counter has a printed menu (the API docs), a fixed order format (the request body), and clear replies: here's your food (200), we added your order (201), that dish doesn't exist (404), you forgot to choose a size (422). FastAPI checks every order slip against the menu before the kitchen even sees it.

Watch it happen

Two requests to an expenses API

App
FastAPI
Storage

POST /expenses {title, amount: -50}

1/5The app sends a new expense with a negative amount.

The big ideas

What you need to know

REST in one line

Resources live at URLs like /expenses, and HTTP methods say what to do: GET reads, POST creates, PUT or PATCH updates, DELETE removes.

Type hints validate

Pydantic models describe the body. Wrong types or missing fields get an automatic 422 error with details.

Docs for free

Open /docs to see interactive Swagger UI where you can try every endpoint in the browser.

Path vs query

/expenses/{expense_id} is a path parameter for one item. ?category=food&limit=10 are query parameters for filtering.

See it in code

Walk through the code

python
1from fastapi import FastAPI, HTTPException2from pydantic import BaseModel, Field3 4app = FastAPI(title="Expenses API")5 6class ExpenseIn(BaseModel):7    title: str8    amount: float = Field(gt=0)9    category: str = "food"10 11class Expense(ExpenseIn):12    id: int13 14expenses: dict[int, Expense] = {}15 16@app.post("/expenses", status_code=201)17def create_expense(item: ExpenseIn) -> Expense:18    new_id = len(expenses) + 119    expense = Expense(id=new_id, **item.model_dump())20    expenses[new_id] = expense21    return expense22 23@app.get("/expenses/{expense_id}")24def read_expense(expense_id: int) -> Expense:25    if expense_id not in expenses:26        raise HTTPException(status_code=404, detail="Expense not found")27    return expenses[expense_id]28 29@app.get("/expenses")30def list_expenses(category: str | None = None, limit: int = 10) -> list[Expense]:31    items = [e for e in expenses.values() if category is None or e.category == category]32    return items[:limit]

1/5The request body model. Field(gt=0) means amount must be greater than zero, and category has a default.

Install with pip install "fastapi[standard]" and run fastapi dev main.py. Then open http://127.0.0.1:8000/docs.

Save yourself the pain

Common mistakes

Oops

Returning 200 for everything, even errors.

Do this instead

Use proper status codes: 201 for created, 404 for not found, 400 or 422 for bad input. Clients depend on them.

Oops

Using verbs in URLs like /getExpense or /deleteExpense.

Do this instead

Use nouns for resources and let the method carry the action: GET /expenses/7, DELETE /expenses/7.

Oops

Calling slow blocking code, like requests.get, inside an async def endpoint.

Do this instead

Use a plain def endpoint for blocking code (FastAPI runs it in a thread pool), or use an async library like httpx inside async def.

Your mission

Finish the CRUD

~35 min

Quick check

In FastAPI, a function parameter that is not part of the path and has a simple type like int becomes...

Go deeper

  1. 1Build GET and POST endpoints for a simple resource like books.
  2. 2Define a Pydantic model for the request body and send invalid data to see validation errors.
  3. 3Explore and test your API from the automatic /docs page.

More web & apis at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge