make a http request with a custom body as json in python

Here's an example code snippet for making a HTTP POST request with a JSON payload in Python:

main.py
import json
import requests

url = 'http://example.com/api'
payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post(url, data=json.dumps(payload))

# Alternatively, you can pass the payload as a python object, and let
# requests convert it to JSON
# r = requests.post(url, json=payload)

print(r.status_code)
print(r.json())
335 chars
15 lines

Explanation:

  • We import the json and requests libraries at the start of the script
  • We define the target url and the payload dictionary
  • We make a HTTP POST request to the URL, passing the payload dictionary as the data parameter, after converting it to a JSON string using the json.dumps() method
  • We can alternatively pass the payload as a Python object using the json parameter, and requests will automatically serialize it to JSON as needed
  • We then print the status code of the response and the JSON content of the response body using the r.status_code and r.json() methods, respectively.

related categories

gistlibby LogSnag