Building REST APIs
Design a JSON API: resources and URLs, methods and status codes, validating request bodies, consistent error responses, pagination, authentication with tokens, CORS, versioning and documentation, and when to choose FastAPI.
REST in practice
A REST API exposes resources (patients, appointments, predictions) at URLs and uses HTTP methods for actions:
| Request | Meaning | Success status |
|---|---|---|
GET /api/v1/patients | list patients (with pagination) | 200 |
GET /api/v1/patients/7 | one patient | 200 (404 if missing) |
POST /api/v1/patients | create a patient from the JSON body | 201, plus the new id |
PATCH /api/v1/patients/7 | change some fields | 200 |
DELETE /api/v1/patients/7 | remove it | 204 |
Use plural nouns, not verbs, in URLs (/patients, not /getPatients), put a version in the path (/api/v1) so you can change the API later without breaking existing apps, and paginate lists (?page=2&per_page=50) so nobody downloads a million rows by accident.
Try it: match the action to the method and status
For each situation, choose the right response status code.
Interactive: this part runs in your browser.
Validate every request body
Never trust incoming JSON. Check types, ranges and required fields, and reply with 400 or 422 and a helpful message when it is wrong. Pydantic does this neatly (the same library as in the Generative AI course); this part runs right here:
from pydantic import BaseModel, Field, ValidationError
class NewAppointment(BaseModel):
patient_id: int = Field(gt=0)
day: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$") # YYYY-MM-DD
minutes: int = Field(default=15, ge=15, le=60)
def handle_post(body: dict):
"""What a Flask view would do with request.get_json()."""
try:
appt = NewAppointment.model_validate(body)
except ValidationError as e:
problems = [{"field": ".".join(map(str, err["loc"])), "message": err["msg"]} for err in e.errors()]
return {"error": "invalid_request", "problems": problems}, 422
return {"created": appt.model_dump()}, 201
print(handle_post({"patient_id": 7, "day": "2026-11-20"}))
print(handle_post({"patient_id": -1, "day": "20/11/2026", "minutes": 5}))Errors, security and documentation
- Consistent errors: always return the same JSON shape, for example
{"error": "not_found", "message": "No patient 99"}. In Flask,@app.errorhandler(404)lets you return JSON instead of an HTML error page. Never send stack traces to clients; log them. - Authentication: APIs usually use a token in the
Authorizationheader (an API key, or a signed JWT after login). Reply 401 when it is missing or wrong, and 403 when the user is known but not allowed. - Rate limiting (for example with Flask-Limiter) protects you from abuse and runaway costs, replying 429.
- CORS: browsers block JavaScript on one website from calling an API on another domain unless the API allows it with CORS headers. Allow only the sites that need access (Flask-CORS helps).
- Documentation: describe each endpoint with an OpenAPI specification so others can use your API. FastAPI generates it automatically from type hints; in Flask, extensions such as flask-smorest or APIFlask do.
Quiz
1. Which URL design is most RESTful for one appointment?
2. A client sends JSON with a missing required field. Best response?
3. Why put /v1/ in API paths?
4. A request has no login token. Which status?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- MDN Web Docs: HTTP ↗ clear reference on requests, responses, methods and status codes
- FastAPI tutorial ↗ Official documentation