Python Reference ยท Third-party Libraries
Flask and FastAPI
Overview of Flask and FastAPI: defining routes, reading requests, returning JSON, path and query parameters, validation with Pydantic, and how to choose between them.
Flask and FastAPI are two popular ways to build web applications and APIs in Python. Both map URLs to plain functions. Flask is a small, flexible framework that has been around since 2010 and is very common for websites, tools and small services. FastAPI is newer and focuses on APIs: it reads your type hints to validate input, convert types and generate interactive documentation automatically.
Neither ships with Python. Install them with python -m pip install flask or python -m pip install "fastapi[standard]". The server snippets on this page are read-only, because a browser sandbox cannot run a web server. A runnable stand-in at the end shows the central idea, routing, using only the standard library.
A Flask app
from flask import Flask, jsonify, request app = Flask(__name__) @app.get("/") def home(): return "Hello, world" @app.get("/users/<int:user_id>") def get_user(user_id): return jsonify(id=user_id, name="Ada") @app.post("/users") def create_user(): data = request.get_json() return jsonify(created=data["name"]), 201 if __name__ == "__main__": app.run(debug=True) # development server only
Run it with python app.py, or flask --app app run. The <int:user_id> part converts the path segment to an int. Returning a tuple sets the status code, and a dict returned from a view is converted to JSON automatically.
A FastAPI app
from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() class NewUser(BaseModel): name: str age: int = 0 @app.get("/users/{user_id}") def get_user(user_id: int, verbose: bool = False): if user_id > 100: raise HTTPException(status_code=404, detail="No such user") return {"id": user_id, "verbose": verbose} @app.post("/users", status_code=201) def create_user(user: NewUser): return {"created": user.name, "age": user.age}
Run it with fastapi dev app.py (or uvicorn app:app --reload). Open /docs in the browser for generated, clickable documentation. A request with a non-integer user_id is rejected with a 422 response before your function runs; verbose comes from the query string (/users/7?verbose=true).
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Comparison
| Flask | FastAPI | |
|---|---|---|
| Style | Minimal core, extensions for the rest | API-first, batteries for validation and docs |
| Input validation | Manual, or add a library | Automatic from type hints (Pydantic) |
| Async | Supported, but the ecosystem is mostly synchronous | Built around async def (plain def also works) |
| Templates | Jinja2 included | Optional, via Jinja2 |
| Interface standard | WSGI | ASGI |
| Auto docs | No | Yes (/docs and /redoc) |
| Typical use | Websites, dashboards, small services | JSON APIs, microservices |
Usage notes
- Never run the built-in servers in production. Flask's
app.run()andfastapi devare for development. Use Gunicorn or Waitress (WSGI) or Uvicorn behind a reverse proxy. - Keep secrets out of code. Read settings such as
SECRET_KEYand database URLs from environment variables. - Do not trust input. Flask gives you raw values from
request; validate them. FastAPI validates types, but you still need authorization checks. debug=Trueis dangerous on a public server because it can expose an interactive console.- Flask's
request,gandsessionare context-local and work only while a request is being handled. - In FastAPI, a plain
defendpoint runs in a thread pool, whileasync defruns on the event loop and must not block it with slow synchronous calls. - Testing: both provide test clients, and they pair naturally with pytest.
Related
- requests, pytest, SQLAlchemy
json,asyncio,http.serverandurllib- Lessons: Web development, Type hints