How to Send JSON Data in Request Python: Simple Guide
To send JSON data in a request in Python, use the
requests library and pass your data as a dictionary to the json parameter in requests.post() or requests.put(). This automatically converts the dictionary to JSON and sets the correct headers.Syntax
Use the requests.post() or requests.put() function with the json parameter to send JSON data. The json parameter takes a Python dictionary, converts it to JSON, and sets the Content-Type header to application/json.
Example syntax:
requests.post(url, json=data_dict)requests.put(url, json=data_dict)
python
import requests url = 'https://example.com/api' data = {'key': 'value'} response = requests.post(url, json=data)
Example
This example shows how to send JSON data in a POST request to a test API and print the response status and JSON content.
python
import requests url = 'https://httpbin.org/post' data = {'name': 'Alice', 'age': 30} response = requests.post(url, json=data) print('Status code:', response.status_code) print('Response JSON:', response.json())
Output
Status code: 200
Response JSON: {'args': {}, 'data': '{"name": "Alice", "age": 30}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Content-Length': '27', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.31.0', 'X-Amzn-Trace-Id': 'Root=1-650d7d7f-4a1b2c3d5e6f7a8b9c0d1e2f'}, 'json': {'age': 30, 'name': 'Alice'}, 'origin': 'YOUR_IP', 'url': 'https://httpbin.org/post'}
Common Pitfalls
Common mistakes when sending JSON data include:
- Using
data=instead ofjson=which sends data as form-encoded, not JSON. - Not setting the
Content-Typeheader toapplication/jsonmanually when usingdata=. - Passing a JSON string instead of a Python dictionary to
json=.
Always pass a dictionary to json= to let requests handle conversion and headers.
python
import requests url = 'https://httpbin.org/post' json_string = '{"name": "Bob"}' # Wrong way: passing JSON string to json= parameter response_wrong = requests.post(url, json=json_string) # Right way: passing dictionary to json= parameter response_right = requests.post(url, json={'name': 'Bob'}) print('Wrong status:', response_wrong.status_code) print('Right status:', response_right.status_code)
Output
Wrong status: 200
Right status: 200
Quick Reference
Tips for sending JSON data in Python requests:
- Use
json=parameter to send JSON easily. - Pass a Python dictionary, not a JSON string.
requestssetsContent-Type: application/jsonautomatically.- Use
response.json()to parse JSON response.
Key Takeaways
Use the requests library's json= parameter to send JSON data easily.
Always pass a Python dictionary to json=, not a JSON string.
requests automatically sets the Content-Type header to application/json.
Use response.json() to read JSON responses from the server.
Avoid using data= for JSON as it sends form-encoded data by default.