Python Post JSON using requests library (2024)

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:

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 enter application/json.
  • Click on the body section and click the raw radio button. enter your JSON data. Click the Send button.
Python Post JSON using requests library (2024)

FAQs

How do you post JSON data requests in Python? ›

post() method to send a POST request with JSON data, passing the URL and the data dictionary as arguments. The session will automatically encode the data as JSON and set the Content-Type header to application/json . The session. post() method returns a Response object, just like the regular requests.

How do you post JSON content in Python Requests? ›

How to post JSON data with Python Requests
  1. Prerequisites.
  2. Send a basic POST request.
  3. Send a POST request with JSON data.
  4. Send headers with POST request.
  5. Send a POST request using json parameter.
  6. Send FORM data with POST request.
  7. Upload files with POST request.
  8. Send POST request within a session.
Mar 13, 2024

How to pass JSON file in POST request in Python? ›

Step 2: Click on the Request tab and select POST from the dropdown menu. Step 3: Enter the URL of the API endpoint you want to test, in the Headers section, add any required headers. In the Body section, select JSON from the dropdown menu and enter the JSON data you want to send in the request body.

How to post JSON data in HTTP request? ›

2. Building a JSON POST Request With HttpURLConnection
  1. 2.1. Create a URL Object. ...
  2. 2.2. Open a Connection. ...
  3. 2.3. Set the Request Method. ...
  4. 2.4. Set the Request Content-Type Header Parameter. ...
  5. 2.5. Set Response Format Type. ...
  6. 2.6. Ensure the Connection Will Be Used to Send Content. ...
  7. 2.7. Create the Request Body. ...
  8. 2.8.
Jan 25, 2024

How to send JSON data to Python? ›

Step 1: Create a folder containing the data you want to send. Step 2: Use the jsonify() function provided by Flask to convert the data to JSON format and send it as a response. Step 3: Test the application. If the application is working correctly, you should see the JSON data in the web browser.

How to send large JSON in POST request? ›

Use WebSocket messages
  1. Split the input data into smaller pieces.
  2. Connect to the WebSocket server.
  3. Start sending messages with the smaller pieces till the end of the file.
  4. Close connection to the server.
Feb 4, 2022

How to pass JSON file as parameter in Python? ›

json.load() method

The json.load() accepts the file object, parses the JSON data, populates a Python dictionary with the data, and returns it back to you. Parameter: It takes the file object as a parameter. Return: It return a JSON Object.

How do you pass a JSON object as a parameter in Python? ›

If the json obj is {'first', '1st', 'second':'2nd', 'third':'3rd'} , the function would be called with f(first='1st', second='2nd', third='3rd') .

How to import JSON package in Python? ›

Use the import function to import the JSON module. The JSON module is mainly used to convert the python dictionary above into a JSON string that can be written into a file. While the JSON module will convert strings to Python datatypes, normally the JSON functions are used to read and write directly from JSON files.

How to send a POST request in Python? ›

To make a POST request in Python, you can use the requests. post() function in Python's requests library. This function allows you to send data to a server and receive a response. In this example, we import the requests library and use the requests.

What does request.JSON do in Python? ›

When you pass JSON data via json , Requests will serialize your data and add the correct Content-Type header for you. You can see from the response that the server received your request data and headers as you sent them.

Can we pass JSON data in GET request? ›

If you want to send JSON data via a get request you will have to URL encode the data and send it as a parameter.

How do you pass payload in a POST request in Python? ›

POST requests pass their data through the message body, The Payload will be set to the data parameter. data parameter takes a dictionary, a list of tuples, bytes, or a file-like object. You'll want to adapt the data you send in the body of your request to the specified URL.

How to post JSON data in rest API? ›

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You must also specify the data type using the Content-Type: application/json request header.

How to pass data in HTTP POST request? ›

In a POST request, you pass data in the request body. The type of data in the body is indicated by the Content-Type header of the request. A POST request is often sent using an HTML form or a fetch request.

How to pass JSON as argument in Python? ›

JSON String to Python Dictionary

To do this, we will use the loads() function of the json module, passing the string as the argument. json. loads(data_JSON) creates a new dictionary with the key-value pairs of the JSON string and it returns this new dictionary.

How to post JSON data in Django? ›

Conclusion
  1. Set up a Django project and create a simple API app.
  2. Define a model and a serializer for the JSON data.
  3. Create a view and a URL for the API endpoint.
  4. Test the API using Apidog, a web-based tool that lets you test and debug APIs with ease.
  5. Analyze and manipulate the JSON data using Apidog's features and tools.
Jan 25, 2024

How to load JSON in Python? ›

The json. load() function accepts a file object as an argument and returns deserialized JSON data in the form of Python objects such as dictionaries, lists, strings, numbers, booleans, and null values. To read JSON data from a file, you need to open the file in read mode, extract the data using the json.

Top Articles
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 6185

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.