Python Flask Introduction
In this page:
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
# 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
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
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
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
from flask import Flask
app = Flask(__name__)
@app.route("/data")
def data():
return {"status": "ok"}
client = app.test_client()
print(client.get("/data").json)
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB