Introduction to Flask
Build web apps and JSON APIs with Flask — routes, dynamic URLs, query params, and returning JSON responses in minutes.
"Flask is a micro web framework — micro meaning it starts small and you add only what you need. A working web server in 5 lines, a full REST API in 30."
— ShuraiHow a Web Framework Works
Without a framework, you’d need to manually parse HTTP requests, build responses, and manage connections. Flask handles all of that — you just tell it which URL calls which function:
GET /about
matches @app.route
def about():
HTML or JSON
pip install flask
Your First Flask App — 5 Lines
from flask import Flask
app = Flask(__name__) # create the app
@app.route("/") # when someone visits "/"
def home():
return "Hello, World!" # return this response
@app.route("/about")
def about():
return "<h1>About Us</h1><p>Built with Flask!</p>"
if __name__ == "__main__":
app.run(debug=True) # start the server
# Visit: http://127.0.0.1:5000
# Visit: http://127.0.0.1:5000/about
Dynamic URLs — Capture Values from the Path
Use <variable> in the route to capture part of the URL and pass it to your function:
@app.route("/user/<name>")
def profile(name):
return f"<h1>Profile: {name}</h1>"
# /user/Riya → <h1>Profile: Riya</h1>
@app.route("/post/<int:post_id>") # <int:...> converts to integer
def show_post(post_id):
return f"Showing post #{post_id}"
# /post/42 → Showing post #42
# /post/abc → 404 (not an integer)
Reading Query Parameters and POST Data
from flask import Flask, request
# Query params: /search?q=python&lang=en
@app.route("/search")
def search():
query = request.args.get("q", "") # "" = default if missing
lang = request.args.get("lang", "en")
return f"Searching '{query}' in {lang}"
Building a JSON REST API
This is Flask’s most common use in modern apps — a backend that speaks JSON. Use jsonify() to return proper JSON responses:
from flask import Flask, jsonify, request
app = Flask(__name__)
books = [
{"id": 1, "title": "The Alchemist", "author": "Coelho"},
{"id": 2, "title": "Atomic Habits", "author": "Clear"},
{"id": 3, "title": "Sapiens", "author": "Harari"},
]
# GET /api/books → all books
@app.route("/api/books")
def get_all():
return jsonify(books)
# GET /api/books/2 → one book by id
@app.route("/api/books/<int:book_id>")
def get_one(book_id):
book = next((b for b in books if b["id"] == book_id), None)
if book is None:
return jsonify({"error": "not found"}), 404
return jsonify(book)
# POST /api/books → add a new book
@app.route("/api/books", methods=["POST"])
def add_book():
data = request.get_json()
new_book = {"id": len(books) + 1, **data}
books.append(new_book)
return jsonify(new_book), 201 # 201 = Created
debug=True, Flask auto-reloads on code changes and shows detailed error pages. Never use it in production — those detailed error pages expose your source code to anyone who triggers an error."The @app.route decorator is one of the most elegant uses of Python decorators in the real world. It maps a URL to a function — that simple idea is the backbone of most web frameworks."
— Shurai🧠 Quiz — Q1
What does @app.route("/about") do?
🧠 Quiz — Q2
In the route @app.route("/post/<int:post_id>"), what does int: do?
🧠 Quiz — Q3
What does jsonify(data) do in Flask?
🧠 Quiz — Q4
A route needs to accept both GET and POST. How do you declare this?