Python Requests Body JSON
If you are working with APIs or web services in Python, there may come a time when you need to send data in JSON format. This is where the Python Requests library comes in handy. With Requests, you can easily send HTTP requests and handle responses in Python.
Sending a JSON Request Body
To send a JSON request body using Requests, you can use the json
parameter of the requests.post()
method. Here's an example:
import requests
url = 'https://example.com/api/create_user'
data = {
'username': 'john_doe',
'password': 'my_super_secret_password',
'email': '[email protected]'
}
response = requests.post(url, json=data)
print(response.status_code)
print(response.json())
In this example, we're sending a POST request to https://example.com/api/create_user
with a JSON request body containing the user's username, password, and email address.
The json=data
parameter tells Requests to automatically encode the data as JSON and set the Content-Type header to application/json
.
Sending a JSON Request Body with Custom Headers
If you need to send additional headers along with your request, you can pass them as a dictionary to the headers
parameter of the requests.post()
method:
import requests
url = 'https://example.com/api/create_user'
data = {
'username': 'john_doe',
'password': 'my_super_secret_password',
'email': '[email protected]'
}
headers = {
'Authorization': 'Bearer my_token',
'X-Custom-Header': 'my_value'
}
response = requests.post(url, json=data, headers=headers)
print(response.status_code)
print(response.json())
In this example, we're sending the same JSON request body as before, but we're also including an Authorization
header with a bearer token and a custom header called X-Custom-Header
.
Conclusion
Sending a JSON request body with Python Requests is easy and convenient. Whether you're working with APIs or web services, Requests makes it simple to send HTTP requests and handle responses in Python.