Introduction
As builders, we regularly work with APIs or internet companies, and one widespread process is sending information in JSON (JavaScript Object Notation) format to a server. Luckily, Python offers us with a robust requests
library, which makes HTTP requests a breeze, together with sending JSON information.
On this article, we’ll undergo methods to use the
requests
library to ship a POST request with JSON information in Python. We’ll cowl all the pieces from the fundamentals of sending a POST request to dealing with the response acquired from the server, and even dealing with errors that will happen alongside the best way.
Sending JSON Knowledge by way of POST Request
Now, we will bounce into the meat of this text – making a POST request with the requests
library in Python. Let’s begin with a easy instance that sends JSON information within the physique of the request. We first must import the requests
library, specify the URL that we wish to ship the request to and outline the JSON information within the information
variable. We additionally specify the Content material-type
header to point that we’re sending JSON information:
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
headers = {'Content material-type': 'utility/json'}
information = '{"title": "foo", "physique": "bar", "userId": 1}'
Then, we make the POST request utilizing the requests.publish()
technique, passing within the URL, headers, and information:
response = requests.publish(url, headers=headers, information=information)
Lastly, we print the standing code and response textual content to confirm that the request was profitable and that we acquired the anticipated response:
print(response.status_code)
print(response.textual content)
Notice: We’ll take a better have a look at the responses we will get from a server within the following sections.
Now that we have seen a fundamental instance, let’s take a better have a look at the parameters we handed to the requests.publish()
technique:
url
: The URL that we wish to ship the request to.headers
: A dictionary of headers to incorporate within the request. On this case, we specify theContent material-type
header to point that we’re sending JSON information.information
: The info to ship within the physique of the request. This may be both a string or a dictionary. In our instance, we handed a JSON string.
It is price noting that there is one other solution to ship JSON information in a POST request, utilizing the json
parameter as an alternative of information
:
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
information = {'title': 'foo', 'physique': 'bar', 'userId': 1}
response = requests.publish(url, json=information)
print(response.status_code)
print(response.textual content)
The json
parameter robotically units the Content material-type
header to utility/json
and encodes the info as JSON within the request physique.
Notice: Each strategies work equally effectively, so select the one that matches your use case greatest.
And that is just about it for making a POST request with JSON information utilizing the requests
library in Python. Now, we will check out methods to deal with the response acquired from the server.
Dealing with the Response
Now that we have realized methods to make a POST request with JSON information, it is time to deal with the response from the server. The response can provide us necessary details about the success of the request and any information that was returned.
Let’s broaden the instance from the earlier part to make it deal with the response appropriately. We’ll first make the POST request utilizing the identical code as within the earlier part. Then, we verify the standing code of the response utilizing the response.status_code
attribute:
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
headers = {'Content material-type': 'utility/json'}
information = '{"title": "foo", "physique": "bar", "userId": 1}'
response = requests.publish(url, headers=headers, information=information)
if response.status_code == requests.codes.okay:
print('Request was profitable')
print(response.json())
else:
print('Request failed with standing code:', response.status_code)
If the standing code is requests.codes.okay
, which is equal to 200
, we print successful message and the JSON information returned by the server utilizing the response.json()
technique. If the standing code is something apart from 200
, we print an error message and the standing code.
Notice: The response.json()
technique returns the JSON information from the response as a Python dictionary. This makes it simple to work with the info in your Python code.
Dealing with the response also can embrace checking for particular HTTP standing codes or headers, parsing the response textual content, or working with the response content material. The
requests
library offers quite a lot of strategies and attributes to make it simple to deal with the response from a request.
Dealing with Errors
When working with HTTP requests, it is necessary to deal with errors that will happen throughout the course of. On this part, we’ll cowl methods to deal with widespread errors you might face when making POST requests we have been discussing up to now. Let’s begin with a easy instance that demonstrates methods to verify for errors within the response:
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
headers = {'Content material-type': 'utility/json'}
information = '{"title": "foo", "physique": "bar", "userId": 1}'
response = requests.publish(url, headers=headers, information=information)
if response.status_code != requests.codes.okay:
increase Exception('Request failed with standing code:', response.status_code)
We made the POST request utilizing the identical code as within the earlier sections. Then, we checked the standing code of the response utilizing the response.status_code
attribute.
If the standing code will not be 200
, we increase an exception with an error message and the standing code. This ensures that this system stops executing if an error happens, relatively than persevering with with doubtlessly invalid information.
Different widespread errors that will happen when making a POST request with JSON information embrace:
ConnectionError
: raised when a connection to the server can’t be established.Timeout
: raised when the request occasions out.JSONDecodeError
: raised when the response can’t be decoded as JSON.
Try our hands-on, sensible information to studying Git, with best-practices, industry-accepted requirements, and included cheat sheet. Cease Googling Git instructions and truly be taught it!
Let’s check out an instance that demonstrates methods to deal with all of those errors:
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
headers = {'Content material-type': 'utility/json'}
information = '{"title": "foo", "physique": "bar", "userId": 1}'
strive:
response = requests.publish(url, headers=headers, information=information, timeout=5)
response.raise_for_status()
json_data = response.json()
besides requests.exceptions.ConnectionError as ce:
print('Connection error:', ce)
besides requests.exceptions.Timeout as te:
print('Request timed out:', te)
besides requests.exceptions.HTTPError as he:
print('HTTP error occurred:', he)
besides ValueError as ve:
print('JSON decoding error:', ve)
else:
print('Request was profitable')
print(json_data)
Notice: Right here, we wrapped the POST request in a try-except
block with the intention to catch various kinds of exceptions that will happen.
The response.raise_for_status()
technique is used to boost an exception if the standing code signifies an error (e.g. 404
). If the request is profitable, we print successful message and the JSON information returned by the server utilizing the response.json()
technique.
By dealing with errors that will happen when making a POST request with JSON information, we will write sturdy and dependable code that handles varied situations.
Conclusion
On this article, we took a have a look at methods to use the requests
library to make a POST request with JSON information in Python. We lined the fundamentals of constructing a POST request, dealing with the response acquired from the server, and dealing with errors that will happen throughout the course of.
We noticed that the requests
library offers a easy and intuitive API for making HTTP requests, and that sending JSON information in a POST request is easy utilizing both the information
or json
parameter. We additionally realized methods to deal with the response from the server, together with checking the standing code and extracting the JSON information returned.
Lastly, we lined error dealing with and demonstrated methods to deal with widespread errors that will happen when making a POST request with JSON information.