[Practical Flask API Project Guide] Part 4 Request and Response Processing

Practical Flask API Project Guide – Request and Response Processing

This series of articles will take you to explore in depth Practical Flask API Project Guide. By following Xiaocai’s learning journey, you will gradually master the application of Flask in actual projects. Let’s embark on this exciting learning journey together!

Foreword

When Xiaocai steps into the world of Flask back-end development, processing requests (Request) and generating responses (Response) are very critical parts.

These requests and responses are the primary means of interaction between the backend platform and users or other applications. Let’s take a deeper look at requests and responses in Flask.

Note: This article is described in more detail (i.e. more verbose), but it is all practical information

Request and response processing

In a Flask application, processing client requests and returning appropriate responses is the core of building web applications. Flask provides a wealth of tools and mechanisms to make request processing and response generation efficient and flexible.

1. Request

1.1 HTTP request method

So in all the previous code examples, we accessed it through the GET method.

We did not specify the methods parameter because the view function responds to GET requests by default.

When we have needs for other HTTP methods, we can handle other HTTP methods by specifying the methods parameter. Flask supports common HTTP request methods, such as GET, POST, PUT, DELETE, etc.

The following is a brief description of these HTTP request methods and their purpose:

HTTP method Purpose
GET Obtain resources from the server, usually used to request the reading of data.
POST Submit data to the server, usually used to create new resources or update data.
PUT Submit data to the server, usually used to update existing resources, completely replacing the original data.
DELETE Requests the server to delete the specified resource.
PATCH Partially updates resources on the server, usually used to update part of the resource.
HEAD The request server only returns HTTP header information, without actual content, and is used to check the metadata of the resource.
OPTIONS Requests the server to provide information about supported communication options, typically for cross-origin requests.
TRACE Requests the server to return a request to the client, typically for diagnostic and debugging purposes.

Because the default is a GET request, this is set to a POST request.

from flask import Flask

app = Flask(__name__)

@app.route("/submit", methods=["POST"])
def submit():
    return "Your request method is POST!"

if __name__ == "__main__":
    app.run()

In this example, we define the “/submit” route, which responds to POST requests. The view function will return “Your request method is POST!”

Because submit here is a POST request, if you use the GETrequest method at this time, Flask will throw 404 error (Not Found). This means that Flask cannot find a matching routing rule because the request method does not meet the requirements.

The access effect is shown below:

Multiple HTTP request methods

In development, the commonly used HTTP methods are GET and POST. These two methods are used here for demonstration.

from flask import Flask, request

app = Flask(__name__)

@app.route("/submit", methods=["GET", "POST"])
def submit():
    if request.method == "POST":
        return "Your request method is POST!"
    return "Your request method is GET!"

if __name__ == "__main__":
    app.run()

In this example, we define the “/submit” route, which can respond to GET and POST requests.

  • If the user uses GET to request, otherwise “Your request method is GET!”
  • If the user requests using POST, the view function will return “Your request method is POST!”

The access effect is shown below:

1.2 Request object request

The request object of Flask is a global object and can be accessed directly in the view function. It contains all information about the current request, including URL parameters, form data, request method, etc.

The following are some commonly used request object methods and properties:

Method/Property Description
request.method Get the HTTP request method, such as GET, POST, PUT, etc.
request.args Get a dictionary containing URL query parameters.
request.form Gets a dictionary containing form data (usually used for POST requests).
request.values Get a dictionary containing query parameters and form data.
request.headers Get the header information of the HTTP request and return a dictionary.
request.cookies Get the cookie data in the request and return a dictionary.
request.get(key, default) Get the value of the specified key in the query parameter or form data, you can Specify default value.
request.files Get the uploaded files and return a dictionary, each file is represented as a FileStorage Object.
request.data Get the original data of the HTTP request, usually used to read the data in the request body.
request.json Try to parse the JSON data in the request body and return the parsed Python object.
request.remote_addr Get the client’s IP address.
request.user_agent Get the client’s User-Agent string.

Use a few simple examples to demonstrate:

Read request parameters
  • URL parameters are data passed through the query string of the URL, usually appearing after the question mark, such as http://127.0.0.1:5000/?name=frica01. These parameters can be obtained using the request.args dictionary.
from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def user():
    name = request.args.get("name", "frica01")
    return f"Hello, {<!-- -->name}!"

if __name__ == "__main__":
    app.run()

In the above example, we use the request.args.get() method to get the query parameter named name. If the parameter does not exist, it defaults to frica01 .

Read request data
  • When sending JSON data in a POST request, use request.data to obtain the original data of the request.
from flask import Flask, request

app = Flask(__name__)

@app.route("/json", methods=["POST"])
def json_data():
    data = request.data
    return f"Received JSON data: {<!-- -->data.decode()}"

if __name__ == "__main__":
    app.run()

Read form
  • Use the request.form dictionary to form data.
from flask import Flask, request

