Python Requests is a powerful HTTP library that makes it easy to send GET, POST, and other requests. This guide will show you how to make POST requests using the Requests library.

Make a Basic POST Request

Here's a simple example to make a POST request:

import requests

url = 'https://example.com/api'

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=payload)

print(response.text)

If the API accepts JSON data, use the json parameter:

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

You can also pass a list of tuples to the data parameter. This is especially useful when multiple elements in the form use the same key:

payload = (('key1', 'value1'), ('key1', 'value2'))
response = requests.post(url, data=payload)

POST file

If you want to upload a file via POST request, you can use the following code example:

files = {'file': open('info.xls', 'rb')}
response = requests.post(url,files=files)

You can also set the file name, file type and request headers:

files = {'file': ('info.xls', open('info.xls', 'rb'),
                  'application/vnd.ms-excel',
                  {'Expires': '0'}
                  )
         }
response = requests.post(url,files=files)

You can also POST a string as a file:

files = {'file': ('info.txt', 'hello world\n')}
response = requests.post(url,files=files)