Chapter 21: Web Development with Flask & FastAPI

Learn how to create web applications and RESTful APIs using Flask and FastAPI, from routing to templating and deployment.

Download chapter21.py

Objectives

1. Flask Basics

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello, Flask!"

@app.route("/greet/")
def greet(name):
    return f"Welcome, {name}!"

@app.route("/submit", methods=["GET","POST"])
def submit():
    if request.method == "POST":
        data = request.form.get("data")
        return render_template("result.html", data=data)
    return render_template("form.html")

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

Templates folder structure:

templates/
├── form.html
└── result.html

form.html example:

<form method="post">
  <input name="data" />
  <button>Send</button>
</form>

result.html example:

<p>You submitted: {{ data }}</p>

2. FastAPI Basics

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

@app.post("/items/")
def create_item(item: Item):
    return {"message": "Created", "item": item}

# run with: uvicorn src.chapter21:app --reload

3. Deployment

# gunicorn for Flask
gunicorn --bind 0.0.0.0:8000 wsgi:app

# uvicorn for FastAPI
uvicorn src.chapter21:app --host 0.0.0.0 --port 8000

Exercises

  1. Create a Flask “to-do” app with add/delete tasks stored in memory.
  2. Write a FastAPI endpoint that validates a JSON payload of user data.
  3. Use Jinja2 template inheritance to build a common layout for Flask pages.
  4. Containerize your Flask/FastAPI app with Docker and run locally.