← Back to Python Course | Chapter 13: Data Science & Web | Lesson 12 of 14

Python Flask Introduction

Introduction to Flask

Flask is a minimal, unopinionated web framework -- it gives you routing and request handling without prescribing a project structure or bundling an ORM, which makes it a good fit for small services and APIs. Install it with pip install flask before running any Flask code.

Example: Introduction to Flask

python
# pip install flask
from flask import Flask
app = Flask(__name__)
print(type(app))

Flask App Routing

Routing maps a URL path to the Python function that should handle requests to it, declared with the @app.route('/path') decorator directly above the handler function. When a browser or client requests that path, Flask calls the associated function and returns whatever it produces as the HTTP response.

Example: Flask App Routing

python
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, Flask!"

print(app.url_map)

Testing Flask Routes

Flask's built-in test client lets you simulate requests against your routes in code, without starting an actual listening server or opening a real network socket. This makes automated testing of route logic fast and doesn't require any special test infrastructure.

Example: Testing Flask Routes

python
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, Flask!"

client = app.test_client()
response = client.get("/")
print(response.data)

Using Dynamic Route Variables

Writing a path segment inside angle brackets, like /users/<username>, tells Flask to capture that portion of the URL as a variable and pass it directly into the handler function as an argument -- letting one route definition serve an entire family of related URLs.

Example: Using Dynamic Route Variables

python
from flask import Flask
app = Flask(__name__)

@app.route("/users/<username>")
def show_user(username):
    return f"User: {username}"

client = app.test_client()
print(client.get("/users/alex").data)

Returning JSON Responses

Returning a plain Python dictionary from a Flask route handler is automatically converted into a JSON HTTP response with the correct Content-Type header set, which is the most common response shape for a Flask-based API endpoint.

Example: Returning JSON Responses

python
from flask import Flask
app = Flask(__name__)

@app.route("/data")
def data():
    return {"status": "ok"}

client = app.test_client()
print(client.get("/data").json)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.