Building a Simple API
You can build APIs with plain Flask routes.
flowchart LR
subgraph "/api/books"
A["GET -> 200, a list"]
B["POST -> 201 + Location, the created item"]
end
subgraph "/api/books/<id>"
C["GET -> 200, or 404"]
D["PUT/PATCH -> 200, the updated item"]
E["DELETE -> 204, no body"]
end
F["a method the rule does not list"] --> G["405 Method Not Allowed"]
H["a body that fails validation"] --> I["400 with the errors, not 500"]
Example: in-memory todo API (learning)
Section titled “Example: in-memory todo API (learning)”from flask import Flask, request
app = Flask(__name__)
todos = [
{"id": 1, "title": "Learn Flask", "done": False},
]
@app.get("/api/todos")
def list_todos():
return {"items": todos}
@app.post("/api/todos")
def create_todo():
payload = request.get_json(silent=True) or {}
title = (payload.get("title") or "").strip()
if not title:
return {"error": "validation_error", "message": "title is required"}, 400
new_id = max([t["id"] for t in todos], default=0) + 1
todo = {"id": new_id, "title": title, "done": False}
todos.append(todo)
return todo, 201.get_json(silent=True)avoids raising exceptions on bad JSON- Always validate input
- Use status codes consistently
Moving from in-memory to database
Section titled “Moving from in-memory to database”In real apps:
- replace the list with SQLAlchemy models
- implement
to_dict()methods - add pagination and authentication
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading