python requests post with json body

Python Requests Post with JSON Body

If you want to make a POST request to an API that requires a JSON request body, you can use the Python Requests library. Here's how:

Step 1: Import the requests library

import requests

Step 2: Define the URL and JSON data


url = 'https://example.com/api'
data = {'name': 'John', 'age': 30}

In this example, the URL is 'https://example.com/api' and the JSON data is a dictionary with two keys: 'name' and 'age'.

Step 3: Send the POST request


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

The json parameter in the requests.post() method sets the request body to be sent as JSON.

Step 4: Check the response


print(response.status_code)
print(response.json())

The status_code attribute of the response object will give you the HTTP status code returned by the API. The json() method of the response object will parse the JSON response body and return it as a Python dictionary.

Alternative Method: Using the json library

If you prefer to use the built-in Python json library to encode the JSON data, you can do it like this:


import json

url = 'https://example.com/api'
data = {'name': 'John', 'age': 30}
json_data = json.dumps(data)

response = requests.post(url, data=json_data, headers={'Content-Type': 'application/json'})

print(response.status_code)
print(response.json())

In this alternative method, we first use the json.dumps() method to encode the JSON data as a string. Then, we set the data parameter in the requests.post() method to the encoded JSON string. We also set the Content-Type header to application/json.