How to make an HTTP GET request in Python?

Published on Aug. 22, 2023, 12:19 p.m.

To make an HTTP GET request in Python, you can use the requests library. Here is an example:

import requests

# Make a GET request
response = requests.get('https://www.example.com/api/data')

# Check the response status code
if response.status_code == 200:
    # Access the response data
    data = response.json()
    # Do something with the data
else:
    # Handle the error
    print(f"Error: {response.status_code} - {response.reason}")

In this example, we first imported the requests library. We then used the requests.get() function to make a GET request to an API endpoint. The resulting response object contains information about the response, including the response status code and any response data.

We checked the status code using the status_code attribute of the response object. If the status code indicates success (i.e. a 2xx status code), we accessed the response data using the json() method of the response object, and then performed some action with the data.

To make an HTTP GET request in Python with authentication and parameters, you can use the requests library. Here is an example:

import requests

# Set the authentication credentials
auth = ('username', 'password')

# Set the parameters for the request
params = {'param1': 'value1', 'param2': 'value2'}

# Make the GET request with authentication and parameters
response = requests.get('https://www.example.com/api/data', auth=auth, params=params)

# Check the response status code
if response.status_code == 200:
    # Access the response data
    data = response.json()
    # Do something with the data
else:
    # Handle the error
    print(f"Error: {response.status_code} - {response.reason}")

In this example, we set the authentication credentials using a tuple called auth. We also set the parameters for the GET request using a dictionary called params.

We then made the GET request using the requests.get() function with the auth and params parameters. The resulting response object contains information about the response, including the response status code and any response data.

We checked the status code using the status_code attribute of the response object. If the status code indicates success (i.e. a 2xx status code), we accessed the response data using the json() method of the response object, and then performed some action with the data.

If the status code indicates an error (i.e. a non-2xx status code), we handled the error by printing an error message.

Note that you need to have requests installed to use this functionality. You can install it using pip:

pip install requests

Also, ensure that you replace the example URL, username and password with actual values.

Tags: