Python Flask
last modified November 16, 2026 Python 3.15
In this article we show how to create web applications in Python with Flask.
Flask is a Python micro web framework. The core contains only routing, request and response handling, templates, and a development server; validation, form handling, database access, or authentication are added with extensions. Flask is built on the Werkzeug WSGI toolkit and the Jinja template engine.
The Web Server Gateway Interface (WSGI) is a calling convention for web servers to forward requests to web applications written in Python. A Flask application is a WSGI application, so in production it runs under a WSGI server such as Gunicorn or Waitress; during development we use the server built into Flask.
The examples in this article use Flask 3.1 with Python 3.15. We send requests
to the applications with the curl command line tool.
Installation
We create a virtual environment and install Flask into it with
pip.
$ python -m venv .venv $ source .venv/bin/activate $ pip install -q Flask $ flask --version Python 3.15.2 Flask 3.1.3 Werkzeug 3.1.9
A simple application
In the first example, we create a minimal Flask application. Each example in
this article lives in its own directory; this one in hello.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello there!\n'
The application returns a short text message for the home page.
app = Flask(__name__)
The Flask object is the WSGI application and the central object
of the framework. The __name__ argument tells Flask where to look
for resources such as templates and static files.
@app.route('/')
def hello():
return 'Hello there!\n'
The route decorator maps a URL path to a view
function. The returned string becomes the body of the response, with
the 200 status code and the text/html content type.
Running the application
The flask run command starts the development server. The
--app option names the module with the application; it can be
omitted if the module is called app.py or
wsgi.py. The --debug option enables the
interactive debugger and reloads the code when a file changes.
$ cd hello $ flask --app app run * Serving Flask app 'app' * Debug mode: off WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000 Press CTRL+C to quit
Sending a request
While the server runs in one terminal, we send requests to it from another one. The default port is 5000.
$ cd hello $ curl localhost:5000 Hello there! $ curl -i localhost:5000 HTTP/1.1 200 OK Server: Werkzeug/3.1.9 Python/3.15.2 Date: Mon, 16 Nov 2026 21:40:39 GMT Content-Type: text/html; charset=utf-8 Content-Length: 13 Connection: close Hello there!
Query parameters
The query string is the part of the URL after the ? character.
It contains key/value pairs that refine the request. Flask provides them in
the request.args dictionary.
from flask import Flask, request
app = Flask(__name__)
@app.route('/greet')
def greet():
name = request.args.get('name', 'Guest')
times = request.args.get('times', 1, type=int)
msg = f'Hello {name}\n' * times
return msg, 200, {'Content-Type': 'text/plain; charset=utf-8'}
@app.route('/tags')
def tags():
values = request.args.getlist('tag')
return {'tags': values, 'count': len(values)}
The application greets the user given in the name query
parameter.
name = request.args.get('name', 'Guest')
times = request.args.get('times', 1, type=int)
The get method returns a default value when the parameter is
missing. With the type argument, the value is converted; if the
conversion fails, the default is used as well.
return msg, 200, {'Content-Type': 'text/plain; charset=utf-8'}
A view can return a tuple of the body, the status code, and the headers.
values = request.args.getlist('tag')
return {'tags': values, 'count': len(values)}
A parameter can occur multiple times; getlist returns all its
values. A returned dictionary is converted to JSON.
$ cd query
$ curl 'localhost:5000/greet?name=Lucia'
Hello Lucia
$ curl localhost:5000/greet
Hello Guest
$ curl 'localhost:5000/greet?name=Peter×=3'
Hello Peter
Hello Peter
Hello Peter
$ curl 'localhost:5000/greet?name=Peter×=x'
Hello Peter
$ curl 'localhost:5000/greet?name=J%C3%A1n%20Nov%C3%A1k'
Hello Ján Novák
$ curl 'localhost:5000/tags?tag=python&tag=web&tag=flask'
{"count":3,"tags":["python","web","flask"]}
Path parameters
Values can also be passed in the path of the URL. A path parameter is written
in angle brackets in the route, optionally with a converter:
<int:user_id>.
from flask import Flask
app = Flask(__name__)
users = {1: 'Paul', 2: 'Lucy', 3: 'Robert'}
@app.route('/greet/<name>')
def greet(name):
return f'Hello {name}\n'
@app.route('/users/<int:user_id>')
def user(user_id):
return f'User {user_id}: {users.get(user_id, "unknown")}\n'
@app.route('/files/<path:subpath>')
def files(subpath):
return f'Requested file: {subpath}\n'
@app.route('/about/')
def about():
return 'About page\n'
The value of a path parameter is passed to the view function as a keyword
argument. The int converter accepts only digits and passes an
integer, so /users/abc does not match and gives a 404 error. The
path converter accepts slashes.
@app.route('/about/')
A route with a trailing slash behaves like a directory: a request without the slash is redirected to the URL with it. A route without a trailing slash returns 404 for a request that has one.
$ cd paths
$ curl localhost:5000/greet/Robert
Hello Robert
$ curl localhost:5000/users/2
User 2: Lucy
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:5000/users/abc
404
$ curl localhost:5000/files/docs/2026/report.pdf
Requested file: docs/2026/report.pdf
$ curl -i localhost:5000/about
HTTP/1.1 308 PERMANENT REDIRECT
Server: Werkzeug/3.1.9 Python/3.15.2
Date: Mon, 16 Nov 2026 21:40:43 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 243
Location: http://localhost:5000/about/
Connection: close
<!doctype html>
<html lang=en>
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to the target URL: <a href="http://localhost:5000/about/">http://localhost:5000/about/</a>. If not, click the link.
$ curl -L localhost:5000/about
About page
HTTP methods
By default, a route responds to GET requests (and HEAD and OPTIONS). Other
methods are enabled with the methods argument or with the
get, post, put, delete,
and patch shortcut decorators.
from flask import Flask, request
app = Flask(__name__)
users = ['Paul', 'Lucy']
@app.get('/users')
def list_users():
return users
@app.post('/users')
def create_user():
name = request.form['name']
users.append(name)
return {'created': name, 'id': len(users)}, 201
@app.route('/ping', methods=['GET', 'PUT'])
def ping():
return f'{request.method} received\n'
The /users path has two view functions: one lists the users, the
other one adds a user from the submitted form data. The
request.form dictionary holds the fields of a URL-encoded or
multipart form.
return {'created': name, 'id': len(users)}, 201
The 201 Created status code tells the client that a new resource was created. A returned list is converted to JSON just like a dictionary.
$ cd methods
$ curl localhost:5000/users
["Paul","Lucy"]
$ curl -d name=Robert localhost:5000/users
{"created":"Robert","id":3}
$ curl localhost:5000/users
["Paul","Lucy","Robert"]
$ curl -X PUT localhost:5000/ping
PUT received
$ curl -s -o /dev/null -w '%{http_code}\n' -X DELETE localhost:5000/ping
405
$ curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:5000/users
400
Method errors
In the previous transcript, the DELETE request to /ping was
answered with 405 Method Not Allowed, because the route accepts only GET and
PUT. The POST request without form data got 400 Bad Request: reading a
missing key from request.form raises a KeyError
subclass, which Flask turns into a 400 response.
Posting JSON data
The request.get_json method parses a JSON request body. The
request must have the application/json content type.
{
"customer": "Lucy",
"items": [
{"name": "pen", "price": 1.2, "qty": 10},
{"name": "notebook", "price": 3.5, "qty": 2}
]
}
This is the order that we send to the application.
from flask import Flask, request
app = Flask(__name__)
@app.post('/orders')
def create_order():
data = request.get_json(silent=True)
if data is None:
return {'error': 'JSON body expected'}, 415
items = data.get('items', [])
if not items:
return {'error': 'no items'}, 422
total = sum(item['price'] * item['qty'] for item in items)
return {'customer': data.get('customer'), 'items': len(items),
'total': round(total, 2)}, 201
The application computes the total price of an order. With
silent=True, get_json returns None for
a request that is not JSON instead of raising an error, so we can return our
own error message with the 415 Unsupported Media Type status. An order without
items gets 422 Unprocessable Content.
$ cd posting
$ curl -i -H 'Content-Type: application/json' -d @../order.json localhost:5000/orders
HTTP/1.1 201 CREATED
Server: Werkzeug/3.1.9 Python/3.15.2
Date: Mon, 16 Nov 2026 21:40:47 GMT
Content-Type: application/json
Content-Length: 43
Connection: close
{"customer":"Lucy","items":2,"total":19.0}
$ curl -w '%{http_code}\n' -H 'Content-Type: application/json' -d '{"customer": "Paul", "items": []}' localhost:5000/orders
{"error":"no items"}
422
$ curl -w '%{http_code}\n' -d 'customer=Paul' localhost:5000/orders
{"error":"JSON body expected"}
415
Response objects, cookies, and redirects
The make_response function creates a response object from a
return value, so that we can set headers and cookies on it. The
redirect function returns a redirect response, and
url_for builds the URL of a view function.
from flask import Flask, make_response, redirect, request, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'Home page\n'
@app.route('/hello/<name>')
def hello(name):
resp = make_response(f'Hello {name}\n')
resp.headers['X-Greeting'] = 'yes'
resp.mimetype = 'text/plain'
resp.set_cookie('visitor', name, max_age=3600, httponly=True)
return resp
@app.route('/visit')
def visit():
name = request.cookies.get('visitor', 'stranger')
return f'Welcome back, {name}\n'
@app.route('/old')
def old():
return redirect(url_for('hello', name='redirected'))
The hello view adds a custom header, changes the content type,
and sets a cookie valid for one hour. The visit view reads the
cookie from request.cookies.
return redirect(url_for('hello', name='redirected'))
The url_for function takes the name of the view function and its
parameters; this is more robust than hard-coding paths. The redirect has the
302 Found status by default.
$ cd responses $ curl -i -c cookies.txt localhost:5000/hello/Peter HTTP/1.1 200 OK Server: Werkzeug/3.1.9 Python/3.15.2 Date: Mon, 16 Nov 2026 21:40:49 GMT Content-Type: text/plain; charset=utf-8 Content-Length: 12 X-Greeting: yes Set-Cookie: visitor=Peter; Expires=Mon, 16 Nov 2026 22:40:49 GMT; Max-Age=3600; HttpOnly; Path=/ Connection: close Hello Peter $ curl -b cookies.txt localhost:5000/visit Welcome back, Peter $ curl localhost:5000/visit Welcome back, stranger $ curl -i localhost:5000/old HTTP/1.1 302 FOUND Server: Werkzeug/3.1.9 Python/3.15.2 Date: Mon, 16 Nov 2026 21:40:49 GMT Content-Type: text/html; charset=utf-8 Content-Length: 221 Location: /hello/redirected Connection: close <!doctype html> <html lang=en> <title>Redirecting...</title> <h1>Redirecting...</h1> <p>You should be redirected automatically to the target URL: <a href="/hello/redirected">/hello/redirected</a>. If not, click the link.
JSON responses
Flask converts returned dictionaries and lists to JSON automatically. Other
values, such as numbers, can be converted with jsonify. The
abort function stops the request with an HTTP error.
from flask import Flask, abort, jsonify
app = Flask(__name__)
movies = {
1: {'title': 'Toy Story', 'year': 1995},
2: {'title': 'The Raid', 'year': 2011},
3: {'title': 'Hero', 'year': 2002},
4: {'title': 'Ip Man', 'year': 2008},
}
@app.route('/movies')
def get_movies():
return movies
@app.route('/movies/<int:movie_id>')
def get_movie(movie_id):
if movie_id not in movies:
abort(404)
return movies[movie_id]
@app.route('/titles')
def titles():
return [m['title'] for m in movies.values()]
@app.route('/count')
def count():
return jsonify(len(movies))
The application serves a small collection of movies. JSON object keys must be strings, so the integer keys of the dictionary are converted to strings. Requesting a movie that does not exist returns 404.
$ cd movies
$ curl localhost:5000/movies
{"1":{"title":"Toy Story","year":1995},"2":{"title":"The Raid","year":2011},"3":{"title":"Hero","year":2002},"4":{"title":"Ip Man","year":2008}}
$ curl -i localhost:5000/movies/3
HTTP/1.1 200 OK
Server: Werkzeug/3.1.9 Python/3.15.2
Date: Mon, 16 Nov 2026 21:40:51 GMT
Content-Type: application/json
Content-Length: 29
Connection: close
{"title":"Hero","year":2002}
$ curl localhost:5000/titles
["Toy Story","The Raid","Hero","Ip Man"]
$ curl localhost:5000/count
4
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:5000/movies/9
404
Templates
The render_template function renders a Jinja template from the
templates directory with the given variables.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/greet/<name>')
def greet(name):
langs = ['Python', 'Go', 'Rust']
return render_template('index.html', name=name, langs=langs)
The view passes the name from the path and a list of languages to the
index.html template.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Greeting</title>
</head>
<body>
<p>Hello {{ name }}</p>
<ul>
{% for lang in langs %}
<li>{{ loop.index }}. {{ lang }}</li>
{% endfor %}
</ul>
</body>
</html>
The {{ }} delimiters output a value and the
{% %} delimiters contain statements such as the
for loop. The loop.index variable is the current
iteration number, starting from 1.
$ cd greet
$ curl localhost:5000/greet/Peter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Greeting</title>
</head>
<body>
<p>Hello Peter</p>
<ul>
<li>1. Python</li>
<li>2. Go</li>
<li>3. Rust</li>
</ul>
</body>
</html>
$ curl -s 'localhost:5000/greet/%3Cscript%3E' | grep Hello
<p>Hello <script></p>
Automatic escaping
In the previous transcript, the second request passed
<script> as the name. Flask enables autoescaping for
.html templates, so the angle brackets were output as
< and > entities. This protects the
application against cross-site scripting (XSS) attacks. See the
Jinja tutorial for more template features.
Static files
Static files, such as CSS, JavaScript, and images, do not change. Flask serves
them from the static directory under the /static
URL path.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/about')
def about():
return app.send_static_file('about.html')
The home page renders a template; the about page returns a static HTML file
with the send_static_file method.
body { font-family: sans-serif; margin: 2em; }
This is a small stylesheet in the static directory.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<p>About page</p>
</body>
</html>
The about.html page is a plain HTML file without template
directives.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home page</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<p>Home page</p>
<a href="{{ url_for('about') }}">About</a>
</body>
</html>
The template links the stylesheet and the about page with
url_for. For static files, the endpoint name is
static and the file is given in the filename
parameter.
$ cd static_demo
$ curl -s localhost:5000/ | grep -E 'stylesheet|href'
<link rel="stylesheet" href="/static/style.css">
<a href="/about">About</a>
$ curl -i localhost:5000/static/style.css
HTTP/1.1 200 OK
Server: Werkzeug/3.1.9 Python/3.15.2
Date: Mon, 16 Nov 2026 21:40:55 GMT
Content-Disposition: inline; filename=style.css
Content-Type: text/css; charset=utf-8
Content-Length: 47
Last-Modified: Mon, 16 Nov 2026 21:38:10 GMT
Cache-Control: no-cache
ETag: "1794865090.439356-47-344535186"
Date: Mon, 16 Nov 2026 21:40:55 GMT
Accept-Ranges: bytes
Connection: close
body { font-family: sans-serif; margin: 2em; }
$ curl localhost:5000/about
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<p>About page</p>
</body>
</html>
Sending files
The send_file function sends the contents of a file or a binary
file-like object to the client.
import csv
import io
from flask import Flask, send_file
app = Flask(__name__)
rows = [('name', 'population'), ('Bratislava', 475000), ('Prague', 1384000)]
@app.route('/report')
def report():
text = io.StringIO()
csv.writer(text, lineterminator='\n').writerows(rows)
data = io.BytesIO(text.getvalue().encode('utf-8'))
return send_file(data, mimetype='text/csv', as_attachment=True,
download_name='cities.csv')
The application generates a CSV report in memory and sends it as an
attachment. The download_name parameter sets the file name in
the Content-Disposition header.
$ cd download $ curl -i localhost:5000/report HTTP/1.1 200 OK Server: Werkzeug/3.1.9 Python/3.15.2 Date: Mon, 16 Nov 2026 21:40:57 GMT Content-Disposition: attachment; filename=cities.csv Content-Type: text/csv; charset=utf-8 Content-Length: 49 Cache-Control: no-cache Date: Mon, 16 Nov 2026 21:40:57 GMT Accept-Ranges: bytes Connection: close name,population Bratislava,475000 Prague,1384000 $ curl -s -OJ localhost:5000/report $ cat cities.csv name,population Bratislava,475000 Prague,1384000
Error handlers
The errorhandler decorator registers a function that creates the
response for an HTTP error code or an exception class.
from flask import Flask, abort, render_template
app = Flask(__name__)
pages = {'about': 'About page', 'contact': 'Contact page'}
@app.route('/<page>')
def show(page):
if page not in pages:
abort(404)
return f'{pages[page]}\n'
@app.route('/admin')
def admin():
abort(403)
@app.route('/crash')
def crash():
return 1 / 0
@app.errorhandler(404)
def not_found(error):
return render_template('404.html', path=error.description), 404
@app.errorhandler(403)
def forbidden(error):
return {'error': 'forbidden', 'code': 403}, 403
@app.errorhandler(500)
def server_error(error):
return 'Something went wrong on our side\n', 500
We register handlers for the 404, 403, and 500 errors. The 404 handler renders
a template, the 403 handler returns JSON. An unhandled exception in a view,
here a ZeroDivisionError, causes a 500 Internal Server Error,
which is handled by our 500 handler; the traceback is written to the server
log.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404 error</title>
</head>
<body>
<p>404 - page not found</p>
</body>
</html>
This is the error page shown for missing pages.
$ cd errors
$ curl localhost:5000/about
About page
$ curl -i localhost:5000/blog
HTTP/1.1 404 NOT FOUND
Server: Werkzeug/3.1.9 Python/3.15.2
Date: Mon, 16 Nov 2026 21:40:59 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 158
Connection: close
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404 error</title>
</head>
<body>
<p>404 - page not found</p>
</body>
</html>
$ curl localhost:5000/admin
{"code":403,"error":"forbidden"}
$ curl localhost:5000/crash
Something went wrong on our side
A database application
In the following example, we serve data from an SQLite database with the
Flask-SQLAlchemy extension. It is installed with pip install
Flask-SQLAlchemy.
import click
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cities.db'
db = SQLAlchemy(app, model_class=Base)
class City(db.Model):
__tablename__ = 'cities'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
population: Mapped[int]
def to_dict(self):
return {'id': self.id, 'name': self.name,
'population': self.population}
@app.cli.command('init-db')
def init_db():
db.drop_all()
db.create_all()
db.session.add_all([
City(name='Bratislava', population=475000),
City(name='Budapest', population=1686000),
City(name='Prague', population=1384000),
City(name='Warsaw', population=1862000),
City(name='Berlin', population=3897000),
])
db.session.commit()
click.echo('Database initialized')
@app.route('/cities')
def all_cities():
cities = db.session.execute(db.select(City).order_by(City.name)).scalars()
return [city.to_dict() for city in cities]
@app.route('/cities/<int:city_id>')
def one_city(city_id):
return db.get_or_404(City, city_id).to_dict()
@app.route('/cities/big/<int:limit>')
def big_cities(limit):
query = db.select(City.name).where(City.population > limit)
return list(db.session.execute(query).scalars())
The application defines a City model mapped to the
cities table and three routes that return the data as JSON.
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cities.db' db = SQLAlchemy(app, model_class=Base)
A relative SQLite path is placed in the application's instance
folder, which Flask creates next to the application.
class City(db.Model):
__tablename__ = 'cities'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
population: Mapped[int]
The columns are declared with SQLAlchemy 2.0 type annotations. A
Mapped[str] annotation without a mapped_column
call creates a non-nullable column of the matching type.
@app.cli.command('init-db')
def init_db():
The app.cli.command decorator adds a custom command to the
flask command line tool. The init-db command creates
the table and fills it with data.
cities = db.session.execute(db.select(City).order_by(City.name)).scalars()
We build a select statement and execute it in the session;
scalars returns the City objects instead of rows.
The get_or_404 method returns an object by its primary key or
aborts with 404.
$ cd cities
$ flask init-db
Database initialized
$ ls instance
cities.db
$ curl localhost:5000/cities
[{"id":5,"name":"Berlin","population":3897000},{"id":1,"name":"Bratislava","population":475000},{"id":2,"name":"Budapest","population":1686000},{"id":3,"name":"Prague","population":1384000},{"id":4,"name":"Warsaw","population":1862000}]
$ curl localhost:5000/cities/3
{"id":3,"name":"Prague","population":1384000}
$ curl localhost:5000/cities/big/1500000
["Budapest","Warsaw","Berlin"]
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:5000/cities/42
404
Testing with the test client
The test_client method creates a client that sends requests to
the application directly, without a running server. It is the basis for
testing Flask applications with pytest or unittest.
from flask import Flask, request
app = Flask(__name__)
@app.route('/add')
def add():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return {'sum': a + b}
The application adds two numbers from the query string.
from app import app
client = app.test_client()
resp = client.get('/add?a=3&b=4')
print(resp.status_code, resp.json)
assert resp.json == {'sum': 7}
resp = client.get('/add?a=3')
print(resp.status_code, resp.json)
resp = client.get('/missing')
print(resp.status_code, resp.mimetype)
resp = client.post('/add')
print(resp.status_code, resp.headers['Allow'])
The script sends requests with the test client and checks the responses. The
json attribute holds the parsed JSON body. A POST request to a
GET-only route returns 405, and the Allow header lists the
permitted methods.
$ cd testing
$ python test_app.py
200 {'sum': 7}
200 {'sum': 3}
404 text/html
405 GET, OPTIONS, HEAD
Source
Flask-SQLAlchemy documentation
In this article we have created web applications in Python with Flask. See also Python Jinja, Python Bottle, and Python GET and POST requests.
Author
List all Python tutorials.