Intermediate Chapter 176 · 30 min read · Module 14: Advanced Application Development
Introduction to Web Development with Python
- After this chapter you can explain the client, server, request and response cycle.
- You can read the parts of a URL and an HTTP status code.
- You can name common web frameworks in Python and say how they differ.
- You can describe how a simple Python web app routes a path to a function.
- You can escape user text to avoid unsafe HTML.
Every time you open a website, your browser sends a message to another computer and gets a page back. Python is used on that other computer by many large websites, because it is easy to read and has strong libraries. Learning web development with Python means learning how to write the program that answers those messages.
In this chapter you will see the big picture. You will learn what HTTP is, how a URL is built, what status codes mean, and how a Python program turns a request into a response. You will also meet the main frameworks, Flask, Django and FastAPI, and see why they exist.
You will not need a network connection for the runnable examples. They use the standard library to show the ideas in a small, safe way. The framework examples are marked as not runnable here because they need an installed package and a running server.
How the web works
The web follows a simple pattern. A client, usually a browser, sends a request to a server. The server runs some code and sends back a response. The language they use to talk is HTTP, the HyperText Transfer Protocol. The response may be an HTML page, some JSON data, an image or an error message.
A request contains a method, a path, headers and sometimes a body. The two most common methods are GET, which asks for data, and POST, which sends data such as a filled-in form. A response contains a status code, headers and a body.
Parts of a URL
A URL tells the browser where to go. It has a scheme (https), a host (example.com), an optional port, a path (/products/5) and an optional query string (?sort=price). The standard library module urllib.parse can split a URL into these parts, which helps you understand what your server will receive.
from urllib.parse import urlparse, parse_qs
url = "https://shop.example.com/products/5?sort=price&page=2"
parts = urlparse(url)
print(parts.scheme)
print(parts.netloc)
print(parts.path)
print(parse_qs(parts.query))Status codes
Every response starts with a three digit status code. The first digit shows the group: 2xx means success, 3xx means redirection, 4xx means the client made a mistake, and 5xx means the server had a problem. Python's http.HTTPStatus enum gives the code a readable name.
from http import HTTPStatus
for code in (200, 301, 404, 500):
status = HTTPStatus(code)
print(code, status.phrase)| Code | Meaning | When you see it |
|---|---|---|
| 200 | OK | The page loaded normally |
| 301 | Moved Permanently | The address has changed |
| 404 | Not Found | The path does not exist |
| 403 | Forbidden | Access is not allowed |
| 500 | Internal Server Error | The server code crashed |
Routing: from a path to a function
The heart of a web app is routing. The server looks at the path of the request and chooses which Python function should answer it. Python defines a standard interface for this called WSGI. A WSGI application is simply a function that receives the request details and a start_response function, and returns the body as a list of bytes. Frameworks hide these details, but the idea is the same. The example below calls such an app directly, without any network.
from wsgiref.util import setup_testing_defaults
def call(app, path):
environ = {"REQUEST_METHOD": "GET", "PATH_INFO": path}
setup_testing_defaults(environ)
environ["PATH_INFO"] = path
seen = {}
def start_response(status, headers):
seen["status"] = status
body = b"".join(app(environ, start_response))
return seen["status"], body.decode()
def app(environ, start_response):
path = environ["PATH_INFO"]
if path == "/":
start_response("200 OK", [("Content-Type", "text/plain")])
return [b"Welcome home"]
start_response("404 Not Found", [("Content-Type", "text/plain")])
return [b"No such page"]
print(call(app, "/"))
print(call(app, "/missing"))Frameworks
Writing everything by hand is slow, so most people use a framework. A framework handles routing, requests, templates and many security details for you.
- Flask is small and flexible. You choose the extra tools you need. It is a good first framework.
- Django is large and includes an admin panel, a database layer (ORM), user login and forms. It suits big sites.
- FastAPI is modern and fast, built for APIs, and it uses type hints to check data.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from Flask"
@app.route("/hello/<name>")
def hello(name):
return f"Hello, {name}!"
if __name__ == "__main__":
app.run(debug=True)Returning data as JSON
Many modern sites send data instead of full pages, and JavaScript in the browser draws it. The common format is JSON. Python's json module converts dictionaries and lists to JSON text and back. This is the basis of web APIs.
import json
product = {"id": 5, "name": "Pen", "price": 12.5, "in_stock": True}
text = json.dumps(product)
print(text)
back = json.loads(text)
print(back["name"], back["price"])Safety: never trust user input
Anything that a visitor types can contain harmful HTML or script. If you put it into a page without care, an attacker can run code in other visitors' browsers. This attack is called cross-site scripting (XSS). The fix is to escape special characters before showing text. Frameworks and template engines such as Jinja2 do this automatically, but you should know why.
import html
comment = "<script>alert('hi')</script>"
print(html.escape(comment))Running a server during development
While you learn, you run the server on your own computer at the address 127.0.0.1 (also called localhost). Only your machine can reach it. The development server restarts when you change code. For real websites you deploy to a production server with a tool such as gunicorn, never the development server.
from http.server import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"Hello browser")
HTTPServer(("127.0.0.1", 8000), Handler).serve_forever()Python syntax
@app.route("/path")
def view():
return "response text"urlparse(url).path # split a URLjson.dumps(data) / json.loads(text)Real-world applications
- Company websites, blogs and online shops.
- REST APIs that serve mobile apps and single page apps.
- Dashboards and admin tools for internal use.
- Machine learning models exposed as web services.
- Automation tools that receive webhooks from other services.
Common mistakes
Fix: Escape it with html.escape or use a template engine that escapes automatically.
Fix: Deploy with a production server such as gunicorn behind a web server.
Fix: Python runs on the server; the browser runs HTML, CSS and JavaScript.
Fix: Return the correct code, such as 404 for a missing page, so clients can react.
Fix: Use POST for actions that change data or carry private information.
Important tips
- Start with Flask to learn the ideas, then try Django for larger projects.
- Use a virtual environment for every web project.
- Read the status code first when something goes wrong.
- Use the browser developer tools Network tab to see real requests.
Key points summary
- Web communication follows client, request, server, response.
- HTTP defines methods (GET, POST) and status codes.
- A URL has a scheme, host, path and query string.
- Routing maps a path to a Python function.
- Frameworks like Flask, Django and FastAPI handle common tasks.
- Always escape or validate user input.
Exam and interview points
- HTTP status groups: 2xx success, 3xx redirect, 4xx client error, 5xx server error.
- WSGI is the standard interface between Python web servers and apps.
- Flask uses decorators such as @app.route for routing.
- Django follows the MTV pattern (model, template, view).
- XSS is prevented by escaping output.
Quick revision
- Client sends request, server sends response
- GET reads, POST sends
- 200 ok, 404 not found, 500 server error
- Route = path to function
- Escape user input
Frequently asked questions
Which framework should a beginner choose?
Flask is the easiest to start with because it is small. Django is better when you want many built-in features.
Does Python run in the browser?
Not normally. Browsers run JavaScript. Python runs on the server and sends HTML or JSON to the browser.
What is the difference between GET and POST?
GET asks for data and puts values in the URL. POST sends data in the body and is used for forms and changes.
What does 404 mean?
The server could not find anything at the requested path.
What is an API?
A set of URLs that return data, usually JSON, for programs to use instead of showing a web page.
Practise this chapter
19 practice questions Take the chapter quiz