Learn / Frameworks / Flask / Introduction and Routes

Flask · Lesson 1 of 4

Introduction and Routes

Create a Flask app, define routes and return JSON.

  • Beginner
  • 12 min read
  • 3 objectives

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.

Setup and hello world

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.

Routes with variables

@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.

HTTP methods and the request object

@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.

Error handlers

@app.errorhandler(404)
def not_found(e):
    return jsonify(error="Not found"), 404
# Write your solution here
Up next · Lesson 2Templates and FormsRender HTML with Jinja2 and process form submissions.