Learn / Frameworks / Flask / Introduction and Routes

Beginner 12 min

Introduction and Routes

Create a Flask app, define routes and return JSON.

What you will learn

  • Run a Flask app
  • Define routes with variables
  • Return JSON

Flask is a small, flexible Python web framework. It gives you routing and request handling and leaves the rest (database, forms, authentication) to libraries you choose. That makes it an excellent way to understand how web apps work, and it is easy to start with and easy to grow.

python3 -m venv .venv && source .venv/bin/activate
pip install flask
# app.py
from flask import Flask, jsonify, request

app = Flask(__name__)

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

@app.route("/health")
def health():
    return jsonify(status="ok")

if __name__ == "__main__":
    app.run(debug=True)
flask --app app run --debug        # or: python app.py

Visit http://127.0.0.1:5000/. Debug mode reloads on save and shows an interactive error page; never enable it in production.

@app.route("/users/<int:user_id>")
def get_user(user_id):
    return jsonify(id=user_id)

@app.route("/hello/<name>")
def hello(name):
    return f"Hello, {name}!"

Converters such as int, float, string and uuid validate and convert the URL part. A non-matching URL gives a 404 automatically.

@app.route("/search")
def search():
    q = request.args.get("q", "")           # query string ?q=...
    page = request.args.get("page", 1, type=int)
    return jsonify(query=q, page=page)

@app.route("/items", methods=["POST"])
def create_item():
    data = request.get_json(silent=True) or {}
    if not data.get("name"):
        return jsonify(error="name is required"), 400
    return jsonify(id=1, name=data["name"]), 201

A view can return a string, a dict (converted to JSON), or a tuple of (body, status). Use abort(404) to stop with an error.

@app.errorhandler(404)
def not_found(e):
    return jsonify(error="Not found"), 404
Flask or FastAPI?

Flask is great for server-rendered sites and small services. For new JSON APIs with automatic validation and docs, FastAPI (covered in this section) is often a better fit.

Try it yourself

Add GET /add?a=2&b=3 returning the sum as JSON, responding with 400 if either value is missing or not a number.

Show solution
@app.route("/add")
def add():
    a = request.args.get("a", type=float)
    b = request.args.get("b", type=float)
    if a is None or b is None:
        return jsonify(error="a and b must be numbers"), 400
    return jsonify(sum=a + b)