python requests post json string

Python Requests post JSON string

If you want to send data to a server using the POST method with Python Requests, you can use the json parameter to provide a JSON-encoded string as the message body. Here's how you can do it:


  import requests
  import json
  
  data = {'name': 'John', 'age': 30}
  headers = {'Content-type': 'application/json'}
  url = 'https://example.com/api/'
  
  response = requests.post(url, data=json.dumps(data), headers=headers)
  

In the code above, we first create a dictionary containing the data we want to send to the server. We then set the Content-type header to application/json, which tells the server that we are sending JSON data. We then use the json.dumps() method to convert our data dictionary into a JSON-encoded string, which we pass as the data parameter to the requests.post() method.

If you have multiple ways to send the JSON data using requests.post() then here are some of the ways:

Method 1: Using json parameter


  import requests
  
  url = 'https://example.com/api/'
  data = {'name': 'John', 'age': 30}
  
  response = requests.post(url, json=data)
  

In this method, we can directly pass the data dictionary to the json parameter of the requests.post() method. Requests will automatically encode the data as JSON and set the Content-type header to application/json.

Method 2: Using data parameter


  import requests
  import json
  
  url = 'https://example.com/api/'
  data = {'name': 'John', 'age': 30}
  
  response = requests.post(url, data=json.dumps(data))
  

In this method, we pass the JSON-encoded string to the data parameter of the requests.post() method. We also need to set the Content-type header to application/json. This method is useful if you need to set other headers besides Content-type.