Skip to main content

APIs · Beginner · 22 min

How to Build a REST API with FastAPI

By Padding · Updated 15 Nov 2026
FastAPI 0.163 · Python 3.15

You will build a small items API with FastAPI 0.163 on Python 3.15 that validates its input, returns the right HTTP status codes, never shows a stack trace to callers, documents itself, and has automated tests.

On this page

A REST API exposes things such as items, users or orders at addresses, and lets clients read and change them with the HTTP methods: GET to read, POST to create, PUT to replace, DELETE to remove. The part that separates a good API from a fragile one is what happens with bad input: it should be rejected with a clear message and the right status code, and it should never expose the inside of your server.

FastAPI is a Python framework built for this. You declare the shape of your data with type hints and Pydantic models. FastAPI then validates every request against them, converts the data, writes the error responses, and generates interactive documentation. This tutorial builds an items API step by step. It keeps its data in memory, so restarting the server clears it: the next tutorials in the API series replace that with a database and add authentication. For a first look at calling an API, see the httpx tutorial.

Step 1 · Create the project and install FastAPI

Make a folder and add FastAPI with its standard extras. They bring the fastapi command and the Uvicorn server that runs your app. The version range allows patch releases of 0.163 only:

Bash
mkdir -p ~/items-api
cd ~/items-api
uv init --no-package
uv add "fastapi[standard]>=0.163,<0.164"

uv creates .venv, installs the packages, and records them in pyproject.toml. It also writes a starter main.py, which you replace in the next step.

Check it worked

Bash
uv run python -c "import fastapi, pydantic; print(fastapi.__version__, pydantic.VERSION)"

The output is 0.163.1 2.14.3, or later patch releases of the same lines.

Step 2 · Write the first endpoint

Replace main.py with the smallest app that does something: one route that returns a short status message.

Bash
cat > main.py <<'PY'
from fastapi import FastAPI

app = FastAPI(title="Items API", version="1.0.0")


@app.get("/api/health")
def health():
    return {"status": "ok"}
PY

FastAPI(...) creates the application. The @app.get line registers the function for GET /api/health. Whatever the function returns is converted to JSON.

Start the development server in a second terminal, in the project folder. It restarts on its own whenever you save a file, so leave it running for the rest of the tutorial:

Bash
cd ~/items-api
uv run fastapi dev main.py

The server prints a line like Uvicorn running on http://127.0.0.1:8000. fastapi dev listens on your own computer only. Leave that as it is while you develop.

Check it worked

In the first terminal:

Bash
curl -s -w '\n' http://127.0.0.1:8000/api/health

The output is {"status":"ok"}.

Step 3 · Describe your data with models

Replace main.py with the full API. Read it once through before you run it. The comments below explain the parts:

Bash
cat > main.py <<'PY'
from itertools import count
from typing import Annotated

from fastapi import FastAPI, HTTPException, Query, Response, status
from pydantic import BaseModel, ConfigDict, Field

app = FastAPI(title="Items API", version="1.0.0")


class ItemIn(BaseModel):
    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)

    title: Annotated[str, Field(min_length=1, max_length=100)]
    done: bool = False


class Item(ItemIn):
    id: int


items: dict[int, Item] = {}
ids = count(1)


@app.get("/api/health")
def health():
    return {"status": "ok"}


@app.get("/api/items")
def list_items(
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    done: bool | None = None,
) -> list[Item]:
    found = [i for i in items.values() if done is None or i.done == done]
    return found[:limit]


@app.post("/api/items", status_code=status.HTTP_201_CREATED)
def create_item(data: ItemIn, response: Response) -> Item:
    item = Item(id=next(ids), **data.model_dump())
    items[item.id] = item
    response.headers["Location"] = f"/api/items/{item.id}"
    return item


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


@app.put("/api/items/{item_id}")
def replace_item(item_id: int, data: ItemIn) -> Item:
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    items[item_id] = Item(id=item_id, **data.model_dump())
    return items[item_id]


@app.delete("/api/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int) -> None:
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]
PY
  • ItemIn is what a client sends. title must be 1 to 100 characters, and done defaults to false. extra="forbid" rejects fields you did not define, so a typo such as titel is an error instead of being silently ignored. str_strip_whitespace trims spaces around text before the length check, so a title of only spaces counts as empty.
  • Item is what the API returns: the same fields plus an id that the server assigns. Because the functions declare -> Item, FastAPI uses that model to build the response, and fields that are not in it never leak out.
  • Query(ge=1, le=100) limits the limit parameter to 1 through 100. item_id: int means that /api/items/abc is rejected before your code runs.
  • Success codes are explicit: 201 Created with a Location header for a new item, and 204 No Content for a delete. Errors raise HTTPException, which becomes a JSON body of the form {"detail": "..."}.
  • items and ids are plain module variables, a stand-in for a database.

The server in the second terminal reloads when the file changes.

Step 4 · Create and read items

Create two items with POST. --json sets the content type for you. -i shows the status line and headers. FastAPI's JSON has no newline at the end, so -w '\n' makes curl add one, which keeps your prompt on its own line:

Bash
curl -si -w '\n' --json '{"title": "Learn FastAPI"}' http://127.0.0.1:8000/api/items
curl -s -w '\n' --json '{"title": "Write tests", "done": true}' http://127.0.0.1:8000/api/items

The first response starts with HTTP/1.1 201 Created and has location: /api/items/1. Its body is {"title":"Learn FastAPI","done":false,"id":1}. The second creates item 2. Now read them back:

Bash
curl -s -w '\n' http://127.0.0.1:8000/api/items
curl -s -w '\n' http://127.0.0.1:8000/api/items/1
curl -s -w '\n' 'http://127.0.0.1:8000/api/items?done=true'

The first prints both items in a list. The second prints item 1. The third prints only item 2, the one marked done.

Check it worked

Bash
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/items/2

The output is 200.

Step 5 · Replace and delete

PUT replaces an item with the data you send. DELETE removes it:

Bash
curl -s -w '\n' -X PUT --json '{"title": "Learn FastAPI well", "done": true}' http://127.0.0.1:8000/api/items/1
curl -si -w '\n' -X DELETE http://127.0.0.1:8000/api/items/2
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/items/2

The first returns the updated item. The delete answers HTTP/1.1 204 No Content with an empty body. The last request prints 404, because the item is gone.

Step 6 · See how bad input is rejected

Send things that are wrong, and read the answers. FastAPI answers with 422 Unprocessable Entity and says which field failed:

Bash
curl -s -w '\n%{http_code}\n' --json '{"title": ""}' http://127.0.0.1:8000/api/items
curl -s -w '\n%{http_code}\n' --json '{"titel": "typo"}' http://127.0.0.1:8000/api/items
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/api/items/abc
curl -s -w '\n%{http_code}\n' 'http://127.0.0.1:8000/api/items?limit=1000'
curl -s -w '\n%{http_code}\n' --json '{not json' http://127.0.0.1:8000/api/items

The first four give 422 with a JSON body whose detail list names the problem: for example "type":"string_too_short" with "loc":["body","title"] for the empty title, "type":"missing" plus "type":"extra_forbidden" for the typo (the real field is missing and the unknown one is not allowed), "type":"int_parsing" for abc, and "type":"less_than_equal" for the limit. The last, with a body that is not JSON at all, gives 422 as well, with a json_invalid error. The messages tell the caller what to fix and contain nothing about your server. A missing item is a different case, handled by your own code: 404 with {"detail":"Item not found"}.

Check it worked

Bash
curl -s -o /dev/null -w '%{http_code}\n' --json '{"title": "   "}' http://127.0.0.1:8000/api/items

The output is 422, because a title of only spaces is empty once the spaces are stripped.

Step 7 · Keep stack traces away from callers

A bug in your code raises an exception, and the caller must not see the traceback, file paths or variable values. They help an attacker and mean nothing to a user. FastAPI does not send them: an unhandled exception becomes a plain 500 Internal Server Error, and the traceback goes to the server's log. See it with a throwaway app that has a deliberate bug. Make a second file, crash.py, and run it on another port:

Bash
cat > crash.py <<'PY'
from fastapi import FastAPI

app = FastAPI()


@app.get("/crash")
def crash():
    secret_total = 0
    return {"ratio": 1 / secret_total}
PY
Bash
uv run fastapi run crash.py --host 127.0.0.1 --port 8001

Call it from the first terminal:

Bash
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8001/crash

The output is Internal Server Error and 500. Look at the terminal that runs the crash server. It logs the full traceback with the line ZeroDivisionError: division by zero, which only you can see.

Stop that server with Ctrl+C. One setting could undo this. Never run a production server with debug=True on the app or with a development server mode that shows tracebacks in responses, and keep fastapi dev for your own machine. To return JSON instead of plain text for unexpected errors, register a handler for Exception that returns JSONResponse({"detail": "Internal server error"}, status_code=500). Keep the real error in your logs.

Delete the throwaway file:

Bash
rm crash.py

Step 8 · Read the generated documentation

FastAPI builds an OpenAPI description of your API from the code and serves interactive documentation from it. With the server running, open http://127.0.0.1:8000/docs in a browser. You see every route, its parameters and its models, and you can send requests from the page. http://127.0.0.1:8000/redoc is a read-only view, and /openapi.json is the machine-readable file that tools use to generate client code.

Check it worked

Bash
curl -s http://127.0.0.1:8000/openapi.json | python3 -c "import json,sys; d=json.load(sys.stdin); print(d['info']['title'], sorted(d['paths']))"

The output is Items API ['/api/health', '/api/items', '/api/items/{item_id}'].

If your API will be public, consider turning the documentation pages off in production with FastAPI(docs_url=None, redoc_url=None), or protecting them, since they describe every route.

Step 9 · Write automated tests

Clicking and curl are good for exploring. Tests keep the behaviour from breaking later. FastAPI has a TestClient that calls your app in-process, with no server and no network. It needs httpx, and pytest runs the tests. Add both as development dependencies:

Bash
uv add --dev pytest httpx
mkdir -p tests

Write tests for the success path, a missing item and bad input. The fixture empties the store before each test, so tests do not depend on each other:

Bash
cat > tests/test_items.py <<'PY'
from itertools import count

import pytest
from fastapi.testclient import TestClient

import main

client = TestClient(main.app)


@pytest.fixture(autouse=True)
def empty_store():
    main.items.clear()
    main.ids = count(1)


def test_create_and_read_item():
    created = client.post("/api/items", json={"title": "Learn FastAPI"})
    assert created.status_code == 201
    assert created.headers["location"] == "/api/items/1"
    assert created.json() == {"id": 1, "title": "Learn FastAPI", "done": False}
    assert client.get("/api/items/1").json() == created.json()


def test_missing_item_is_404():
    response = client.get("/api/items/99")
    assert response.status_code == 404
    assert response.json() == {"detail": "Item not found"}


@pytest.mark.parametrize(
    "body",
    [{"title": ""}, {"title": "   "}, {"titel": "typo"}, {"title": "x" * 101}, {}],
)
def test_bad_input_is_422(body):
    assert client.post("/api/items", json=body).status_code == 422


def test_delete_returns_204_then_404():
    client.post("/api/items", json={"title": "Temporary"})
    assert client.delete("/api/items/1").status_code == 204
    assert client.delete("/api/items/1").status_code == 404


def test_filter_by_done():
    client.post("/api/items", json={"title": "One"})
    client.post("/api/items", json={"title": "Two", "done": True})
    titles = [i["title"] for i in client.get("/api/items", params={"done": True}).json()]
    assert titles == ["Two"]
PY

python -m pytest adds the project folder to the import path, so import main works. Run it:

Bash
uv run python -m pytest -q

The output ends with 9 passed, with five of those from the parametrised bad-input test.

Step 10 · Run it for real

fastapi dev is for development. It reloads on changes and listens on your own computer. To run the API for other people, use fastapi run, which runs without reload and listens on all addresses by default:

Bash
uv run fastapi run main.py --port 8000

On a server you would run it as a service behind a reverse proxy that handles HTTPS: see run your app as a systemd service and nginx as a reverse proxy. When a proxy sits in front, fastapi run reads the X-Forwarded-For and X-Forwarded-Proto headers so the app sees the client's real address and scheme, and --forwarded-allow-ips (see fastapi run --help) says which proxies it trusts. Because the data here lives in memory, run one worker only. More workers would each have their own copy of the items.

Troubleshooting

  • Address already in use on startup means another process uses port 8000. Stop it, or start FastAPI with --port 8010.
  • 422 for a request you thought was valid: read the loc and msg in the response. A missing Content-Type: application/json header, or a body sent with -d instead of --json, is the usual cause.
  • ModuleNotFoundError: No module named 'main' when running pytest means you ran pytest directly. Use uv run python -m pytest.
  • Your edit does not show up. fastapi dev reloads on save, but fastapi run does not: restart it.

Step 11 · Stop the server and clean up

Press Ctrl+C in the server terminal. The API folder contains only what you made here, so delete it:

Bash
cd ~
rm -rf ~/items-api

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.