Skip to main content

Request and Response Objects in Flask

We now know how to route a URL to a specific view function. But web development is a two-way street. Our application needs to be able to receive data from the user and send back more than just a simple string of HTML.

This entire interaction is managed by two central objects in Flask: the request object, which holds all incoming data from the client, and the response object, which we can use to craft a specific reply to send back.


📚 Prerequisites

You should have a basic Flask application with several routes.


🎯 Article Outline: What You'll Master

In this article, you will learn:

  • The Request Object: How to import and use the global request object to inspect incoming requests.
  • Accessing Request Data: How to get data from URL query parameters (request.args) and POST form data (request.form).
  • The Response Object: How to create and customize response objects to set things like status codes and headers.
  • JSON Responses: The proper way to return JSON data from an API endpoint using jsonify.

🧠 Section 1: The request Object

Whenever a browser makes a request to your Flask application, Flask creates a request object that contains all the information the client sent. To access it, you just need to import it from the flask library.

This request object is a "context local," which means that within a single request-response cycle, it always holds the data for the current, active request. You can access it from within your view function without having to pass it as an argument.

Key Attributes of the request object:

  • request.method: The HTTP method used for the request (e.g., 'GET', 'POST').
  • request.args: A dictionary-like object containing the parsed query string parameters.
  • request.form: A dictionary-like object containing data from a submitted HTML form (<form>).
  • request.json: If the request contains JSON data, this holds the parsed data.
  • request.headers: The headers sent by the client.

💻 Section 2: Accessing Incoming Data

Let's see how to get data from the two most common methods: GET query strings and POST forms.

Accessing Query Parameters (request.args)

A query string is the part of a URL that comes after a ?. It's often used for search queries or filtering. Example URL: /search?q=python&sort=newest

We can access this data using request.args.

from flask import Flask, request

app = Flask(__name__)

@app.route("/search")
def search():
# .get() is used to safely access keys that might not exist
query = request.args.get("q", "No query provided")
sort_by = request.args.get("sort", "default")
return f"<h1>Searching for: {query}</h1><p>Sorting by: {sort_by}</p>"

If you visit http://127.0.0.1:5000/search?q=flask+tutorial, your browser will display a page showing that you searched for "flask tutorial".

Accessing Form Data (request.form)

To handle data from an HTML form submitted with the POST method, you first need to tell your route to accept POST requests. Then, you can access the data via request.form.

app.py:

from flask import Flask, request, render_template

app = Flask(__name__)

# This route now accepts both GET and POST requests
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
# This block runs when the form is submitted
username = request.form.get("username")
password = request.form.get("password")
# In a real app, you would validate the password here
return f"<h1>Welcome, {username}!</h1>"

# This block runs for a GET request (when the user first visits the page)
return render_template("login_form.html")

templates/login_form.html:

<!DOCTYPE html>
<html>
<body>
<h2>Login</h2>
<form method="post"> <!-- The method must be "post" -->
<label>Username:</label><br>
<input type="text" name="username"><br> <!-- The 'name' attribute is the key -->
<label>Password:</label><br>
<input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

When you visit /login, you'll see the form. When you fill it out and click submit, the browser sends a POST request, and your view function will process the data from request.form.


🛠️ Section 3: Crafting Responses

So far, we've just been returning strings. Flask is smart enough to turn a string into a response object with a default 200 OK status code and a text/html content type.

For more control, you can create a response object yourself using make_response or return a tuple of (body, status_code, headers).

A very common requirement for APIs is to return data in JSON format. Flask provides a handy helper function called jsonify for this.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api/user/info")
def user_api():
# A sample Python dictionary
user_data = {
"id": 101,
"username": "alice_c",
"email": "[email protected]",
"is_active": True
}
# jsonify converts the dict to a JSON string and sets the
# correct Content-Type header ('application/json')
return jsonify(user_data)

If you visit /api/user/info, your browser will display the raw JSON data, and any API client would be able to parse it correctly.


✨ Conclusion & Key Takeaways

The request and response objects are your primary tools for building interactive web applications. The request object gives you a window into the data sent by the client, and functions like jsonify give you precise control over the data you send back.

Let's summarize the key takeaways:

  • Import and use the request object from flask to access incoming request data.
  • request.args holds URL query parameters (from GET requests).
  • request.form holds data from submitted forms (from POST requests).
  • A view function can return a string, but for more control, you can return a Response object or use helpers like jsonify.
  • Use jsonify to correctly format Python dictionaries as JSON responses for APIs.

➡️ Next Steps

This concludes our introduction to Flask! You now have the foundational knowledge to build simple web pages and APIs.

In the next series, "Building a Simple Web App with Flask," we'll put all these concepts together to build a more complete application, starting with a deeper dive into "Templates in Flask (Part 1): Template inheritance."

Happy coding!