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.

Operators at an international Bell System switchboard connecting calls

What you need

The project starts from an empty folder and does not depend on the first project.

Download the finished code (zip, 2 KB) View on GitHub

  • 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

  1. 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: the fastapi command, the uvicorn server and the httpx library that the tests run on.

    Windows (PowerShell or Command Prompt)

    Terminal
    mkdir fastapi-todo
    cd fastapi-todo
    python -m venv .venv
    .venv\Scripts\activate
    pip install "fastapi[standard]"

    macOS and Linux (Terminal)

    Terminal
    mkdir 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.0 and uvicorn-0.54.0. The command pip show fastapi shows 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.

  2. 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.get in 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.py
    from fastapi import FastAPI
    
    app = FastAPI(title="Task list")
    
    tasks = []
    
    @app.get("/tasks")
    def list_tasks():
        return tasks

    Start the server in development mode: it restarts every time you save the file.

    Terminal
    fastapi dev main.py

    Expected 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/tasks in 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.

  3. 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.py
    from 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 task
    • Field(min_length=1, max_length=200) sets limits on the title, and str_strip_whitespace=True first removes spaces at the edges. A title made only of spaces becomes empty and fails validation — just like in the first project.
    • data: TaskCreate among 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.
    • -> Task and -> list[Task] state what the function returns. FastAPI uses this hint to check the response and describe it in the documentation.
    • status_code=201 is the “Created” code: by REST rules a new record answers 201, not 200.
    • count(1) from the itertools module produces the numbers 1, 2, 3… one at a time on every next(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 201 and 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; the create_task function was not called:

    {
      "detail": [
        {
          "type": "string_too_short",
          "loc": [
            "body",
            "title"
          ],
          "msg": "String should have at least 1 character",
          "input": "   ",
          "ctx": {
            "min_length": 1
          }
        }
      ]
    }

    loc says where the error is: in the request body, the title field; msg says what is wrong. input shows the value as sent, with spaces, although the empty string was what got checked. Every time you save main.py, the server restarts and the task list is empty again: it lives in memory.

  4. 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 the find function and two routes at the end.

    main.py
    from 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 hint task_id: int makes FastAPI turn it into a number; the address /tasks/abc gets 422.
    • HTTPException(status_code=404, …) stops the function and answers the client with a code and a message. The lookup is moved into find so 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. -> None says the same.

    In /docs add 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 404 and the message from HTTPException:

    {
      "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 responses parameter; it doesn't change how the API works.

  5. Step 5. Explore the auto-documentation

    You didn't write the /docs page: FastAPI built it from the code. It describes routes, parameters, models and response codes in the OpenAPI standard — that is the /openapi.json file, 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” from FastAPI(title=…). Expand the Schemas section at the bottom: it holds the Task and TaskCreate models with their limits.

    What it should look like

    The /docs page: the title “Task list”, version 0.1.0, OAS 3.1 and four routes — GET /tasks, POST /tasks, GET /tasks/{task_id}, DELETE /tasks/{task_id}
    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 /docs and /redoc from the internet, from cdn.jsdelivr.net. Without internet these pages are blank, although the API itself works.

  6. Step 6. Test the API

    Create test_main.py next to main.py and install pytest. TestClient sends requests straight into the app, without a running server. The fixture with autouse=True empties the list before each test so the tests don't depend on each other.

    test_main.py
    import 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 == 422
    Terminal
    pip 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 -q flag 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=True from TaskCreate, the test test_empty_title_is_rejected fails: 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.

main.py — add at the end
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
test_main.py — add at the end
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.

The same API on two frameworks
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 .

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.