app = Flask(__name__)

@app.route("/example", methods=["POST"])
def example():
    # Get form data
    username = request.form.get("username")
    password = request.form.get("password")
    return f"Received POST request with username: {<!-- -->username}, password: {<!-- -->password}"

if __name__ == "__main__":
    app.run()

In the above example, we used request.method to check the HTTP method of the request and request.form to get the form data.

1.3 Request header

HTTP requests usually include some metadata called request headers. These headers contain additional information about the request, such as user agent, content type, etc. You can access request headers using request.headers.

When it comes to request headers, the following are some common request headers and their meanings, organized into a table as follows:

Request header Meaning
User-Agent The requested user agent identifier usually contains information about the client application and can be used to identify the client type.
Content-Type The media type of the request body specifies the type of data contained in the request, such as application/json Indicates that the request contains JSON data.
Authorization Contains credentials for authentication, typically used to access protected resources.
Cookie Contains cookie information passed by the client to the server for session management, etc.
Accept Specifies the response content type that the client can accept, and the server can return appropriate content based on this header.
Referer Contains the URL of the source page that directed the user to the current page.

Extend here,

The Flask code is as follows:

from flask import Flask, request

app = Flask(__name__)

@app.route("/book")
def profile():
    user_agent = request.headers.get("User-Agent")
    print(user_agent)
    return f"Hello, fric01!"

if __name__ == "__main__":
    app.run()

The request code is as follows:

import requests

resp = requests.get('http://127.0.0.1:5000/book')
print(resp)

The access effect is shown below:

From a security perspective, it can be judged that no data will be returned if user-agent contains a python string.

2. Response

When the Flask application has processed the request, it needs to generate a response and send it back to the client. The response typically contains an HTTP status code, response headers, and response body.

When using Flask to implement the back-end platform of the API interface, we only care about the HTTP status code and response body. We will introduce them below.

2.1 Response text

The response body is the actual data to be sent back to the client. It can be different types of data such as HTML, JSON, text, etc. You can include the data directly in the make_response function, or you can use the jsonify function to convert Python data to JSON format. (Note: make_response will not be introduced here)

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello, World!"

In this example, the string “Hello, World!” returned by the view function will be sent to the client as the body of the response.

2.2 Set status code

When it comes to HTTP status codes, here are some common ones and what they mean:

Status code Meaning
1xx Related information
2xx Operation successful
3xx Repeat Directed
4xx Client error
5xx Server error

These are some common HTTP status codes that servers typically use to indicate the outcome of a request so that the client can take appropriate action based on the status code.

When generating a response, the status code can be set via the second return value.

from flask import Flask

app = Flask(__name__)

@app.route("/not_found")
def not_found():
    return "Resource not found", 404

In this example, the string “Resource not found” returned by the view function will be sent to the client as the body of the response, and the status code will be set to 404.

2.3 Return value type

Flask supports multiple different types of view function return values, each type corresponding to different response content and HTTP status codes.

The following are some common Flask view function return value types and their characteristics:

Return value type Description
String Returns a string sent to the client as the body content of the HTTP response.
Tuple Returns a tuple containing the response body, HTTP status code, and response headers, which can be used to more precisely control various aspects of the response.
Response object Using the Response object provided by Flask, you can set the response properties more flexibly, including the response body, HTTP status codes, response headers, etc.
JSON data Use the jsonify function to convert the Python dictionary into JSON format and return the body content as the HTTP response, Suitable for building APIs.
Redirect response Returns a redirect response that redirects the client to another URL, which can be used to navigate within the application or redirect to External website.

When using Flask to implement the back-end platform of the API interface, commonly used return value types mainly include tuples and JSON data. Here is sample code on how to use these two return value types:

Return tuple
from flask import Flask

app = Flask(__name__)

@app.route("/tuple")
def return_tuple():
    response_body = "This is a tuple response"
    status_code = 200
    return response_body, status_code

if __name__ == '__main__':
    app.run()

In this example, we define a view function return_tuple() that returns a tuple containing the response body and HTTP status code.

However, in the return value of the request, usually only the response body can be accessed, and the status code will not be directly seen.

Return JSON data

Flask provides the jsonify function, which can convert a Python dictionary into JSON format and return it.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api/data")
def api_data():
    data = {<!-- -->"name": "John", "age": 30}
    return jsonify(data)

if __name__ == "__main__":
    app.run()

In the above example, we use the jsonify function to convert a dictionary to JSON format and return the body content as the HTTP response. This is very useful for building APIs.

The access effect is shown below:

Summary

This article provides an in-depth introduction to the key concepts of handling client requests and generating appropriate responses in a Flask application. The main content includes request processing methods (such as GET and POST), the use of the request object request, common request header information, response body generation (including JSON data), status code settings, and different types of return values.

By in-depth understanding of request and response processing in Flask, Xiaocai has the ability to process different types of request data and generate corresponding responses.