How to Create a Post Request in Python?

Estimated read time 1 min read

You can create a POST request in Python using the requests library. Here’s an example code snippet:

import requests

url = 'https://example.com/api'
data = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-type': 'application/json'}

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

print(response.text)

In this example, we’re sending a POST request to the https://example.com/api URL with a JSON payload. The data variable contains the JSON data we want to send. The headers variable contains the headers we want to send along with the request.

We use the requests.post() function to send the request, passing in the URL, data, and headers as arguments. The response object returned by the function contains the server’s response to the request.

Finally, we print the response using the response.text property. You can also use other properties of the response object to access the response status code, headers, or content.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply