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:
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
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.
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"}
PYFastAPI(...) 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:
cd ~/items-api
uv run fastapi dev main.pyThe 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:
curl -s -w '\n' http://127.0.0.1:8000/api/healthThe 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:
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]
PYItemInis what a client sends.titlemust be 1 to 100 characters, anddonedefaults tofalse.extra="forbid"rejects fields you did not define, so a typo such astitelis an error instead of being silently ignored.str_strip_whitespacetrims spaces around text before the length check, so a title of only spaces counts as empty.Itemis what the API returns: the same fields plus anidthat 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 thelimitparameter to 1 through 100.item_id: intmeans that/api/items/abcis rejected before your code runs.- Success codes are explicit:
201 Createdwith aLocationheader for a new item, and204 No Contentfor a delete. Errors raiseHTTPException, which becomes a JSON body of the form{"detail": "..."}. itemsandidsare 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:
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/itemsThe 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:
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
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/items/2The output is 200.
Step 5 · Replace and delete
PUT replaces an item with the data you send. DELETE removes it:
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/2The 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:
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/itemsThe 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
curl -s -o /dev/null -w '%{http_code}\n' --json '{"title": " "}' http://127.0.0.1:8000/api/itemsThe 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:
cat > crash.py <<'PY'
from fastapi import FastAPI
app = FastAPI()
@app.get("/crash")
def crash():
secret_total = 0
return {"ratio": 1 / secret_total}
PYuv run fastapi run crash.py --host 127.0.0.1 --port 8001Call it from the first terminal:
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8001/crashThe 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:
rm crash.pyStep 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
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:
uv add --dev pytest httpx
mkdir -p testsWrite 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:
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"]
PYpython -m pytest adds the project folder to the import path, so import main works. Run it:
uv run python -m pytest -qThe 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:
uv run fastapi run main.py --port 8000On 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 useon startup means another process uses port 8000. Stop it, or start FastAPI with--port 8010.422for a request you thought was valid: read thelocandmsgin the response. A missingContent-Type: application/jsonheader, or a body sent with-dinstead of--json, is the usual cause.ModuleNotFoundError: No module named 'main'when running pytest means you ranpytestdirectly. Useuv run python -m pytest.- Your edit does not show up.
fastapi devreloads on save, butfastapi rundoes 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:
cd ~
rm -rf ~/items-apiNext steps
- Make the server answer only to people who log in: add JWT authentication to a FastAPI API.
- Put an LLM behind an endpoint like this one: build a RAG question-answering endpoint.
- Learn more about the test tool: test Python code with pytest.
- Explore requests with curl: test and debug an API with curl.
Related tutorials
- How to Use Virtual Environments and Install Packages in PythonYou will create an isolated Python 3.15 environment for a project, install a package into it with pip, record the exact versions, rebuild the environment from that record, and then manage the same project with uv.
- How to Write and Run Tests in Python with pytestYou will install pytest 9.2 in a uv project, write tests for a small price-parsing module, run many cases from one test with parametrize, read a failure and fix the code, and use a fixture that gives each test its own temporary folder.
- How to Call a Web API from Python with httpxYou will install httpx 0.28, write a small local API to practise on, then call it from Python by fetching JSON, add query parameters and a reusable client, handle bad statuses, timeouts and network failures, send JSON in a POST request, and make several requests at once with async code.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials