- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Foundations of FastAPI
- Building Your First API — Task Manager (Part 1)
On this page
Building a Task Manager API: Part 1
Published on August 9, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
This project builds a working Task Manager API from nothing: a Pydantic model defining what a task looks like, an in-memory store standing in for a database, and five endpoints covering the full create-read-update-delete cycle. Every step below includes the exact code to write and an explanation of what it does — by the end, all five endpoints are working, testable directly from the browser, and extended with a filter, a partial-update route, and a response model that hides an internal field from the API's output.
Setting Up the Project​
Create a file named main.py, then install FastAPI along with its standard extras, which include Uvicorn:
pip install "fastapi[standard]"
Once the file below has content in it, start the development server:
fastapi dev main.py
This runs the app with auto-reload already enabled, restarting automatically whenever main.py changes.
Defining the Task Model​
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Task(BaseModel):
title: str
description: Optional[str] = None
completed: bool = False
title is required — every task needs one, and a request missing it fails validation before any endpoint code runs. description is optional, defaulting to None, so a task can be created without one. completed defaults to False, meaning a newly created task doesn't need to specify its status explicitly at all.
Creating an In-Memory Data Store​
tasks = {}
task_id_counter = 1
tasks is a plain dictionary standing in for a database table, keyed by task ID. task_id_counter tracks the next ID to assign. This is deliberately the simplest possible storage — it holds up fine for learning and local testing, but it's worth being clear about its real limitation: everything in tasks disappears the moment the server restarts, and a global counter like this one isn't safe if the app is ever run with more than one worker process, since two workers wouldn't share the same tasks dictionary or the same counter at all. Replacing this with an actual database is what removes both limitations, but that's outside the scope of what's being built here.
Creating a Task (POST /tasks)​
@app.post("/tasks", status_code=201)
def create_task(task: Task):
global task_id_counter
task_data = task.model_dump() # convert the validated model into a plain dict
task_data["id"] = task_id_counter # attach a unique id
tasks[task_id_counter] = task_data # store it, keyed by that id
task_id_counter += 1 # advance the counter for the next task
return task_data
task.model_dump() is the Pydantic v2 method for converting a validated model instance into a plain dictionary — this is what makes it possible to add the id field, since id isn't part of the Task model itself and can't be assigned directly onto a Pydantic instance's fields that weren't declared. status_code=201 overrides the default 200 status FastAPI would otherwise return: 201 Created is the conventional status for a request that successfully created a new resource, distinct from 200's more generic "the request succeeded."
Sending this request body to POST /tasks:
{
"title": "Buy milk",
"description": "From the store",
"completed": false
}
returns the same data with an id field added, confirming the task was stored.
Reading All Tasks (GET /tasks)​
@app.get("/tasks")
def get_all_tasks():
return list(tasks.values())
tasks.values() returns every stored task dictionary; wrapping it in list() turns that into something FastAPI can serialize directly into a JSON array.
Reading a Single Task (GET /tasks/{task_id})​
from fastapi import HTTPException
@app.get("/tasks/{task_id}")
def get_task(task_id: int):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
return tasks[task_id]
task_id is captured from the URL and validated as an int automatically. Since a nonexistent ID is a well-formed request that still can't succeed, checking for it and raising HTTPException(status_code=404, ...) is the correct tool here — this isn't something Pydantic's type-level validation could ever catch on its own.
Updating a Task (PUT /tasks/{task_id})​
@app.put("/tasks/{task_id}")
def update_task(task_id: int, updated_task: Task):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
task_data = updated_task.model_dump()
task_data["id"] = task_id
tasks[task_id] = task_data
return task_data
PUT conventionally replaces a resource in full, and this endpoint reflects that: updated_task requires every field Task declares as required, meaning a PUT request has to send the complete task data, not just the one field being changed — sending only {"completed": true} here fails validation, since title is still required. This distinction matters, and it's revisited directly below with a route built for partial updates instead.
Deleting a Task (DELETE /tasks/{task_id})​
@app.delete("/tasks/{task_id}", status_code=204)
def delete_task(task_id: int):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
del tasks[task_id]
204 No Content is the conventional status for a successful request that has nothing meaningful to return, which is exactly the case after a deletion — the function doesn't return anything, and FastAPI sends an empty response body to match the status code.
Exploring the Interactive Docs​
With the server running, http://127.0.0.1:8000/docs opens Swagger UI, listing all five endpoints with their expected request bodies and response shapes, and a "Try it out" button on each one that sends a real request from the browser. http://127.0.0.1:8000/redoc opens ReDoc, the same underlying schema laid out for reading rather than interactive testing. Both are generated automatically from the routes and models already written — nothing further needs to be added for either page to reflect the current state of the API.
The Complete API So Far​
MethodEndpointActionPOST/tasksCreate a taskGET/tasksRead all tasksGET/tasks/\{id\}Read one taskPUT/tasks/\{id\}Replace a taskDELETE/tasks/\{id\}Delete a task
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Task(BaseModel):
title: str
description: Optional[str] = None
completed: bool = False
tasks = {}
task_id_counter = 1
@app.post("/tasks", status_code=201)
def create_task(task: Task):
global task_id_counter
task_data = task.model_dump()
task_data["id"] = task_id_counter
tasks[task_id_counter] = task_data
task_id_counter += 1
return task_data
@app.get("/tasks")
def get_all_tasks():
return list(tasks.values())
@app.get("/tasks/{task_id}")
def get_task(task_id: int):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
return tasks[task_id]
@app.put("/tasks/{task_id}")
def update_task(task_id: int, updated_task: Task):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
task_data = updated_task.model_dump()
task_data["id"] = task_id
tasks[task_id] = task_data
return task_data
@app.delete("/tasks/{task_id}", status_code=204)
def delete_task(task_id: int):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
del tasks[task_id]
Extending the API​
Filtering tasks by completion status​
Adding an optional query parameter to the existing get_all_tasks route makes filtering possible without a separate endpoint:
@app.get("/tasks")
def get_all_tasks(completed: Optional[bool] = None):
if completed is None:
return list(tasks.values())
return [t for t in tasks.values() if t["completed"] == completed]
completed defaults to None, meaning "no filter requested" — GET /tasks with no query string still returns every task, exactly as before. GET /tasks?completed=true now returns only tasks where completed is True, and GET /tasks?completed=false returns only the incomplete ones, using the same boolean-string conversion already built into FastAPI's query parameter handling.
Toggling completion with PATCH​
PUT was defined earlier to replace a task's full data. PATCH fits a narrower, more common action — flipping a task's completion status — without requiring the entire task body to be resent:
@app.patch("/tasks/{task_id}/toggle")
def toggle_task(task_id: int):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
tasks[task_id]["completed"] = not tasks[task_id]["completed"]
return tasks[task_id]
This route takes no request body at all — the action is implicit in the endpoint itself: flip whatever the current value is. Calling PATCH /tasks/1/toggle twice in a row returns the task first as completed, then back as not completed, with each call fully independent of the last.
Hiding an internal field with a response model​
Suppose task creation is extended to also record which user owns the task, a field with no reason to be shown back to whoever's reading the task list:
@app.post("/tasks", status_code=201)
def create_task(task: Task):
global task_id_counter
task_data = task.model_dump()
task_data["id"] = task_id_counter
task_data["owner_id"] = 1 # placeholder until user accounts are introduced
tasks[task_id_counter] = task_data
task_id_counter += 1
return task_data
A response model declares exactly which fields should reach the client, regardless of what's stored internally:
class TaskResponse(BaseModel):
id: int
title: str
description: Optional[str] = None
completed: bool
@app.get("/tasks/{task_id}", response_model=TaskResponse)
def get_task(task_id: int):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
return tasks[task_id]
tasks[task_id] still contains owner_id internally, exactly as stored. response_model=TaskResponse filters it out before the response is serialized, since TaskResponse never declares that field — the internal dictionary and what the client actually receives are no longer required to match one-for-one.
Key Takeaways​
A working CRUD API comes together from a small set of repeating pieces: a Pydantic model defining valid input, a dictionary (or, eventually, a real database) holding state between requests, and one path operation per action, each raising HTTPException for failures that only run-time logic can detect rather than type validation. PUT and PATCH serve genuinely different purposes once both exist side by side — full replacement against a partial, targeted change — and a response model provides a clean way to store more internally than a client is ever shown, without needing to manually strip fields inside every route that returns data.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Error Handling
Next
Intermediate API Design
-
Setting Up the Project
-
Defining the Task Model
-
Creating an In-Memory Data Store
-
Creating a Task (POST /tasks)
-
Reading All Tasks (GET /tasks)
-
Reading a Single Task (
GET /tasks/{task_id}) -
Updating a Task (
PUT /tasks/{task_id}) -
Deleting a Task (
DELETE /tasks/{task_id}) -
Exploring the Interactive Docs
-
The Complete API So Far
-
Extending the API
- Filtering tasks by completion status
- Toggling completion with PATCH
- Hiding an internal field with a response model
-
Key Takeaways
