By WebNest Studio Engineering Team
Python Tutorial
Flask Basics
Flask is Python's classic micro-framework. It gives you routing, request and response handling, HTML templating with Jinja2 and a development server — and leaves everything else (database, forms, authentication) to extensions you choose. It is simple, flexible and still used by a huge number of applications, so every Python web developer should be able to read and write Flask code.
This lesson covers routes and URL variables, handling requests and returning JSON, templates, blueprints and testing — and compares Flask with FastAPI so you can choose between them.
Why it matters
Flask is the classic lightweight Python web framework, and a very large amount of existing code is written in it. You are likely to maintain a Flask application at some point, and comparing it with FastAPI is a common interview question. Its ideas of routes, request objects and templates are shared by nearly every web framework.
Core Concepts
Create an app with app = Flask(__name__) and map URLs to view functions with @app.route("/path") or the shortcuts @app.get and @app.post. URL variables use converters: /books/<int:book_id>. The global request object holds request.args (query string), request.form, request.get_json() and headers. Return a string, a dict (converted to JSON), a (body, status) tuple, or use jsonify(), redirect() and abort(404). Run with flask --app app run --debug.
Templates and Blueprints
render_template("page.html", **context) renders Jinja2 templates from the templates/ folder: {{ variable }} prints (auto-escaped against XSS), {% for %} and {% if %} control output, and {% extends "base.html" %} shares layouts. Blueprints group related routes, like FastAPI's APIRouter, and are registered with app.register_blueprint(bp, url_prefix="/api").
Flask or FastAPI?
- FastAPI — JSON APIs, automatic validation and docs from type hints, async support, high performance.
- Flask — server-rendered websites and small services, a mature extension ecosystem (Flask-SQLAlchemy, Flask-Login, Flask-WTF), very little magic.
- Django — large, full-featured websites needing an admin panel, ORM, auth and more out of the box.
- Flask validates nothing by itself; add Pydantic or marshmallow when you need input validation.
Examples
Routes, URL variables, query strings and JSON
# app.py pip install flask run: flask --app app run --debug
from flask import Flask, abort, jsonify, request
app = Flask(__name__)
books = {1: {"title": "Python Basics", "price": 450}, 2: {"title": "Deep Python", "price": 899}}
@app.get("/")
def home():
return "<h1>Webnest Books</h1>"
@app.get("/books")
def list_books():
max_price = request.args.get("max_price", type=int) # ?max_price=500
result = [{"id": i, **b} for i, b in books.items() if max_price is None or b["price"] <= max_price]
return jsonify(result)
@app.get("/books/<int:book_id>")
def get_book(book_id):
if book_id not in books:
abort(404, description="Book not found")
return books[book_id] # dicts become JSON
@app.post("/books")
def add_book():
data = request.get_json()
if not data or "title" not in data:
return {"error": "title is required"}, 400
book_id = max(books) + 1
books[book_id] = {"title": data["title"], "price": data.get("price", 0)}
return {"id": book_id, **books[book_id]}, 201
client = app.test_client() # Flask's built-in test client
print(client.get("/").data.decode())
print(client.get("/books?max_price=500").get_json())
print(client.get("/books/2").get_json(), client.get("/books/9").status_code)
r = client.post("/books", json={"title": "SQL Basics", "price": 350})
print(r.status_code, r.get_json())
print(client.post("/books", json={"price": 10}).get_json())
<h1>Webnest Books</h1>
[{'id': 1, 'price': 450, 'title': 'Python Basics'}]
{'price': 899, 'title': 'Deep Python'} 404
201 {'id': 3, 'price': 350, 'title': 'SQL Basics'}
{'error': 'title is required'}
Jinja2 templates, blueprints and error handlers
from flask import Blueprint, Flask, render_template_string
# templates/books.html (inlined here with render_template_string)
PAGE = """<h2>{{ heading }}</h2>
<ul>{% for book in books %}
<li>{{ book.title }}{% if book.price < 500 %} (budget){% endif %}</li>{% endfor %}
</ul>"""
shop = Blueprint("shop", __name__)
BOOKS = [{"title": "Python Basics", "price": 450}, {"title": "<script>alert(1)</script>", "price": 999}]
@shop.get("/books")
def books_page():
return render_template_string(PAGE, heading="All books", books=BOOKS)
app = Flask(__name__)
app.register_blueprint(shop, url_prefix="/shop")
@app.errorhandler(404)
def not_found(error):
return {"error": "not found"}, 404
client = app.test_client()
print(client.get("/shop/books").data.decode()) # note the escaped <script>
print(client.get("/nowhere").get_json())
<h2>All books</h2>
<ul>
<li>Python Basics (budget)</li>
<li><script>alert(1)</script></li>
</ul>
{'error': 'not found'}
Common Mistakes
- Running the development server (flask run --debug) in production — use Gunicorn or Waitress.
- Trusting request.get_json() data without validating it.
- Marking user content as safe in templates, which disables escaping and allows XSS.
- Keeping all routes in one file instead of using blueprints.
- Forgetting to set a strong SECRET_KEY when using sessions.
Exercise
Using Flask, which must be installed with pip install flask, create a route /hello/<name> that returns a JSON greeting. The greeting word comes from an optional query parameter named greeting and defaults to Hello. The code calls the route with Flask's test client.
Expected output: {'message': 'Hello, Asha!'} then {'message': 'Hi, Asha!'}
from flask import Flask, jsonify, request
app = Flask(__name__)
# TODO: a GET route "/hello/<name>" that reads the optional query parameter "greeting"
# and returns JSON such as {"message": "Hello, Asha!"}
client = app.test_client()
print(client.get("/hello/Asha").get_json())
print(client.get("/hello/Asha?greeting=Hi").get_json())
Show hints
- A URL variable in angle brackets becomes a parameter of the function:
def hello(name):. - Query parameters are read from
request.args.get("greeting", "Hello"), andjsonify(...)builds the JSON response.
Show solution
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.get("/hello/<name>")
def hello(name):
greeting = request.args.get("greeting", "Hello")
return jsonify(message=f"{greeting}, {name}!")
client = app.test_client()
print(client.get("/hello/Asha").get_json())
print(client.get("/hello/Asha?greeting=Hi").get_json())
Quick quiz
1. How does a Flask view function read query parameters?
- A. From request.args
- B. From its function parameters
- C. From request.body
- D. From app.config
Show answer
A. request is a global object that represents the current request.
2. Which template engine does Flask use to render HTML?
- A. Mustache
- B. Jinja2
- C. JSX
- D. Handlebars
Show answer
B. render_template fills a template with the values passed to it.
3. What is a Flask blueprint?
- A. A database model
- B. A deployment file
- C. A group of routes that can be registered on the application, like a FastAPI router
- D. A test fixture
Show answer
C. Blueprints split a large application into modules.
Interview questions
What are the main differences between Flask and FastAPI?
Show answer
Flask is a minimal WSGI framework: it provides routing, the request object and templates, and leaves validation, documentation and async support to extensions. FastAPI is an ASGI framework designed for APIs: it validates input from type hints with Pydantic, generates OpenAPI documentation, supports async natively and has dependency injection built in. Flask suits server-rendered sites and simple services; FastAPI is the usual choice for new JSON APIs.
How does Flask make the request object available without passing it as a parameter?
Show answer
request is a proxy object bound to a context. When a request arrives, Flask pushes a request context for the worker handling it, and the proxy forwards attribute access to the request in the current context. Each thread or task sees its own request, although the name is imported globally. The same mechanism provides session, g and current_app.
Key Points to Remember
- Flask maps routes to view functions; request holds args, form, JSON and headers.
- Return strings, dicts, (body, status) tuples, or use jsonify, redirect and abort.
- Jinja2 templates auto-escape output and support loops, conditions and inheritance.
- Blueprints organise routes; app.test_client() tests them.
- Choose FastAPI for typed JSON APIs, Flask for flexible small apps and server-rendered pages, Django for full-featured sites.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
These examples need a project environment on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering