API Navigator Logo

Python Requests POST Example

Author: Newtum

This guide provides a comprehensive example of how to send HTTP POST requests using the Python Requests library. We'll explore sending form data and other types of payloads.

What is an HTTP POST Request?

An HTTP POST request is used to send data to a server to create a new resource. The data is included in the body of the request. It's commonly used for submitting forms, uploading files, or creating new entries in a database.

Sending Form Data

The most common use case for POST is sending URL-encoded form data. You can pass a dictionary to the `data` parameter in `requests.post()`.

import requests

url = 'https://httpbin.org/post'
payload = {'key1': 'value1', 'key2': 'value2'}

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

print('Status Code:', response.status_code)
print('Response Body:')
print(response.text)

Sending Raw Data

For non-form data, like a simple string, you can also use the `data` parameter. You might need to set the `Content-Type` header manually.

import requests
import json

url = 'https://httpbin.org/post'
# Note that this is just a string, not JSON
raw_data = 'This is some raw data'
headers = {'Content-Type': 'text/plain'}

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

print('Response JSON:')
# httpbin will reflect the data back
print(json.dumps(response.json(), indent=2))