Using Python's requests library to make HTTP requests on Linux is a very convenient and efficient way. The requests library is a third-party library used to send HTTP requests and get responses. Below is a simple example that demonstrates how to use the requests library to send a GET request and get the response.
First, you need to install the requests library. You can install it using pip command:
bashreplacement
pip install requests |
After the installation is complete, you can import the requests library in a Python script and send HTTP requests. Here is a sample code:
pythonsynthesis
import requests |
|
#Send GET request |
|
response = requests.get('https://api.example.com/data') |
|
# Output response status code and content |
|
print(response.status_code) |
|
print(response.text) |
In the above code, we send a GET request using the requests.get() function and pass the requested URL as a parameter . You can replace URL with the actual URL you want to send the request to.
After sending the request, you can useresponse.status_code to get the response status code, useresponse .textGet the content of the response. If you want to process responses in JSON format, you can use response.json() to parse the response content into a JSON object. For example:
pythonsynthesis
import requests |
|
#Send GET request |
|
response = requests.get('https://api.example.com/data') |
|
# Parse JSON response |
|
data = response.json() |
|
# Output Data |
|
print(data) |
The above code parses the JSON response content into a Python object and prints it out.
In addition to GET requests, the requests library also supports other HTTP request methods such as POST, PUT, and DELETE. For example, here is an example of sending a request using the POST method:
pythonsynthesis
import requests |
|
#Send POST request |
|
response = requests.post('https://api.example.com/data', data={ 'name': 'John', 'age': 30}) |
|
# Output response status code and content |
|
print(response.status_code) |
|
print(response.text) |
The above code uses therequests.post() function to send a POST request and takes the requested URL and the data to be sent as parameters transfer. You can modify the data to be sent as needed.