The Flask Request-Response Cycle
In Flask, every time a client visits a URL, Flask creates a Request object containing all the information sent by the browser. Once your function processes the logic, it must return a Response object. Understanding how to extract data from the request and format the response is the core of API development.
- The Request Object
The request object is global within the context of a function call. It allows you to access URL parameters, form data, JSON payloads, and HTTP headers.
- Creating a Response
By default, if you return a string or a dictionary, Flask automatically converts it into a response with a 200 OK status. However, for APIs, you often need to set custom status codes or headers using make_response or by returning a tuple.
Common Request Attributes
| Attribute | Description | Example Use Case |
|---|---|---|
| request.args | URL Query parameters | Filtering search results (?q=python) |
| request.form | Form data from POST | Traditional HTML form submissions |
| request.json | Parsed JSON body | Modern REST API payloads |
| request.files | Uploaded files | Handling profile picture uploads |
| request.method | HTTP Method | Checking if request is GET or POST |
| request.cookies | Browser cookies | Reading session IDs |
Visualizing the Flow
The flow starts at the client, passes through Flask's routing middleware, hits your view function, and returns through the response pipeline.