Capstone: Build and Test Your First Web API
A friend is building a to-do app and needs the part behind it: somewhere to save tasks and fetch them. This capstone joins every piece of the course: you design, write, run and test your first web API in Python, then share it through Git.
Design the API: the menu first
Start with the menu. A REST API, as REST APIs and JSON explained, gives each resource, a thing the API manages, its own URL. Yours has one resource, the task, and three endpoints, each a method and URL it answers:
| Request | What it does | Success | Failure |
|---|---|---|---|
GET /tasks | lists every task | 200 | none |
POST /tasks | creates a task | 201 | 400 for bad input |
GET /tasks/1 | fetches task 1 | 200 | 404 if missing |
A task looks like {"id": 1, "title": "Buy milk", "done": false}. The client sends only the title, and the server picks the id. In the README, the table and this shape form the contract from What Is an API?, so the app's developer can start before your code exists. Then build in small steps:
Write the handlers
A web framework is a library that does the HTTP plumbing, reading requests, matching URLs and writing responses, so you write only the rules. Flask is a small Python one. A handler, or view function, answers one endpoint, and the route, the line starting with @ above it, links it to a method and URL.
Create a GitHub repository named tasks-api with only a README, clone it as in Git Basics, and work inside it. With Python 3.10 or later, which pytest 9.2 needs, create a virtual environment, a private folder of packages, and install pinned versions (Werkzeug is Flask's HTTP toolkit):
python3 -m venv .venv
source .venv/bin/activate
pip install flask==3.1.3 werkzeug==3.1.9 pytest==9.2.0
pip should end with Successfully installed; if it finds no matching pytest, your Python is too old. This works on macOS, Linux and WSL 2. Save this as app.py:
from itertools import count
from flask import Flask, request
app = Flask(__name__)
tasks = []
next_id = count(1)
def validate_title(data):
title = data.get("title") if isinstance(data, dict) else None
if not isinstance(title, str) or not title.strip():
return "title must be a non-empty string"
return None
@app.get("/tasks")
def list_tasks():
return tasks
@app.post("/tasks")
def create_task():
data = request.get_json(silent=True)
error = validate_title(data)
if error:
return {"error": error}, 400
task = {"id": next(next_id), "title": data["title"].strip(), "done": False}
tasks.append(task)
return task, 201
@app.get("/tasks/<int:task_id>")
def get_task(task_id):
for task in tasks:
if task["id"] == task_id:
return task
return {"error": "task not found"}, 404
Each handler parses, validates, acts and responds. get_json(silent=True) returns None, rather than failing, when the body is not JSON or the Content-Type header does not say so, and validate_title then answers with one clear 400. A returned dict or list becomes JSON; a second value sets the status code, which is otherwise 200.
In the flowchart, notice that the check comes before the save.
Run it and call it
Start Flask's development server, a simple server built into Flask for trying code on your own machine. --app app loads app.py, and --port picks the port it listens on instead of the default 5000:
flask --app app run --port 8000
It should print these lines first, then wait for requests:
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:8000
The warning is fair: this server suits one developer, and production uses a WSGI server, built on Python's standard interface between web apps and servers. If you see Port 8000 is in use by another program, stop that program. Leave the server running, and in a second terminal call it with curl, where -i shows the status line, -H adds a header and -d sends a body as a POST:
curl -i localhost:8000/tasks -H "Content-Type: application/json" -d '{"title": "Buy milk"}'
curl -i localhost:8000/tasks -H "Content-Type: application/json" -d '{"title": ""}'
curl -i localhost:8000/tasks/99
Trimmed to each status line and body, you should see:
HTTP/1.1 201 CREATED
{"done":false,"id":1,"title":"Buy milk"}
HTTP/1.1 400 BAD REQUEST
{"error":"title must be a non-empty string"}
HTTP/1.1 404 NOT FOUND
{"error":"task not found"}
Werkzeug capitalises the words after the code, but programs act on the number, and Flask sorts the keys. If curl says Failed to connect, the server is not running. Without the -H header, the first call also gets a 400: nothing told the server the body is JSON.
Store the data: list now, database later
The tasks list lives in the server's memory (RAM): quick, but emptied whenever the server stops, and each copy of the server would keep its own. A database, as What Is a Database? explained, keeps data durably and shares it.
Python's built-in sqlite3 module is an easy start: POST becomes an INSERT, and GET /tasks/1 a SELECT with WHERE id = ?, as in SQL Basics. Pass the title as a parameter, the ?, never pasted into the SQL, or a crafted title could rewrite the query: SQL injection. The URLs and JSON stay the same, so the contract holds.
Add tests: taste before you open
Now automate those checks in tests/test_app.py: two unit tests of validate_title alone, and one integration test (see Unit vs Integration vs End-to-End Tests) through the endpoints:
from app import app, validate_title
def test_blank_title():
assert validate_title({"title": " "}) is not None
def test_good_title():
assert validate_title({"title": "Buy milk"}) is None
def test_create_and_fetch():
client = app.test_client()
created = client.post("/tasks", json={"title": "Buy milk"})
assert created.status_code == 201
task_id = created.json["id"]
assert client.get(f"/tasks/{task_id}").json["title"] == "Buy milk"
assert client.get("/tasks/999").status_code == 404
The test client sends requests through Flask's routing and your handlers without starting a server, and json= sets the Content-Type header for you. In the second terminal, run source .venv/bin/activate, then, in the project folder:
python -m pytest -q
You should see one dot for each passing test, then a summary; your time will differ:
... [100%]
3 passed in 0.05s
Plain pytest would fail with ModuleNotFoundError: No module named 'app': it adds only the tests folder to Python's import path, the folders searched for code, while python -m adds the current folder. The diagram shows the finished project.
Ship it, and what next
Add a .gitignore listing .venv/, __pycache__/ and .pytest_cache/, so packages and caches stay out of history. Then commit on a branch and push it, as in Branches and Pull Requests:
git switch -c add-tasks-api
git add .gitignore README.md app.py tests
git commit -m "Add tasks API: list, create and get tasks"
git push -u origin add-tasks-api
GitHub's reply to the push includes a link for opening the pull request. In it, say what you tested, and ask for a code review. Next, add PATCH and DELETE, move storage to SQLite, and run the tests on every push with GitHub Actions.
Check yourself
A client sends POST /tasks with {"title": 42}. What should your API return, and why not 201 or 500?
400: the title is not a string, so the caller broke the rules. A 201 would save junk; a 500 would blame the server.
You restart the server and every task is gone, though no code changed. Why, and what fixes it?
The list lived in the server's memory, which ends with the process; a database keeps tasks durably.
The route is mistyped as @app.post("/task"), yet both unit tests pass. Which test catches it, and why?
The integration test: it posts to /tasks, which now has no POST handler, so its 201 check fails. Unit tests never touch a URL.