This chapter introduces the fundamental tools used for web programming in Python: the requests library for consuming data from the web (APIs) and the Flask micro-framework for building web applications and APIs. This provides a high-level view of Python’s role in network and web development.
Python is a dominant language in backend web development. These two tools represent the core of client-side and server-side interaction.
1. The requests Library (HTTP Client)
The requests library is the standard method for making HTTP requests (e.g., fetching a webpage or interacting with a REST API) in Python. It simplifies the complex world of networking into a clean, human-readable format.
- Installation:
pip install requests
A. Making a GET Request
The most common request type is GET, used to retrieve data from a specified resource.
import requests
# Makes a GET request to the public GitHub API
response = requests.get("https://api.github.com/users/octocat")
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Get the data in JSON format (common API format)
user_data = response.json()
print(f"Username: {user_data['login']}")
else:
print(f"Request failed with status code: {response.status_code}")
B. POST Requests
POST requests are used to send data to a server (e.g., submitting a form or creating a new record).
# Data to be sent to the API
new_post_data = {
"title": "My New Post",
"body": "This is content."
}
# The data argument automatically sends the data in the request body
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post_data)
print(response.json())
2. Flask (Micro Web Framework)
Flask is a popular, lightweight web framework often referred to as a “microframework” because it keeps the core small and simple, allowing developers to choose their own tools for databases, authentication, etc.
- Installation:
pip install Flask
A. Basic Application Structure
A minimal Flask application requires an app instance, a route, and a view function.
- Route: The URL path (e.g.,
/or/about). - View Function: The Python function that runs when a user navigates to that route.
from flask import Flask
# Create the application instance
app = Flask(__name__)
# Define the root route ("/")
@app.route("/")
def home():
return "<h1>Welcome to the Flask App!</h1>" # Returns content to the browser
# Define another route
@app.route("/greet/<name>")
def greet(name):
# 'name' is captured from the URL path
return f"Hello, {name}!"
# To run the app locally, you would typically run
# 'flask run' in the terminal, or use the following lines:
# if __name__ == "__main__":
# app.run(debug=True)
B. Using HTML Templates
For rendering complex, dynamic web pages, Flask uses the Jinja templating engine. The view function renders a template, injecting Python variables into the HTML.
- Create a folder named
templates. - Place your HTML files (e.g.,
index.html) inside it. - Use the
render_templatefunction in your view function.
from flask import Flask, render_template
# ... app initialization ...
# Example view function using a template
@app.route("/profile/<user_name>")
def profile(user_name):
# Looks for 'profile.html' in the 'templates' folder
return render_template("profile.html", username=user_name, title="User Profile")
