How to access data from a Flask request

Flask is a robust Python web framework that allows us to build web applications and APIs. One of the key tasks in web development is processing incoming data from clients, and Flask makes it easier to access and manipulate this data.

To learn about the basics of Flask, we can refer to the following Answer: Learn Flask in five minutes.

Overview of HTTP requests

HTTP methods are standardized ways for clients to communicate their intentions to servers when interacting with resources on the web.

Here’s some commonly used HTTP methods:

  • GET: The GET method requests data from a server.
  • POST: The POST method is used to submit data to be processed by the server.
  • PUT: The PUT method updates an existing resource on the server.
  • DELETE: The DELETE method removes a resource from the server.

Installations

To get the data received in a Flask request, we have a Python package called requests.

pip install requests

In addition to that, a Flask server will also be needed:

pip install Flask

Access data in Flask request

Data can be accessed in the following ways from a Flask request. Let’s discuss them one by one:

1. Accessing the form data

When dealing with form data sent via a POST request, we can use the request.form object to access the data. This is commonly used when processing HTML forms.

request.form.get('value')

2. Returning the JSON data

To return the JSON data in a Flask route, you can use the jsonify() function provided by Flask.

jsonify(data)

3. Accessing query string

Using the request object, we can access the query string parameters from the URL. The query string parameters are the key-value pairs after a URL’s question mark (??).

request.args.get('name')
Query format
Query format

4. Returning the Dictionary Cookies

In Flask, you can manage cookies and return JSON data as responses to client requests.

To set the cookies:

response = make_response("text")
response.set_cookie('key', 'value')

To get the cookies:

request.cookies.get('key')

Code example

Let’s create a simple Flask server that demonstrates working with all these ways to access data from a request.

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <h1>Form Example</h1>

    <h2>Submit Data:</h2>
    <form method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br>
        <label for="age">Age:</label>
        <input type="number" id="age" name="age" required>
        <br>
        <button type="submit">Submit</button>
    </form>

    <h2>Submitted Data:</h2>
    <ul>
        {% for item in data %}
            <li>{{ item.name }}, {{ item.age }}</li>
        {% endfor %}
    </ul>
</body>
</html>
Accessing data from a Flask request

The render_template() function is a built-in feature in Flask that allows you to render and display HTML templates within your application. It’s particularly useful for generating dynamic web pages by injecting data into templates.

Output

The app has five routes, /form, /json, /query, /set-cookies, and /get-cookies. Let’s look at the working and output of all of them. Navigate to the app link (given under the code widget) and append the following routes to the URL:

  • /form: A form will appear. Enter your name and age in it, and the data will be updated.

  • /json: The JSON data passed in the function will be rendered.

  • /query: A sample text Hello, None! Your age is None will be rendered. Append this ahead of the /query: ?name=User&age=23. Now, see the output. It will render the name and age in the query string.

  • /set-cookies: It will set the cookie data as given in the set_cookies() function.

  • /get-cookies: It will show the data we stored in the set_cookies() function.

Sample output

This output is for the route /form :

Sample output
Sample output

Code explanation

  • Lines 1–4: This section imports essential modules— Flask for app creation, render_template for HTML rendering, request for request data access, redirect for URL redirection, jsonify for JSON responses, url_for for URL generation, and make_response for custom HTTP responses. It initializes a Flask server named app.

  • Lines 9–17: This section defines a Flask route at /form that handles GET and POST requests.

    • On a GET request, it renders an HTML template called form.html and passes the data list to it.
    • A POST request retrieves the values of the name and age fields from the form data using request.form.get(). It then appends this data to the data list.
  • Lines 20–24: A function is marked for the /query route, processing query parameters like name and age using request.args.get(). It then forms a response with these values.

  • Lines 27–34: The function is annotated for the /json route. A sample data dictionary, data, is generated. Subsequently, the jsonify() function transforms the data dictionary into a JSON response.

  • Lines 37–43: A function is associated with the route /set-cookies. It involves creating a response object using make_response() and initializing it with the message Cookies have been set! Then, the response object’s set_cookie() method sets two cookies, username and user_id, with corresponding values.

  • Lines 46–52: The function is linked to the /get-cookies route. It employs request.cookies.get() to retrieve the username and user_id cookies from the client. This data is structured into a cookies_dict dictionary and returned.

  • Lines 55–56: This section runs the Flask application, enabling debugging mode, specifying the host as 0.0.0.0, and setting the port to 3000.

Test yourself

Let’s take a moment to ensure you have correctly understood how to get the data in the Flask request. The quiz below helps you check if you have understood the concepts:

Requests in Flask

1

Which request type is used to update an existing resource on a server?

A)

GET

B)

POST

C)

PUT

D)

DELETE

Question 1 of 30 attempted
Copyright ©2024 Educative, Inc. All rights reserved