Building Your Own API with Flask
Lesson 4 of 5 · View course roadmap
Learn the idea
Flask makes building an API absurdly simple. A route maps a URL + method to a Python function; return a dict and Flask serialises it to JSON:
from flask import Flask, request
app = Flask(__name__)
books = [{"id": 1, "title": "Fluent Python"}]
@app.get("/api/books")
def list_books():
return {"books": books}
@app.post("/api/books")
def add_book():
data = request.get_json()
book = {"id": len(books) + 1, "title": data["title"]}
books.append(book)
return book, 201
The three things to remember:
@app.get("/api/books")— the line above a function says "run this function for this URL"return book, 201— return a second value to set the status code (201 means "created")<int:book_id>in a URL — captures a number from the address and passes it to your function
This very site is built exactly this way.
Where you'll use this
Flask and FastAPI power countless production microservices; a route returning a dict is the atom of backend work. The site you're using right now is these exact patterns — read its app.py on GitHub.
Common mistakes
- Trusting client input: request.get_json() can be None or missing keys — validate before indexing, return 400 with a clear message.
- Returning 200 for errors — clients and monitoring rely on honest status codes.
- Global mutable state (a list of books) resets on restart and breaks with multiple workers — real apps persist to a database.
Pro tip
Design the route table on paper before coding — method + path + response shape for each endpoint. Ten minutes of design saves hours of refactoring; it's also exactly how teams spec real services.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +40 XP
Implement get_book(book_id) that searches the books list and returns the matching dict and 200, or {"error": "not found"} and 404. Print the results of looking up id 2 and id 99 (print status then title/error).
200 Automate the Boring Stuff 404 not found
Loop the books; if b["id"] == book_id return b, 200. After the loop return the error dict with 404.
books = [
{"id": 1, "title": "Fluent Python"},
{"id": 2, "title": "Automate the Boring Stuff"},
]
def get_book(book_id):
for b in books:
if b["id"] == book_id:
return b, 200
return {"error": "not found"}, 404
body, status = get_book(2)
print(status, body["title"])
body, status = get_book(99)
print(status, body["error"])
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.