python requests post json file

Python Requests Post Json File

If you're working with APIs, you're likely to need to send and receive data in JSON format. Fortunately, Python's requests library makes it easy to send JSON data with POST requests.

Using Python Requests library to Post JSON File

To send JSON data with a POST request, you'll need to use the requests library's post() method. The post() method takes two arguments - the URL to which to send the POST request, and the data to send. The data should be formatted as a Python dictionary or list, and the requests library will automatically convert it to JSON format.


import requests

url = "https://example.com/api"
data = {
    "name": "John Smith",
    "email": "[email protected]",
    "phone": "(123) 456-7890"
}

response = requests.post(url, json=data)

print(response.status_code)
  

In this example, we're sending a POST request to https://example.com/api with the JSON data {"name": "John Smith", "email": "[email protected]", "phone": "(123) 456-7890"}. The requests library automatically converts the data dictionary to JSON format using the json parameter.

Alternative way of Posting JSON File

Alternatively, you can manually convert the dictionary to JSON format using the json library and then pass the resulting string as the data argument:


import requests
import json

url = "https://example.com/api"
data = {
    "name": "John Smith",
    "email": "[email protected]",
    "phone": "(123) 456-7890"
}

json_data = json.dumps(data)
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.post(url, data=json_data, headers=headers)

print(response.status_code)
  

In this example, we're manually converting the data dictionary to a JSON-formatted string using the json module's dumps() method, and then passing it as the data argument to the requests.post() method. We're also specifying the Content-type header as application/json to indicate that the data is in JSON format.