🐍 Python for Everyone

← Back to all chapters

Chapter 22 of 28 Intermediate 80 min read

Building Web Apps & APIs — Flask & FastAPI

Every chapter so far has run start to finish inside one Python process, printing to a terminal or writing a file. A web framework flips that around: a program keeps running, waits for requests to arrive over the network, and sends a response back for each one — the same basic loop behind every website and mobile-app backend in existence. This chapter covers Flask, the classic way to serve server-rendered HTML pages from Python, and FastAPI, a newer, typed framework built specifically for JSON APIs — the two dominant, genuinely different answers to "how does Python talk to the web."

How to read this chapter

Picture Chapter 19's requests.get(...) calls, hitting some public weather API out there on the internet. Something on the other end of that call had to be running: a program listening for incoming requests, reading what was asked for, and sending back a JSON response. That "something" is a web framework doing its job. This chapter builds that other end — first as an HTML page a browser renders directly (Flask), then as a JSON API exactly like the ones Chapter 19 consumed (FastAPI).
Sub-topic 1 of 7

1. What a web framework is, and the request/response cycle

At a glance
  • A web framework is a library that keeps a Python program running, listens for incoming HTTP requests, and lets you write code that decides what response to send back.
  • Every request has a method (GET to fetch something, POST to send new data) and a path (like /tasks or /tasks/3); every response has a status code and a body.
  • Flask and FastAPI both exist because "serve a request, send a response" has two very different natural shapes: a full HTML page for a browser to render, or a JSON payload for another program to parse.
Why this matters: Flask and FastAPI look like two unrelated libraries to learn from scratch, until you see they're both just different answers to this one shared question — seeing the request/response cycle first makes everything after it click into place as "the same idea, two flavors" instead of two disconnected skills.
What is... a web framework? A web framework is a library that handles the low-level networking of receiving HTTP requests and sending back HTTP responses, so your code only has to say "when a request for this path arrives, run this function and return this." Flask and FastAPI are both Python web frameworks — they differ in what shape of response they're built around, not in what job they do.

Every request/response exchange follows the same basic shape, whether it's a browser loading a page or Chapter 19's requests library calling a weather API:

the request/response cycle
CLIENT (browser, phone app, or requests.get())
   |
   |  HTTP request: method (GET/POST/...) + path (/tasks) + optional body
   v
YOUR PYTHON PROGRAM (Flask or FastAPI, listening on a port)
   |
   |  your code runs, decides what to send back
   v
   HTTP response: status code (200, 404, ...) + a body (HTML or JSON)
   |
   v
CLIENT receives the response
What is... a status code? A status code is a three-digit number every HTTP response carries, summarizing what happened: 200 means "OK, here's your data," 404 means "nothing exists at that path," 500 means "the server itself hit an error." Chapter 19's response.status_code was reading exactly this value from the other side of a request — this chapter is about being the program that sets it.

Flask was built first, in an era when a Python program's job was almost always to render a full HTML page — the response a browser could display directly. FastAPI came later, built for a different reality: many modern applications separate a JSON-serving "backend" from whatever renders the actual screen (a mobile app, or a separate frontend written in something like React). Neither approach is obsolete; they solve genuinely different problems, which is why this chapter teaches both side by side rather than picking one.

Go Deeper: what does "listening on a port" actually mean?

A running web server binds to a numbered "port" on the machine (commonly 5000 for Flask's development server, 8000 for a typical FastAPI/uvicorn setup) and waits there for incoming network connections addressed to that port. Visiting http://localhost:5000 in a browser is literally addressing a request to port 5000 on your own machine (localhost) — the same mechanism a real deployment uses, just pointed at a public address instead of your own computer.

Quick recap
  • A web framework listens for HTTP requests and lets your code decide what response to send back.
  • Requests have a method and path; responses have a status code and a body.
  • Flask serves HTML pages; FastAPI serves JSON APIs — both are legitimate answers to the same request/response cycle.
Sub-topic 2 of 7

2. Flask: @app.route() and render_template()

At a glance
  • @app.route("/path") connects a URL path to a Python function — that function's return value becomes the response.
  • render_template("file.html", **context) fills in an HTML template file with Python values, the same way Chapter 6's f-strings filled values into a string.
  • A route function can just return a plain string too — render_template() is for when the response is a whole HTML page.
Why this matters: @app.route() is the single most-used piece of Flask — nearly every Flask app is, underneath everything else, a collection of route functions mapped to paths, exactly like the one shown here.

Here's a complete, real, runnable Flask app — shown for reference, following the real API exactly, but never executed in this course (there's no live server here to run it against):

app.py (run this locally: pip install flask, then python3 app.py)
from flask import Flask, render_template

app = Flask(__name__)

TASKS = [
    {"id": 1, "title": "Write the report", "done": False},
    {"id": 2, "title": "Review pull request", "done": True},
]


@app.route("/")
def home():
    return render_template("tasks.html", tasks=TASKS)


@app.route("/about")
def about():
    return "A simple task manager, built with Flask."


if __name__ == "__main__":
    app.run(debug=True)  # visit http://localhost:5000
What is... a route? A route is the pairing of a URL path (like "/" or "/about") with the Python function that should run whenever a request for that path arrives. @app.route("/path") is a decorator (Chapter 10) that registers this pairing with Flask — the function underneath it is called the view function, and its return value becomes the response's body.

render_template() looks for an HTML file inside a templates/ folder next to app.py, and fills in placeholders using Jinja2 template syntax ({{ variable }}, {% for x in y %}) — conceptually the same job Chapter 6's f-strings did, just applied to a whole HTML file loaded from disk (Chapter 13's open() territory) instead of one Python string built in memory:

templates/tasks.html (reference only -- not run here)
<!doctype html>
<title>Tasks</title>
<ul>
{% for task in tasks %}
  <li>{{ task.title }} -- {{ "Done" if task.done else "Pending" }}</li>
{% endfor %}
</ul>

Since no live server or template folder exists in this course, this chapter's runnable examples pull the "decide what the page should contain" logic out into a plain function — the exact same logic a real route function would run, just callable and testable directly without render_template()'s file-loading step:

route_logic.py
# This is the same decision-making a Flask view function does, pulled out
# as a plain function so it runs here without a template file or a live
# server -- render_template("tasks.html", tasks=tasks) would use this
# exact list of dicts as its context in a real app.

def build_task_summary(tasks):
    lines = []
    for task in tasks:
        status = "Done" if task["done"] else "Pending"
        lines.append(f"{task['title']} -- {status}")
    return lines


tasks = [
    {"id": 1, "title": "Write the report", "done": False},
    {"id": 2, "title": "Review pull request", "done": True},
]
for line in build_task_summary(tasks):
    print(line)
actual output of route_logic.py
Write the report -- Pending
Review pull request -- Done
try_it.py
Click "Run Code" — try adding another task dict to the list.
Go Deeper: can a route function return something other than a full HTML page?

Yes — a Flask view function can return a plain string (Flask wraps it in a minimal HTML response automatically), a dict (Flask automatically converts it to a JSON response, which is how Flask can also serve small JSON endpoints when a full HTML page isn't needed), or a tuple like (body, status_code) to set a specific status code. render_template() is simply the most common choice when the response genuinely is a full page a browser should render.

Quick recap
  • @app.route("/path") connects a URL path to a view function; its return value is the response.
  • render_template() fills an HTML template file with Python values using Jinja2 syntax.
  • A route function can also just return a plain string, dict, or tuple with a status code.
Sub-topic 3 of 7

3. The Flask request object

At a glance
  • request.args holds query-string parameters (?key=value in the URL) as a dict-like object.
  • request.form holds data submitted from an HTML <form> (a POST request's body, form-encoded).
  • request.json holds a POST request's body when it's JSON — the shape an API client (like Chapter 19's requests) would send.
Why this matters: a route function needs to read what the client actually sent before it can decide what to send back — request is Flask's single object for reading every part of an incoming request, regardless of where the data came from.
What is... the request object? Flask's request is a global object, imported with from flask import request, that always refers to whatever request is currently being handled — reading request.args, request.form, or request.json inside a view function gets you the data the client actually sent for that specific request, without your code ever having to parse raw HTTP text itself.
app_with_request.py (reference only -- not run)
from flask import Flask, request

app = Flask(__name__)


@app.route("/search")
def search():
    # A request to /search?q=python reads "python" from request.args
    query = request.args.get("q", "")
    return f"Searching for: {query}"


@app.route("/tasks", methods=["POST"])
def create_task():
    # A JSON POST body like {"title": "Water the plants"}
    data = request.json
    title = data.get("title", "")
    return {"created": title}, 201


if __name__ == "__main__":
    app.run(debug=True)

Since there's no live server here to actually send a request against, this chapter's runnable version pulls the same .get(key, default) reading pattern out into plain functions operating on ordinary Python dicts — standing in for what request.args and request.json would already look like by the time a view function reads them:

request_reading_demo.py
# simulated_args/simulated_json_body stand in for what request.args /
# request.json would already contain by the time a view function reads
# them -- both behave like plain dicts with a .get(key, default) method.

def handle_search(simulated_args):
    query = simulated_args.get("q", "")
    return f"Searching for: {query}" if query else "No search term provided."


def handle_create_task(simulated_json_body):
    title = simulated_json_body.get("title", "")
    if not title:
        return {"error": "title is required"}, 400
    return {"created": title}, 201


print(handle_search({"q": "python"}))
print(handle_search({}))
print(handle_create_task({"title": "Water the plants"}))
print(handle_create_task({}))
actual output of request_reading_demo.py
Searching for: python
No search term provided.
({'created': 'Water the plants'}, 201)
({'error': 'title is required'}, 400)
What is... a query string? A query string is the part of a URL after ?, made of key=value pairs joined by & — /search?q=python&limit=10 has a query string of q=python&limit=10, readable in Flask as request.args.get("q") and request.args.get("limit").
Go Deeper: why does /tasks need methods=["POST"] in the decorator?

By default, @app.route() only responds to GET requests — the method used for simply fetching a page or resource. Creating something new is conventionally done with a POST request instead (the same distinction Chapter 19 covered from the client side), so a route meant to handle creation needs to explicitly opt in with methods=["POST"], or Flask will reject a POST request to that path with a 405 Method Not Allowed response.

Quick recap
  • request.args reads query-string parameters; request.form reads form data; request.json reads a JSON body.
  • Each supports .get(key, default), the same safe-lookup pattern as a plain dict.
  • A route needs methods=["POST"] to accept anything other than GET requests.
Sub-topic 4 of 7

4. FastAPI: path params, query params, and @app.get/@app.post

At a glance
  • @app.get("/path") and @app.post("/path") are FastAPI's equivalent of Flask's @app.route(), one decorator per HTTP method.
  • A path parameter like {item_id} in @app.get("/items/{item_id}") becomes a function argument, automatically converted to the type hint given.
  • A query parameter is just a regular function argument with a default value — FastAPI infers it belongs in the query string rather than the path.
Why this matters: FastAPI's path/query param handling is where type hints stop being optional documentation and start doing real work — this sub-topic is the concrete mechanism; Sub-topic 6 explains why that design choice matters so much.

Here's a complete, real, runnable FastAPI app — shown for reference, following the real API exactly, never executed here:

main.py (run this locally: pip install fastapi uvicorn, then uvicorn main:app --reload)
from fastapi import FastAPI

app = FastAPI()

TASKS = {
    1: {"title": "Write the report", "done": False},
    2: {"title": "Review pull request", "done": True},
}


@app.get("/tasks/{task_id}")
def get_task(task_id: int):
    # task_id arrives as a STRING in the URL; the : int type hint tells
    # FastAPI to convert it to an int automatically before this function
    # even runs, and to reject the request with a clear error if it can't.
    return TASKS.get(task_id, {"error": "not found"})


@app.get("/tasks")
def list_tasks(done: bool | None = None):
    # done is a QUERY parameter (/tasks?done=true) because it has a
    # default value, rather than appearing inside the path itself.
    if done is None:
        return TASKS
    return {tid: t for tid, t in TASKS.items() if t["done"] == done}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)  # visit http://localhost:8000/docs
What is... a path parameter? A path parameter is a placeholder inside a route's URL path itself, written in curly braces ({task_id}), that becomes a required function argument. It identifies which specific resource a request is about — /tasks/1 and /tasks/2 are two different URLs hitting the same route, with task_id bound to 1 or 2 respectively.
What is... a query parameter? A query parameter is extra, often optional information passed after ? in the URL (/tasks?done=true). In FastAPI, any function argument that isn't part of the path and has a default value is automatically treated as a query parameter — no special decorator syntax needed, unlike the path parameter's curly-brace placeholder.

Since a live server isn't available here, this chapter's runnable version pulls the exact same type-conversion and lookup logic these route functions run into plain functions — the type hints stay real Python type hints throughout, even without FastAPI installed to act on them automatically:

path_and_query_demo.py
# The same logic get_task()/list_tasks() run, as plain functions. A real
# FastAPI route converts the URL's task_id string to int automatically
# because of the `task_id: int` type hint -- here that conversion is
# simulated explicitly with int(), the way FastAPI would do it internally.

TASKS = {
    1: {"title": "Write the report", "done": False},
    2: {"title": "Review pull request", "done": True},
}


def get_task(task_id: int):
    return TASKS.get(task_id, {"error": "not found"})


def list_tasks(done=None):
    if done is None:
        return TASKS
    return {tid: t for tid, t in TASKS.items() if t["done"] == done}


# Simulating a request to /tasks/2 -- FastAPI would have already
# converted the URL string "2" to the int 2 before calling get_task.
print(get_task(int("2")))
print(get_task(99))

# Simulating /tasks (no query string) and /tasks?done=true
print(list_tasks())
print(list_tasks(done=True))
actual output of path_and_query_demo.py
{'title': 'Review pull request', 'done': True}
{'error': 'not found'}
{1: {'title': 'Write the report', 'done': False}, 2: {'title': 'Review pull request', 'done': True}}
{2: {'title': 'Review pull request', 'done': True}}
Go Deeper: what happens if a URL's path parameter can't convert to the type hint?

If a request hits /tasks/abc against def get_task(task_id: int), FastAPI tries to convert the string "abc" to an int, fails, and automatically responds with a 422 Unprocessable Entity error describing exactly what went wrong — without a single line of validation code written by hand. This automatic rejection is a direct product of the type hint being real, checked information rather than just a comment for humans to read.

Quick recap
  • @app.get("/path")/@app.post("/path") register route functions per HTTP method.
  • A path parameter ({name} in the URL) becomes a required, type-hint-converted function argument.
  • A query parameter is a function argument with a default value, read from the URL's query string automatically.
Sub-topic 5 of 7

5. Pydantic models and automatic /docs

At a glance
  • A Pydantic BaseModel describes the exact shape of expected request/response data as a class, using type hints for every field.
  • Passing a Pydantic model as a route function's argument makes FastAPI validate the incoming JSON body against it automatically, before the function body even runs.
  • FastAPI generates an interactive Swagger UI page at /docs automatically, built directly from your route signatures and Pydantic models — no separate documentation to write or maintain.
Why this matters: this is the sub-topic that makes FastAPI's whole "typed" pitch concrete — a Pydantic model isn't just a nicer way to write a dict shape, it's what both the automatic validation and the automatic /docs page are generated from.
What is... Pydantic? Pydantic is the data-validation library FastAPI is built on top of. A Pydantic model is a class inheriting from BaseModel, with each field written as a class attribute with a type hint — similar in spirit to Chapter 14/15's classes, except Pydantic uses the type hints to actually validate incoming data against them, not just document intent.
main_with_pydantic.py (reference only -- not run)
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Task(BaseModel):
    title: str
    done: bool = False   # a default value makes this field optional


TASKS: dict[int, Task] = {}
next_id = 1


@app.post("/tasks")
def create_task(task: Task):
    # FastAPI has ALREADY validated the incoming JSON body against Task
    # by the time this function runs -- a body missing "title", or with
    # "done" set to a non-boolean value, never reaches this line at all;
    # FastAPI responds with a 422 error automatically instead.
    global next_id
    TASKS[next_id] = task
    created_id = next_id
    next_id += 1
    return {"id": created_id, **task.model_dump()}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)  # /docs shows this live

Since Pydantic validation needs the actual library installed and a real request body to run against, this chapter's runnable version demonstrates the same validation idea with a small, plain function — standing in for what a Pydantic model's automatic checking would do before a route function ever runs:

validation_demo.py
# validate_task_shape simulates what a Pydantic BaseModel checks
# automatically: "title" must be present and a str; "done" is optional
# and defaults to False, but must be a bool if given at all. A real
# Pydantic model does exactly this, generated from type hints, before
# create_task() in main_with_pydantic.py ever runs.

def validate_task_shape(body):
    if "title" not in body or not isinstance(body["title"], str):
        return False, "title is required and must be a string"
    if "done" in body and not isinstance(body["done"], bool):
        return False, "done must be a boolean"
    return True, None


print(validate_task_shape({"title": "Water the plants"}))
print(validate_task_shape({"title": "Water the plants", "done": True}))
print(validate_task_shape({"done": True}))
print(validate_task_shape({"title": "Water the plants", "done": "yes"}))
actual output of validation_demo.py
(True, None)
(True, None)
(False, 'title is required and must be a string')
(False, 'done must be a boolean')
What is... /docs? FastAPI automatically serves an interactive documentation page at /docs (a Swagger UI page) for every running app, listing every route, its parameters, and the shape of any Pydantic model involved — generated directly from your code's type hints and models, with a "Try it out" button that sends real requests from right inside the browser. Nothing is written by hand to produce it; it exists purely because the route signatures and models already contain enough real, typed information to build it automatically.
Go Deeper: can a Pydantic model also shape the RESPONSE, not just the request?

Yes — a route can declare @app.get("/tasks/{id}", response_model=Task), and FastAPI will filter and validate whatever the function returns down to exactly that model's fields before sending the response. This is useful for making sure a route never accidentally leaks an internal field (like a password hash on a User model) that happens to exist on the underlying Python object but was never meant to reach a client.

Quick recap
  • A Pydantic BaseModel uses type-hinted class fields to describe and validate expected data shape.
  • A route argument typed as a Pydantic model gets its request body validated automatically before the function runs.
  • /docs is FastAPI's automatic, interactive Swagger UI page, generated from route signatures and models.
Sub-topic 6 of 7

6. Flask vs. FastAPI, side by side

At a glance
  • Flask: untyped by default, server-rendered HTML, a simpler mental model, huge ecosystem, synchronous by default.
  • FastAPI: type hints are load-bearing (validation + docs generation), JSON-first, automatic /docs, async-friendly out of the box.
  • Neither is "better" — they're built around different default outputs (an HTML page vs. a JSON payload).
Why this matters: this is the conceptual payoff of covering both frameworks in one chapter — every difference in Sub-topics 2-5 traces back to one root design choice each framework made about what a typical response looks like.
Flask vs. FastAPI, side by side
                    FLASK                       FASTAPI
                    ----------------------      ----------------------
Typical response    Full HTML page              JSON payload
Type hints          Optional, not enforced      Load-bearing: drive validation + docs
Route decorator     @app.route("/x")             @app.get("/x") / @app.post("/x")
Data validation     Manual (if statements)       Automatic, via Pydantic models
API docs            Not built in                 Automatic, at /docs
Best fit            Server-rendered websites     JSON APIs for another app/frontend to consume
Concurrency style   Synchronous by default       async-friendly by default
What is... "untyped by default," for Flask? Flask's request.args.get("q") always returns a plain string (or None) — converting it to an int or validating its shape is something your code has to do explicitly, with ordinary if statements and try/except (Chapter 12). FastAPI's type hints do this same job automatically, which is the single biggest practical difference between the two frameworks' day-to-day feel.

Why does this contrast matter specifically? Because it's not a cosmetic style choice — it changes where validation logic lives:

Go Deeper: could Flask serve JSON, or FastAPI serve HTML?

Yes, technically — Flask can return a dict (auto-converted to JSON) from any route, and FastAPI can return an HTMLResponse with a raw HTML string. Neither framework is restricted to one output format. But each framework's defaults, ecosystem, and idiomatic patterns are built around one primary use case (Flask around HTML pages with render_template(), FastAPI around typed JSON with Pydantic), which is why real projects pick the framework matching what they're mostly building, rather than fighting either framework's natural grain.

Quick recap
  • Flask defaults to server-rendered HTML and untyped request data; FastAPI defaults to typed JSON with automatic validation and docs.
  • Type hints are optional documentation in Flask, but load-bearing validation logic in FastAPI.
  • Both frameworks can technically do the other's job, but each has a natural, idiomatic use case it's built around.
Sub-topic 7 of 7

7. What's next: server-rendered HTML, a JSON API, and where React fits

At a glance
  • A Flask app rendering full HTML pages is a complete, working website all by itself — nothing else is required.
  • A FastAPI JSON API is deliberately not a complete website by itself — it's meant to be consumed by something else that renders an actual screen.
  • A frontend framework like React is exactly that "something else" — it's JavaScript, runs in the browser, and would call a JSON API like the ones this chapter built, the same way Chapter 19's requests library called a public API from Python.
Why this matters: this is a conceptual "what's next" callout, not a new skill to build — it exists so you know exactly what a JSON API is FOR and what would typically sit on the other end of it, without this Python course teaching JavaScript or React itself.
What is... React (conceptually only — not taught here)? React is a popular JavaScript library for building what a user actually sees and clicks in a browser (a "frontend"). It's mentioned here only so the picture is complete: a React application would run in the user's browser and make HTTP requests — the exact same kind of request Chapter 19's requests.get() made from Python — to a JSON API like the FastAPI app this chapter built, then use the JSON response to decide what to display. No React or JavaScript syntax is taught in this course; it's out of scope for a Python-focused curriculum.
three shapes of "what serves the user," side by side
1. SERVER-RENDERED HTML (this chapter's Flask approach)
   Browser  <----HTML page, ready to display---->  Flask app
   One request gets a complete, displayable page. Simplest mental model.

2. JSON API, no separate frontend built in this course
   Program  <----JSON data only, no visuals---->  FastAPI app
   Something else has to turn this JSON into an actual screen.

3. JSON API + a separate frontend (the real-world "next step")
   React (in the browser)  <--JSON-->  FastAPI app  <--DB-->  Database
   React renders the screen; FastAPI only ever serves data, never HTML.

This is exactly why the same task-manager idea gets built twice in this chapter's project, once each way: a Flask version that's a complete, working mini-website entirely on its own, and a FastAPI version that's deliberately "just" a JSON API — complete and correct on its own terms, but built with the explicit expectation that something else (a real frontend, a mobile app, another script) would be the thing a person actually looks at.

Go Deeper: if a JSON API "isn't a website," why build one at all?

Because a single JSON API can serve multiple different "somethings else" at once — a React web frontend, a native mobile app, another company's integration, and an internal script can all call the exact same FastAPI endpoints, each getting the same JSON back and rendering it however makes sense for that platform. A Flask app rendering HTML directly, by contrast, is tied to being displayed as a webpage specifically — which is exactly the tradeoff Sub-topic 6's comparison was pointing at.

Quick recap
  • Flask's server-rendered HTML is a complete website on its own.
  • FastAPI's JSON API is deliberately meant to be consumed by something else that renders the actual screen.
  • React (not taught here) is a common example of that "something else" — a browser-side consumer of the same kind of JSON API this chapter built.
In the Real World

Points to Remember

← All Chapters Take the Quiz →