In this article, I will let you know how to post a JSON from a client to a server using a requests
library. Also, if you are facing a “400 bad request error” while posting JSON to the server, this article will try to solve that.
Further Reading:
- SolvePython JSON Exerciseto practice Python JSON skills
Steps to Build a JSON POST request
Create a URL object: Let’s create a URL object. We need a target URI string that accepts the JSON data via HTTP POST method. In this example, I am using httpbin.org service to Post JSON data. httpbin.org is a web service that allows us to test the HTTP request. You can use it to test and inspect your POST request. httpbin.org responds with data about your request.
So my URL is: “https://httpbin.org/post“
Set the Request Method: As the name suggests, we need to use a post method of a request module.
requests.post('https://httpbin.org/post')
Code language: Python (python)
Specify the POST data: As per the HTTP specification for a POST request, we pass data through the message body. Using requests, you’ll pass the payload to the corresponding function’s data parameter. Data can be anything including JSON, dictionary, a list of tuples, bytes, or a file-like object. In this example, I am sending the following JSON data.
{'id': 1, 'name': 'Jessa Duggar'}
If you have data in the form of a dictionary or any Python object, you can convert it into JSON like this.
import jsonsampleDict = { "id": 1, "name":"Jessa"}jsonData = json.dumps(sampleDict)
Code language: Python (python)
Use The json
parameter: The requests module provides a json
parameter that we can use to specify JSON data in the POST method. i.e., To send JSON data, we can also use the json
parameter of the requests.post()
method.
For example:
requests.post('https://httpbin.org/post', json={'id': 1, 'name': 'Jessa'})
Code language: Python (python)
Why set it to json? Because it will help the request module to serialize your data into the JSON format. Now, Let’s see the example.
Approach 1: Using json
parameter
import requestsresponse = requests.post('https://httpbin.org/post', json={'id': 1, 'name': 'Jessa'})print("Status code: ", response.status_code)print("Printing Entire Post Request")print(response.json())
Code language: Python (python)
Output:
Status code: 200Printing Entire Post Request{'args': {}, 'data': '{"id": 1, "name": "Jessa"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '26', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'json': {'id': 1, 'name': 'Jessa'}, 'origin': 'xxx.xx.xx.xx, xxx.xx.xx.xx', 'url': 'https://httpbin.org/post'}
Note: This service returns your entire request as a response so it will help you to know details about your request.
Approach 2: By setting header information
Alternatively, we can set the request’s content-type.In this example, we are passing JSON, so the request’s content type is application/json
.
By specifying correct request headers so that the requests module can serialize your data into the correct Content-Type header format. In this can we don’t need to use the json
parameter. This is useful for an older version. Let’s see the example now.
import requestsnewHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}response = requests.post('https://httpbin.org/post', data={'id': 1, 'name': 'Jessa'}, headers=newHeaders)print("Status code: ", response.status_code)response_Json = response.json()print("Printing Post JSON data")print(response_Json['data'])print("Content-Type is ", response_Json['headers']['Content-Type'])
Code language: Python (python)
Output:
Status code: 200Printing Post JSON dataid=1&name=Jessaapplication/json
Test Your JSON POST request using postman before executing
It is always a best practice to test your request along with its message body using postman to verify JSON data, and a request is in the required format. Let’s see how to test POST request using postman.
Add Postman extension or install a native postman app. Let’s see the steps now.
- Select POST request and enter your service POST operation URL.
- Click on Headers. In the key column enter
Content-Type
and in the Value column enterapplication/json
. - Click on the body section and click the raw radio button. enter your JSON data. Click the Send button.