Build a web app with Flask
Create web pages and JSON APIs with Flask: routes, parameters, templates, forms, status codes, sessions and error handling.
In this lesson you will
- Create routes that return pages and JSON
- Capture URL parameters and form data
- Build a small API with correct status codes
- Know how to grow and deploy a Flask app
About 25 minutes
From scripts to websites
Everything you have built so far runs in a terminal on your own computer. A web application lets anybody with a browser use your Python code: a quiz, a calculator, a booking form, an API for a phone app. Flask is a small, friendly framework that turns Python functions into web pages. It is a perfect first step into web development, and the ideas carry over to every other framework.
Install with pip install flask. To show real output in this lesson, we use Flask’s built-in test client, which sends requests to the app inside the program, exactly as a browser would, without starting a server.
Hello, web
# app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Hello from Flask!</h1>"
if __name__ == "__main__":
app.run(debug=True)
pip install flask
python app.py
# open http://127.0.0.1:5000 in your browser
@app.route("/") is a decorator, the idea from the first lesson of this course. It says: when someone visits the home address, call this function and send back whatever it returns. debug=True reloads the server whenever you save, and shows helpful error pages. Use it while developing, never on a live site.
Routes, parameters and templates
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome"
@app.route("/hello/<name>")
def hello(name):
return f"Hello, {name}!"
@app.route("/square/<int:n>")
def square(n):
return {"n": n, "square": n * n} # a dict becomes JSON
PAGE = """
<h1>{{ title }}</h1>
<ul>{% for s in students %}<li>{{ s.name }}: {{ s.mark }}</li>{% endfor %}</ul>
"""
@app.route("/class")
def show_class():
students = [{"name": "Sara", "mark": 90}, {"name": "Ali", "mark": 72}]
return render_template_string(PAGE, title="Class list", students=students)
client = app.test_client()
for url in ["/", "/hello/Sara", "/square/12", "/class", "/nothing-here"]:
r = client.get(url)
print(url, r.status_code, r.get_data(as_text=True).strip().replace("\n", "")[:70])
/ 200 Welcome
/hello/Sara 200 Hello, Sara!
/square/12 200 {"n":12,"square":144}
/class 200 <h1>Class list</h1><ul><li>Sara: 90</li><li>Ali: 72</li></ul>
/nothing-here 404 <!doctype html><html lang=en><title>404 Not Found</title><h1>Not Found
<name>in a route captures part of the address;<int:n>also converts it to a number.- Returning a dictionary sends JSON, perfect for APIs.
- Templates (Jinja) mix HTML with
{{ values }}and{% loops %}. In real projects they live in atemplates/folder and you callrender_template("page.html", ...). - Unknown addresses automatically give
404 Not Found.
Forms and POST requests
from flask import Flask, request, render_template_string
app = Flask(__name__)
FORM = """
<form method="post">
<input name="a"> + <input name="b">
<button>Add</button>
</form>
{% if result is not none %}<p>Result: {{ result }}</p>{% endif %}
"""
@app.route("/add", methods=["GET", "POST"])
def add():
result = None
if request.method == "POST":
try:
result = float(request.form["a"]) + float(request.form["b"])
except ValueError:
result = "please type numbers"
return render_template_string(FORM, result=result)
client = app.test_client()
r = client.post("/add", data={"a": "2.5", "b": "4"})
print("Result line:", [l.strip() for l in r.get_data(as_text=True).splitlines() if "Result" in l])
r = client.post("/add", data={"a": "x", "b": "4"})
print("Bad input:", [l.strip() for l in r.get_data(as_text=True).splitlines() if "Result" in l])
Result line: ['<p>Result: 6.5</p>']
Bad input: ['<p>Result: please type numbers</p>']
Everything a visitor types is untrusted. Validate and convert it (as above), and never build file paths or database commands directly from it. Jinja templates escape HTML for you, which protects against a common attack called XSS.
A small JSON API
from flask import Flask, jsonify, request
app = Flask(__name__)
todos = [{"id": 1, "task": "Learn Flask", "done": False}]
@app.get("/api/todos")
def list_todos():
return jsonify(todos)
@app.post("/api/todos")
def add_todo():
data = request.get_json()
if not data or "task" not in data:
return jsonify({"error": "task is required"}), 400
todo = {"id": len(todos) + 1, "task": data["task"], "done": False}
todos.append(todo)
return jsonify(todo), 201
@app.get("/api/todos/<int:todo_id>")
def get_todo(todo_id):
for t in todos:
if t["id"] == todo_id:
return jsonify(t)
return jsonify({"error": "not found"}), 404
c = app.test_client()
print(c.post("/api/todos", json={"task": "Build a project"}).status_code)
print(c.post("/api/todos", json={"oops": 1}).get_json())
print(c.get("/api/todos").get_json())
print(c.get("/api/todos/2").get_json())
print(c.get("/api/todos/9").status_code)
201
{'error': 'task is required'}
[{'done': False, 'id': 1, 'task': 'Learn Flask'}, {'done': False, 'id': 2, 'task': 'Build a project'}]
{'done': False, 'id': 2, 'task': 'Build a project'}
404
Here you are on the other side of the conversation from the web requests lesson: your program is the server. Return the right status code (201 created, 400 bad request, 404 not found) and clients can react properly.
Sessions, a visit counter and errors
from flask import Flask, session, abort
app = Flask(__name__)
app.secret_key = "change-me-in-real-life" # signs the cookie; keep it secret!
@app.route("/visit")
def visit():
session["count"] = session.get("count", 0) + 1
return f"You have visited {session['count']} times"
@app.route("/secret")
def secret():
abort(403)
@app.errorhandler(403)
def forbidden(e):
return "Sorry, you may not enter.", 403
c = app.test_client()
print(c.get("/visit").get_data(as_text=True))
print(c.get("/visit").get_data(as_text=True))
print(c.get("/secret").status_code, c.get("/secret").get_data(as_text=True))
You have visited 1 times
You have visited 2 times
403 Sorry, you may not enter.
Growing the project
my_site/
|-- app.py
|-- templates/
| |-- base.html shared header and footer
| `-- index.html {% extends "base.html" %}
|-- static/
| |-- style.css
| `-- app.js
`-- requirements.txt
- Databases: use
sqlite3or the Flask-SQLAlchemy extension to store real data. - Logins: Flask-Login handles users; always store password hashes, never passwords.
- Deploying: put it online with a host such as PythonAnywhere, Render or a small VPS, run by a production server like
gunicorn, notapp.run. - Bigger sites: look at Django, which includes accounts, an admin panel and an ORM out of the box.
Leaving debug=True on a live site. The debugger lets visitors run code on your server. Turn it off in production and keep secret keys in environment variables.
Add a route /double/<int:n> that returns JSON with n and its double, and call it with the test client for 21.
Show one possible answer
from flask import Flask
app = Flask(__name__)
@app.route("/double/<int:n>")
def double(n):
return {"n": n, "double": n * 2}
print(app.test_client().get("/double/21").get_json())
{'double': 42, 'n': 21}
Create a route /greet that reads a query string value (/greet?name=Sara) with request.args.get and defaults to “stranger”.
Hint: request.args.get(key, default)
Show one possible answer
from flask import Flask, request
app = Flask(__name__)
@app.route("/greet")
def greet():
name = request.args.get("name", "stranger")
return f"Hello, {name}!"
c = app.test_client()
print(c.get("/greet?name=Sara").get_data(as_text=True))
print(c.get("/greet").get_data(as_text=True))
Hello, Sara!
Hello, stranger!
Turn the expense tracker from the intermediate project into a web app: a form to add expenses, a page listing them, and a JSON endpoint for totals. Every skill you need is now in your toolbox.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does @app.route("/") do?
- Starts the database
- Imports Flask
- Creates a file
- Connects an address to a function
It is a decorator that registers the page.
What does <int:n> in a route do?
- Imports an integer
- Captures a number from the address
- Makes a loop
- Hides the route
It captures and converts that part of the URL.
Which status code should a missing item return?
- 200
- 201
- 404
- 500
404 means not found.
Why should debug=True never be used on a live site?
- It exposes a debugger that can run code
- It is slow
- It deletes files
- It breaks templates
It is a serious security risk in production.
How does Flask return JSON easily?
- Only with a template
- Use print
- Return a dict or use jsonify
- Impossible
Dictionaries become JSON responses.
Summary
- @app.route connects URLs to functions.
- request holds forms, queries and JSON.
- Return proper status codes.
- Validate input; turn debug off in production.
Questions
Flask or Django?
Flask is small and flexible, ideal for learning and small apps. Django is bigger, with accounts and an admin panel built in.
Can I put my Flask site on my WordPress hosting?
Usually not. Shared WordPress hosting rarely runs Python apps. Use a Python-friendly host such as PythonAnywhere or Render.
What is Jinja?
The template language Flask uses to mix HTML with Python values and loops.
