Python Requests Post Call
As a developer, you may need to interact with APIs to send or receive data. In Python, the requests library is a popular choice for making HTTP requests. In this article, we’ll be discussing how to make a POST call using the Python requests library.
The Basics
When making a POST call, you need to specify the URL endpoint and the payload (data) to send. Here’s a basic example:
import requests
url = 'https://example.com/api'
data = {'key': 'value'}
response = requests.post(url, data=data)
print(response.text)
In this code block, we import the requests module and set the URL endpoint and payload data. We then make the POST request using the requests.post() method and store the response in a variable. Finally, we print the response text.
The Payload
The payload of a POST request can be in different formats, such as JSON or form-encoded data. Let’s take a look at how to send JSON data:
import requests
import json
url = 'https://example.com/api'
headers = {'Content-type': 'application/json'}
data = {'key': 'value'}
response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.text)
In this example, we first import the json module. We then set the headers to indicate that the payload is in JSON format. We convert the data dictionary to a JSON string using the json.dumps() method. Finally, we make the POST request with the headers and JSON data.
The Response
When making a POST request, the server may respond with data. You can access the response data using the response.text attribute. However, the response data might not always be in text format. The requests library provides several methods to access the response data in different formats, such as json() or content(). Here’s an example:
import requests
url = 'https://example.com/api'
data = {'key': 'value'}
response = requests.post(url, data=data)
if response.status_code == 200:
json_data = response.json()
print(json_data)
else:
print('Error:', response.status_code)
In this example, we make the POST request and check the response status code. If the response status code is 200 (OK), we can access the JSON data using the response.json() method. Otherwise, we print an error message with the response status code.
Conclusion
Making a POST call is essential when working with APIs. In Python, the requests library provides an easy-to-use interface for sending HTTP requests. In this article, we covered the basics of making a POST call using requests and explored some advanced techniques like sending JSON data and accessing the response data.