Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Building Your Own API with Flask

18 min 40 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 4 of 5 · View course roadmap
Step 1

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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +40 XP

Blank · autosaved

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).

Target output
200 Automate the Boring Stuff
404 not found
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What status code should a successful POST that creates a resource return?
2. In Flask, returning a dict from a route…
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path