Flask or FastAPI? Choosing a Python Web Framework

Flask and FastAPI compared with the same small API in both, how they handle incoming data, where Django fits, and a simple way to choose for your project.

AAyim Nelson27 Nov 20264 min read3

You know Python and you want to build something for the web: a JSON API for a mobile app, a small website, or the backend for a React frontend. Two lightweight frameworks come up first: Flask and FastAPI. (And then someone mentions Django.) Which should you use?

This guide explains what each one is good at, shows the same small API in both, and ends with a simple way to decide.

Flask in one minute

Flask has been around since 2010. It calls itself a microframework: it gives you routing, requests and responses, and Jinja templates, and leaves everything else (databases, forms, logins) to extensions you choose. It's small, stable, and easy to understand line by line, which is why it's a favourite for learning and for small sites.

FastAPI in one minute

FastAPI arrived in 2018 and was built for APIs. It uses Python type hints and the Pydantic library to check incoming data for you, turns your code into interactive API documentation automatically, and supports async code out of the box. If you're building a JSON API, it saves you a lot of boilerplate.

The same endpoint in both

A tiny API that returns the fare for a trotro route.

Flask

from flask import Flask

app = Flask(__name__)

FARES = {"kasoa-circle": 8.50, "madina-37": 6.00}


@app.route("/fares/<route>")
def fare(route):
    if route not in FARES:
        return {"detail": "Unknown route"}, 404
    return {"route": route, "fare": FARES[route]}

Save it as app.py, run it with flask --app app run (after pip install flask) and open http://127.0.0.1:5000/fares/kasoa-circle.

FastAPI

from fastapi import FastAPI, HTTPException

app = FastAPI()

FARES = {"kasoa-circle": 8.50, "madina-37": 6.00}


@app.get("/fares/{route}")
def fare(route: str):
    if route not in FARES:
        raise HTTPException(status_code=404, detail="Unknown route")
    return {"route": route, "fare": FARES[route]}

Save it as main.py, run it with fastapi dev main.py (after pip install "fastapi[standard]"), then open http://127.0.0.1:8000/docs: FastAPI has already written interactive documentation for your endpoint.

Where they really differ: incoming data

The difference shows when clients send you data. In FastAPI you describe the data once, with a Pydantic model, and every request is checked against it:

from pydantic import BaseModel, Field


class FareReport(BaseModel):
    route: str
    fare: float = Field(gt=0)


@app.post("/reports", status_code=201)
def report(data: FareReport):
    return {"saved": data.route, "fare": data.fare}

Send "fare": -2 or leave out route, and FastAPI answers with a 422 response that says exactly which field is wrong, before your function even runs. In Flask you write those checks yourself or add a library for them.

Side by side

FlaskFastAPI
Best forSmall websites with templates, simple APIs, learningJSON APIs, especially for React or mobile frontends
Data validationYou add it (or an extension)Built in, from type hints and Pydantic
API docsYou add themAutomatic at /docs
AsyncPossible, but not its focusBuilt in
HTML pagesJinja templates are part of itPossible, but it's API-first
ServerWSGI (Gunicorn, Waitress)ASGI (Uvicorn)

And Django?

Django is the "batteries included" option: database models, migrations, an admin site, user accounts, forms and security features all come in the box. With Django REST Framework on top, it's also a strong choice for APIs. Choose Django when your project needs lots of those parts, such as a marketplace, a school portal or anything with user accounts and an admin team. Choose Flask or FastAPI when you want something small, or want to pick each piece yourself.

So which should you choose?

  • Building a JSON API for a React, Vue or mobile app? Start with FastAPI.
  • Building a small website with pages and forms, or learning how web frameworks work? Start with Flask.
  • Building a big site with accounts, an admin and lots of data? Start with Django.

Whichever you pick, the core ideas (routes, requests, responses, status codes, JSON, testing) carry over to the others.

Learn them on JeliScript

New to how APIs work? How the Web Works explains HTTP, status codes and JSON first.

Comments

Log in to join the conversation.

Loading comments...