Python - How To POST JSON Data With requests in Python

ID : 228

viewed : 245

Tags : PythonPython JSON

vote vote


Python provides us with the requests library that allows us to interact between client and server for posting JSON data.

In this tutorial, we will post JSON data with Python requests.

The function sends a POST request to the given URL. It returns a requests.Reponse type object.

For posting the JSON data, we will a URL object for targeting a URL string accepting the JSON data using the post() function.

We will then specify the post data. We will be passing the data through the message body as per the HTTP specification. We can specify the JSON data using the json parameter in the post() function. This parameter is available from requests module 2.4.2 version.

See the following example.

import requests  response ='', json={'id': 1, 'name': 'ram sharma'})  print(response.status_code) 



In our example, we also printed the status code of the requests.Reponse object. Status code 200 indicates that we were successful in sending the POST request with JSON data.

Below version 2.4.2 of the requests module, we can convert the data to JSON using the json.dumps() function and specify this data in the data parameter of the function.

For example,

import requests import json  response ='', data= json.dumps({'id': 1, 'name': 'ram sharma'}))  print(response.status_code) 



  • Related HOW TO?