Building APIs with Python
Lesson opener
In one line: A FastAPI endpoint is a Python function bound to a method and a path, with a model that rejects bad input before your function runs.
Why it matters: Northline's first stock API accepted any JSON object and wrote it to the ERP. A missing SKU became a blank item. The warehouse could not pick it, and the error appeared only on the pick list.
Before this lesson: Authentication and authorization. Python basics help. This lesson pins FastAPI 0.141.1.
What you will be able to do
- Map one business operation to one path and method.
- Reject an invalid body with 422 before any write.
- Return 404 when the item does not exist.
- Point a teammate at the generated documentation.
Prerequisites
Lessons 1 to 4. Install, when you are ready to run the server, with the pin from PyPI (https://pypi.org/project/fastapi/): fastapi==0.141.1. FastAPI's own guide is First steps (https://fastapi.tiangolo.com/tutorial/first-steps/) and Request body (https://fastapi.tiangolo.com/tutorial/body/). The checker below uses only the Python standard library so you can practice the rules without the server.
Endpoints, validation, errors, documentation
This course pins FastAPI 0.141.1 (released 2026-07-29). It generates an OpenAPI description and a documentation page at /docs when the app is running. That page is a view of the contract. It is not a second contract you edit by hand.
The rules, which you can run now:
def validate_item(body):
errors = []
sku = body.get("sku")
if not isinstance(sku, str) or not sku.strip():
errors.append("sku")
qty = body.get("on_hand")
if isinstance(qty, bool) or not isinstance(qty, int) or qty < 0:
errors.append("on_hand")
return errors
def response_for(body, known_skus):
errors = validate_item(body)
if errors:
return 422, {"errors": errors}
if body["sku"] not in known_skus:
return 404, {"errors": ["sku"]}
return 200, {"sku": body["sku"], "on_hand": body["on_hand"]}
assert response_for({"sku": "FX-100", "on_hand": 80}, {"FX-100"})[0] == 200
assert response_for({"sku": "", "on_hand": 80}, {"FX-100"})[0] == 422
assert response_for({"sku": "NO-SUCH", "on_hand": 1}, {"FX-100"})[0] == 404The server form of the same rules is below. It needs the pin installed and a process listening. Do not point it at production data.
# requires: server
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Northline item API", version="0.1")
class ItemIn(BaseModel):
sku: str = Field(min_length=1, max_length=32)
on_hand: int = Field(ge=0)
@app.get("/items/{sku}")
def read_item(sku: str):
if sku != "FX-100":
raise HTTPException(status_code=404, detail="sku")
return {"sku": sku, "on_hand": 80}Start it, when you choose to, with the command FastAPI documents for the version you installed. The documentation page lists GET /items/{sku}. A body that fails ItemIn is 422 from FastAPI's validation. Your function does not run.
Error handling in this lesson:
- 422 for a body that breaks the model.
- 404 for an unknown SKU.
- 403 is still the authorization answer from lesson 4. Do not bury it inside 500.
- Do not catch every exception and return 200.
Teacher walkthrough: one read endpoint
Illustrative store: only FX-100 exists, with 80 on hand.
GET /items/FX-100returns 200 and{"sku": "FX-100", "on_hand": 80}.GET /items/NO-SUCHreturns 404.- A write model with
on_hand: -1returns 422 and does not change 80. - Open
/docsand confirm the path, the method, and the fields match the model. - Validation: the number in the 200 body matches the warehouse screen for FX-100.
A second workplace case
A teammate adds POST /items in the same function that handles GET, using a query parameter to switch. Callers cannot tell a read from a create. Split them: GET reads, POST creates, and the create uses the idempotency rule from lesson 2.
Failure example: validation after the write
Symptom: A negative on_hand is stored, then a later job "cleans" it. The pick list already used the negative number.
Diagnosis: The check ran after the ERP write. The root cause is ordering. Validation is part of accepting the request, not a cleanup task.
Correction: Reject with 422 first. Write only after the model accepts the body and the caller is authorized.
Validation: Send on_hand: -1. The status is 422 and the stored quantity is unchanged.
Guided practice: add the receipt rule
Scenario: A receipt body must include receipt_id, sku, and integer qty greater than 0. Unknown SKUs are 404. Figures are illustrative.
Hints:
- Reuse the idea of
response_for. - Do not write on 422 or 404.
- A blank
receipt_idis a validation error.
Complete solution:
def receipt_status(body, known_skus):
errors = []
if not isinstance(body.get("receipt_id"), str) or not body["receipt_id"].strip():
errors.append("receipt_id")
if not isinstance(body.get("sku"), str) or not body["sku"].strip():
errors.append("sku")
qty = body.get("qty")
if isinstance(qty, bool) or not isinstance(qty, int) or qty <= 0:
errors.append("qty")
if errors:
return 422
if body["sku"] not in known_skus:
return 404
return 201
assert receipt_status({"receipt_id": "R-19", "sku": "FX-100", "qty": 10}, {"FX-100"}) == 201
assert receipt_status({"receipt_id": "", "sku": "FX-100", "qty": 10}, {"FX-100"}) == 422
assert receipt_status({"receipt_id": "R-19", "sku": "NO-SUCH", "qty": 10}, {"FX-100"}) == 404201 means the receipt was accepted as a new resource. The ERP write happens only on that path.
Independent practice
Specify one endpoint for a read you understand.
Acceptance criteria:
- You name the method, the path, and the success status.
- You list two validation rules and the 422 behaviour.
- You name the 404 case.
- You say the documentation page must show the same fields.
- You pin FastAPI as 0.141.1 if you include a server snippet, and you do not invent endpoints that FastAPI does not document.
- You do not return 200 for a failed validation.
Common mistakes
- Writing to the database and validating afterwards.
- One function that switches on a flag instead of separate methods.
- Returning 500 for a blank SKU.
- Editing a screenshot of
/docsinstead of the model that generates it.
Quick check
- Which FastAPI version does this lesson pin, and where is that pin published?
- What status does a negative
on_handreceive before any write? - What status does an unknown SKU receive when the body is otherwise valid?
- What is
/docsa view of? - Why must the function not run when the model rejects the body?
Answers:
- 0.141.1, the release published on PyPI on 2026-07-29. The guide is fastapi.tiangolo.com.
- 422.
- 404.
- The contract generated from the code, not a separate document you maintain by hand.
- Because a rejected body must not change the system of record.
Lesson summary
Bind one operation to a method and a path. Let the model reject bad input with 422. Use 404 when the identifier is well formed and unknown. Show the generated docs as the contract people read.
Bridge to the next lesson
The next lesson is the other direction: your program calls someone else's API, with timeouts, pagination, retries, and rate limits.