SoFunction
Updated on 2025-03-10

Python method to obtain request response body

In Python, we can use multiple libraries to send HTTP requests and get response body. Among them, one of the most commonly used libraries isrequests. This library provides a simple and easy-to-use interface to send HTTP requests and can easily obtain the content of the response body.

Below is a detailed example showing how to userequestsThe library sends HTTP GET requests and gets the response body. This sample code can be run directly and has certain reference value and practical significance.

1. Get the request response body

1. Install the requests library

First, make sure we have installedrequestsLibrary. If you have not installed it, you can use the following command to install it:

pip install requests

2. Sample code

Here is a complete Python script that shows how to send HTTP GET requests and get the response body:

import requests
def fetch_url(url):
    try:
        # Send HTTP GET request        response = (url)
        # Check whether the request is successful (status code is 200)        if response.status_code == 200:
            # Get the response body content (text format)            response_body = 
            print("The request was successful, the response body content is as follows:")
            print(response_body)
        else:
            # If the request fails, output status code and error message            print(f"Request failed,Status code:{response.status_code}")
            print(f"error message:{}")
    except  as e:
        # Capture all request exceptions and output error messages        print(f"An exception occurred in the request:{e}")
if __name__ == "__main__":
    # Replace with the URL we want to request    url = "/posts/1"
    fetch_url(url)

3. Code explanation

(1)Import the requests library

import requests

(2)Define functionsfetch_url

  • This function accepts a URL as an argument.
  • use(url)Send an HTTP GET request.
  • Check whether the status code of the response is 200 (indicates that the request is successful).
  • If the request is successful, get the response body content and print it.
  • If the request fails, output status code and error message.
  • Catch and handle all request exceptions.

(3)Main program

  • Set up a sample URL (using the example API of JSONPlaceholder here).
  • Callfetch_urlFunction sends a request.

4. Run the code

Save the above code to a Python file (e.g.fetch_url.py), and then run on the command line:

python fetch_url.py

We should see an output similar to the following (the specific content depends on the requested URL):

Request succeeded,The response body content is as follows:
{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quasi\net nostrum exercitationem laborum\n",
    "postedDate": "2023-10-04T09:46:24.282Z"
}

5. Things to note

(1)URL: In actual application, replace the sample URL with the URL we need to request.

(2)Error handling: The sample code contains basic error handling, but in production we may need more detailed error handling and logging.

(3)Security: For requests involving sensitive information (such as API keys), make sure to use the HTTPS protocol and properly keep the sensitive information.

This example shows how to userequestsThe library sends HTTP requests and obtains the response body, which has practical reference value for handling HTTP requests and responses.

2. How to create a website in Python

Creating a website in Python often involves the use of web frameworks that provide a suite of tools and libraries for building web applications and websites. A popular Python web framework is Flask, which is lightweight and easy to use, but Django is also a powerful and widely used option. Below I will briefly introduce how to create a simple website using Flask.

1. Install Flask

First, we need to install Flask. We can use pip (Python's package manager) to install it:

pip install Flask

2. Create a simple Flask app

(1) Create a new Python file, for example

(2)In the file, write the following code to create a simple Flask application:

from flask import Flask, render_template
app = Flask(__name__)
#Route and view functions@('/')
def home():
    return render_template('')
if __name__ == '__main__':
    (debug=True)

(3) Create a name calledtemplatesand create a folder namedfile. This folder and file will be used to store our HTML templates.

(4)In the file, write some simple HTML code:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>My Flask Website</title>
  </head>
  <body>
    <h1>Welcome to My Flask Website!</h1>
  </body>
</html>

(4) Now, we can run our Flask application. On the command line, navigate to includeThe directory of the file and run:

python 

(5) Open our web browser and accesshttp://127.0.0.1:5000/. We should see the homepage of the simple website we created with "Welcome to My Flask Website!".

3. Explain the code

  • from flask import Flask, render_template: Import the Flask class and render_template function from the Flask library.
  • app = Flask(__name__): Create a Flask application instance.
  • @('/'): Define a route when the user accesses the root URL (/) The following view function is called.
  • def home():: Define a view function to handle requests for root URLs.
  • return render_template(''): RenderingTemplate and return it to the client as an HTTP response.
  • if __name__ == '__main__':: Check whether the script is run directly (rather than importing as a module).
  • (debug=True): Run the Flask application and enable debug mode (which should be disabled in production).

4. Deploy the website

To deploy our Flask website on the internet, we need to deploy it to a web server, like Gunicorn or uWSGI, and use a reverse proxy like Nginx to handle static files and forward requests. In addition, we may also need to configure a database (such as SQLite, PostgreSQL, or MySQL) to store the website's data.

For deployment in production environments, it is recommended to use containerization technologies like Docker to encapsulate our applications and their dependencies to ensure consistency and portability in different environments. We can also use platforms like Heroku, AWS Elastic Beanstalk, or Google Cloud Run to simplify the deployment process.

This is the end of this article about how to obtain the request response body in Python. For more related Python request response body content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!