First API with FastAPI
The same “task list” app, but without pages: the server receives and returns JSON. FastAPI validates data with Pydantic models, answers with the right status codes by itself and builds documentation where you can try the API. About 40 minutes.
HTTP methods, JSON and status codes are explained in “REST API” — have a look there first.
What you need
The project starts from an empty folder and does not depend on the first project.
- Python 3.12 or newer: the command
python --version. - An understanding of the GET, POST and DELETE methods and the 200, 201 and 404 codes — the “REST API” section.
- A completed first project helps for comparison but is not required.
We send requests from the browser. The address bar is enough for GET, and POST and DELETE are easy to send from the /docs page that FastAPI creates by itself — this works the same on Windows, macOS and Linux. Completed steps are saved in this browser.
The task list API
Four routes: the list, adding, a single task and deleting. Then the documentation and tests.
0 of 6 steps done
-
Step 1. Create a project and install FastAPI
A new folder and its own virtual environment, as in the first project. The word
[standard]in quotes installs, together with FastAPI, everything you need later: thefastapicommand, theuvicornserver and thehttpxlibrary that the tests run on.Windows (PowerShell or Command Prompt)
Terminalmkdir fastapi-todo cd fastapi-todo python -m venv .venv .venv\Scripts\activate pip install "fastapi[standard]"macOS and Linux (Terminal)
Terminalmkdir fastapi-todo cd fastapi-todo python3 -m venv .venv source .venv/bin/activate pip install "fastapi[standard]"Expected result
The last line of the installation is long: it lists almost 60 packages, among them
fastapi-0.163.1,pydantic-2.14.3,starlette-1.10.0anduvicorn-0.54.0. The commandpip show fastapishows the FastAPI version:Name: fastapi Version: 0.163.1 Summary: FastAPI framework, high performance, easy to learn, fast to code, ready for production
The version number may be newer — that's fine. Without quotes around
fastapi[standard]some terminals (for example, zsh on macOS) won't understand the square brackets. -
Step 2. The first route: the task list
Create a file
main.py. The@app.get("/tasks")decorator links an address and the GET method to a function — just like@app.getin Flask. The difference is in the response: the function returns an ordinary Python list, and FastAPI turns it into JSON by itself. For now the tasks are kept in the server's memory.main.pyfrom fastapi import FastAPI app = FastAPI(title="Task list") tasks = [] @app.get("/tasks") def list_tasks(): return tasksStart the server in development mode: it restarts every time you save the file.
Terminalfastapi dev main.pyExpected result
The terminal shows the server address and the documentation address and stays busy with the server:
⚡️ Starting FastAPI in development mode 🐍 Using import string: main:app 🌐 Server started at http://127.0.0.1:8000 Documentation at http://127.0.0.1:8000/docs Logs: INFO: Will watch for changes in these directories: ['…/fastapi-todo'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [629] using WatchFiles INFO: Started server process [632] INFO: Waiting for application startup. INFO: Application startup complete.The address
http://127.0.0.1:8000/tasksin the browser shows an empty list in JSON:[].The Will watch for changes line will show the full path to your folder (its beginning is shortened to … here), and the process numbers in square brackets will be different too. Don't close this window; type commands in a second terminal window.
-
Step 3. Pydantic models and adding a task
Replace the whole
main.py. Pydantic models describe data as classes with type hints, and FastAPI uses them to validate the request and build the response. There are two models because the data differs in each direction: the client sends only the title (TaskCreate), while the server assigns the number and the “done” mark (Task).main.pyfrom itertools import count from fastapi import FastAPI from pydantic import BaseModel, ConfigDict, Field app = FastAPI(title="Task list") class TaskCreate(BaseModel): model_config = ConfigDict(str_strip_whitespace=True) title: str = Field(min_length=1, max_length=200) class Task(BaseModel): id: int title: str done: bool = False tasks: dict[int, Task] = {} ids = count(1) @app.get("/tasks") def list_tasks() -> list[Task]: return list(tasks.values()) @app.post("/tasks", status_code=201) def create_task(data: TaskCreate) -> Task: task = Task(id=next(ids), title=data.title) tasks[task.id] = task return taskField(min_length=1, max_length=200)sets limits on the title, andstr_strip_whitespace=Truefirst removes spaces at the edges. A title made only of spaces becomes empty and fails validation — just like in the first project.data: TaskCreateamong the function's parameters means “read the request body as JSON and validate it against the model”. If validation fails, the function is not even called: FastAPI answers with code 422 by itself.-> Taskand-> list[Task]state what the function returns. FastAPI uses this hint to check the response and describe it in the documentation.status_code=201is the “Created” code: by REST rules a new record answers 201, not 200.count(1)from theitertoolsmodule produces the numbers 1, 2, 3… one at a time on everynext(ids).
Let's send a request. Open
http://127.0.0.1:8000/docs, expand the POST /tasks row, click Try it out, type{"title": "Buy bread"}into the Request body field and click Execute. Then send{"title": " "}— three spaces — the same way.Expected result
The first request: code
201and the created task in the Response body field:{ "id": 1, "title": "Buy bread", "done": false }The second request: code
422. This is Pydantic's answer; thecreate_taskfunction was not called:{ "detail": [ { "type": "string_too_short", "loc": [ "body", "title" ], "msg": "String should have at least 1 character", "input": " ", "ctx": { "min_length": 1 } } ] }locsays where the error is: in the request body, thetitlefield;msgsays what is wrong.inputshows the value as sent, with spaces, although the empty string was what got checked. Every time you savemain.py, the server restarts and the task list is empty again: it lives in memory. -
Step 4. One task, deleting and the 404 code
Let's add reading a single task and deleting. Replace the whole
main.py: the new parts are thefindfunction and two routes at the end.main.pyfrom itertools import count from fastapi import FastAPI, HTTPException from pydantic import BaseModel, ConfigDict, Field app = FastAPI(title="Task list") class TaskCreate(BaseModel): model_config = ConfigDict(str_strip_whitespace=True) title: str = Field(min_length=1, max_length=200) class Task(BaseModel): id: int title: str done: bool = False tasks: dict[int, Task] = {} ids = count(1) def find(task_id: int) -> Task: if task_id not in tasks: raise HTTPException(status_code=404, detail="Task not found") return tasks[task_id] @app.get("/tasks") def list_tasks() -> list[Task]: return list(tasks.values()) @app.post("/tasks", status_code=201) def create_task(data: TaskCreate) -> Task: task = Task(id=next(ids), title=data.title) tasks[task.id] = task return task @app.get("/tasks/{task_id}") def get_task(task_id: int) -> Task: return find(task_id) @app.delete("/tasks/{task_id}", status_code=204) def delete_task(task_id: int) -> None: del tasks[find(task_id).id]{task_id}in the address is a path parameter. The hinttask_id: intmakes FastAPI turn it into a number; the address/tasks/abcgets 422.HTTPException(status_code=404, …)stops the function and answers the client with a code and a message. The lookup is moved intofindso the check isn't repeated in every route.- Deleting answers
204 No Content: it worked and there is nothing to show, so the response has no body.-> Nonesays the same.
In
/docsadd two tasks (“Buy bread” and “Learn FastAPI”), then open GET /tasks/{task_id} with number 1 and with number 99, delete task 1 with DELETE and request the whole list again.Expected result
Adding returns tasks numbered 1 and 2 (code
201):{ "id": 1, "title": "Buy bread", "done": false }{ "id": 2, "title": "Learn FastAPI", "done": false }Task 1 — code
200:{ "id": 1, "title": "Buy bread", "done": false }There is no task 99 — code
404and the message fromHTTPException:{ "detail": "Task not found" }Deleting — code
204, no body; Swagger shows only the response headers:Code 204
One task is left in the list:
[ { "id": 2, "title": "Learn FastAPI", "done": false } ]For the 404 response Swagger says “Undocumented”: the route's description doesn't declare this code. You can declare it with the decorator's
responsesparameter; it doesn't change how the API works. -
Step 5. Explore the auto-documentation
You didn't write the
/docspage: FastAPI built it from the code. It describes routes, parameters, models and response codes in the OpenAPI standard — that is the/openapi.jsonfile, and/docs(Swagger UI) and/redoc(ReDoc) are two viewers for that file. Labels such as “List Tasks” come from the function names, and “Task list” fromFastAPI(title=…). Expand the Schemas section at the bottom: it holds theTaskandTaskCreatemodels with their limits.What it should look like
Swagger UI at /docs: the four routes from main.py. The /openapi.json link under the title opens the API description in JSON. The browser loads the look of
/docsand/redocfrom the internet, from cdn.jsdelivr.net. Without internet these pages are blank, although the API itself works. -
Step 6. Test the API
Create
test_main.pynext tomain.pyand install pytest.TestClientsends requests straight into the app, without a running server. The fixture withautouse=Trueempties the list before each test so the tests don't depend on each other.test_main.pyimport pytest from fastapi.testclient import TestClient import main client = TestClient(main.app) @pytest.fixture(autouse=True) def empty_list(): main.tasks.clear() def test_create_and_list(): response = client.post("/tasks", json={"title": "Buy bread"}) assert response.status_code == 201 task = response.json() assert task["title"] == "Buy bread" assert task["done"] is False assert client.get("/tasks").json() == [task] def test_empty_title_is_rejected(): response = client.post("/tasks", json={"title": " "}) assert response.status_code == 422 assert client.get("/tasks").json() == [] def test_missing_task_is_404(): response = client.get("/tasks/999") assert response.status_code == 404 assert response.json() == {"detail": "Task not found"} def test_delete(): task_id = client.post("/tasks", json={"title": "Delete me"}).json()["id"] assert client.delete(f"/tasks/{task_id}").status_code == 204 assert client.get(f"/tasks/{task_id}").status_code == 404 def test_id_must_be_a_number(): assert client.get("/tasks/abc").status_code == 422Terminalpip install pytest pytest -q- The tests check both successful responses (201, 200, 204) and errors: an empty title — 422, no task — 404, a number that isn't a number — 422.
- The task number is taken from the response (
.json()["id"]) rather than written in the test as a number: the counter is not reset between tests. - The
-qflag prints briefly: a dot for each passed test.
Expected result
..... [100%] 5 passed in 0.31s
Your time will differ. If you remove the line
str_strip_whitespace=TruefromTaskCreate, the testtest_empty_title_is_rejectedfails: three spaces become a valid title.
Test yourself
Answer in your head first, then open the answer.
Why two models, TaskCreate and Task, if the fields are almost the same?
They describe the two sides of the exchange. The client sends only the title — it must not choose the number or the “done” mark, so TaskCreate doesn't have them. The server returns the whole task — that is Task. If input went through Task, the client could send any id it liked.
Why did the server answer 422 to an empty title and not 400?
Code 422 Unprocessable Content means the request is well-formed (it is real JSON), but the data in it doesn't fit. That is how FastAPI answers any Pydantic validation error. Code 400 usually means the whole request is broken, for example a scrap of text arrived instead of JSON.
What happens to the tasks after the server restarts?
They are lost: the tasks dictionary lives in the program's memory, like the list in step 2 of the first project on Flask. To keep data you need a database — for example SQLite, as in the second project.
Why does deleting have code 204 and an empty response?
204 No Content means “it worked, and there is nothing more to say”. The task is gone, there is nothing to return, and the code is enough for the client. That is why the function has -> None and the decorator has status_code=204.
What does the -> Task hint after the function give you?
FastAPI checks the response against the model and lets only its fields through. If the function returns incomplete data by mistake, the server answers with error 500 and ResponseValidationError appears in the terminal — the error won't reach the client silently. This hint also adds an example response to /docs.
Exercise on your own
Add a PATCH /tasks/{task_id} route that marks a task as done or removes the mark. The request body is {"done": true} or {"done": false}, the response is the changed task, and a task that doesn't exist gets 404. Write a test for it.
Show the solution
You need a model for the request body and a new route. The find function from step 4 already answers 404.
class TaskUpdate(BaseModel):
done: bool
@app.patch("/tasks/{task_id}")
def update_task(task_id: int, data: TaskUpdate) -> Task:
task = find(task_id)
task.done = data.done
return task
def test_mark_done():
task_id = client.post("/tasks", json={"title": "To do"}).json()["id"]
response = client.patch(f"/tasks/{task_id}", json={"done": True})
assert response.status_code == 200
assert response.json()["done"] is True
assert client.get(f"/tasks/{task_id}").json()["done"] is True
assert client.patch("/tasks/999", json={"done": True}).status_code == 404
Check: pytest -q shows 6 passed. A green PATCH /tasks/{task_id} row appears in /docs.
Flask and FastAPI
The REST principles are the same. The difference is how much work the framework does by itself. An API example on Flask is in the “REST API” section.
| What you need | Flask | FastAPI |
|---|---|---|
| Read JSON from a request | request.get_json() by hand |
a function parameter with a Pydantic model |
| Validate data | your own if checks, and the 400 response by hand too |
limits in the model, a 422 response automatically |
| Turn the response into JSON | jsonify(…) or a dictionary |
any model object, list or dictionary |
| Documentation | written separately | /docs and /redoc from the code |
| Development server | flask run --debug |
fastapi dev (uvicorn inside) |
Common errors and how to fix them
The messages are shown exactly as FastAPI 0.163 and pytest print them. Click an error to see the fix.
«To use the fastapi command, please install "fastapi[standard]"»
To use the fastapi command, please install "fastapi[standard]" Only FastAPI itself is installed, without the fastapi command and the server. Run pip install "fastapi[standard]" — with the quotes — in the same environment.
422 «Input should be a valid integer»
{"detail":[{"type":"int_parsing","loc":["path","task_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]} The address has text instead of a task number, for example /tasks/abc. The task_id: int parameter accepts whole numbers only.
405 «Method Not Allowed»
{"detail":"Method Not Allowed"} The address exists, but with a different method. For example, DELETE /tasks without a number: deleting is declared only for /tasks/{task_id}. Check the method and the address in /docs.
Error 500 and “ResponseValidationError” in the terminal
fastapi.exceptions.ResponseValidationError: 1 validation error: {'type': 'missing', 'loc': ('response', 'title'), 'msg': 'Field required', 'input': {'id': 1}} The function returned data that doesn't fit -> Task: here a dictionary without title. Return a whole Task model object, as in step 3.
pytest: «ModuleNotFoundError: No module named 'main'»
E ModuleNotFoundError: No module named 'main' The test didn't find main.py. The files main.py and test_main.py must be in the same folder, and pytest must be run from it.
The /docs page is blank
The browser loads Swagger UI's look from cdn.jsdelivr.net. Without internet, or if the site is blocked, /docs and /redoc stay blank, while /openapi.json and all API routes work. Check the internet connection or send requests from the tests, as in step 6.
Sources
The code targets FastAPI 0.163 and Pydantic 2. All steps were run on Python 3.13, FastAPI 0.163.1 and Pydantic 2.14.3, sources checked on .
- FastAPI: first steps — the app, a route,
fastapi dev - FastAPI: request body — Pydantic models
- FastAPI: path parameters —
task_id: int - FastAPI: response model — the
-> Taskhint - FastAPI: response status code —
status_code=201 - FastAPI: handling errors —
HTTPException - FastAPI: testing —
TestClient - Pydantic: fields and constraints —
Field(min_length=…)
What's next
For now the tasks live in memory. How to store an API's data in SQLite and test it is shown in the second project — a blog API on Flask. The REST rules from this section apply to it unchanged.