Send POST Requests with Python and Requests Module: A Step-by-Step Guide
When working with web applications or APIs, you may need to send HTTP requests to submit form data or retrieve data from a remote server. Python provides several libraries for working with HTTP requests, but one of the most popular and user-friendly is the requests
module.
In this tutorial, we'll walk through how to send a POST request with Python and the requests
module, using an example of submitting form data to a remote server.
Setting up the Example
For this tutorial, we'll use the following example:
- We have an encoded form submission string that we want to send as a POST request to a URL
- The URL we'll use is "http://requestfrom.me"
- We'll assume that the form submission string is already encoded in the proper format for submitting form data, and we just need to send it as a POST request.
Sending the POST Request
To send a POST request with Python and the requests
module, we'll need to:
- Import the
requests
module - Define the URL and any necessary headers for the request
- Define the data to be sent in the request body
- Send the POST request using the
requests.post()
method
Here's what the code looks like:
import requests
from urllib.parse import parse_qs
url = 'http://mazhar.me'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data_str = 'hppshac%5B%5D=map&hppshac%5B%5D=POV&hppshac%5B%5D=act&hppshac%5B%5D=1'
data_dict = parse_qs(data_str)
response = requests.post(url, headers=headers, data=data_dict)
print(response.text)