Python Requests POST Nested Dictionary
If you are working with Python, requests and nested dictionaries, you might come across a situation where you need to send a POST request with a nested dictionary in its payload. In this case, the nested dictionary needs to be converted to JSON format before sending it as payload. Here are a few ways to achieve this:
Method 1: Using the json module
import requests
import json
url = 'https://example.com/api/endpoint'
headers = {'Content-Type': 'application/json'}
data = {'name': 'John', 'age': 25, 'address': {'city': 'New York', 'state': 'NY'}}
response = requests.post(url, headers=headers, data=json.dumps(data))
In the above code snippet, we first import the requests
and json
modules. Then we define the url
, headers
, and data
variables. The data
variable contains a nested dictionary. Before sending the POST request, we convert the data
dictionary to JSON format using the json.dumps()
method. Finally, we make the POST request using the requests.post()
method.
Method 2: Using the data parameter
import requests
url = 'https://example.com/api/endpoint'
headers = {'Content-Type': 'application/json'}
data = {'name': 'John', 'age': 25, 'address': {'city': 'New York', 'state': 'NY'}}
response = requests.post(url, headers=headers, json=data)
In this method, we use the json
parameter of the requests.post()
method. This parameter automatically converts the dictionary to JSON format. This method is simpler and cleaner than the previous method.
Method 3: Using the data parameter with custom encoder
import requests
import json
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
url = 'https://example.com/api/endpoint'
headers = {'Content-Type': 'application/json'}
data = {'name': 'John', 'age': 25, 'interests': {'hobbies': {'sport': 'football', 'music': 'guitar'}, 'movies': ['Star Wars', 'The Matrix']}}
json_data = json.dumps(data, cls=CustomEncoder)
response = requests.post(url, headers=headers, data=json_data)
In this method, we define a custom JSON encoder class that converts the sets to lists. We then use this custom encoder to convert the dictionary to JSON format. Finally, we make the POST request using the requests.post()
method.
These are a few ways to send a POST request with a nested dictionary using Python requests. Choose the method that suits your requirements and coding style.