make a http request with a custom body as json and return a json response in python

To make an HTTP request with a custom body as JSON and return a JSON response in Python, you can use the requests library. Here's an example:

main.py
import requests
import json

url = 'https://example.com/api/endpoint'
headers = {
    'Content-Type': 'application/json'
}
payload = {
    'key1': 'value1',
    'key2': 'value2'
}
# make HTTP POST request with JSON payload and headers
response = requests.post(url, data=json.dumps(payload), headers=headers)
# try decoding JSON response
try:
    json_response = response.json()
    print(json_response)
except ValueError as e:
    print("Error decoding JSON response:", e)
473 chars
20 lines

In this example, we create a dictionary object payload with the data we want to send in the request body. We then convert this dictionary to a JSON string using json.dumps, and pass it as the data parameter to the requests.post method. We also set the Content-Type header to application/json to indicate to the server that we are sending JSON data.

After making the request, we can try to decode the JSON response using the response.json() method. If decoding fails, we catch the ValueError exception and print an error message.

gistlibby LogSnag