python requests post body x-www-form-urlencoded

Python Requests Post Body x-www-form-urlencoded

When making HTTP requests in Python, the requests library is a commonly-used tool. One common use case is to send POST requests with an x-www-form-urlencoded body. This format is used when sending data in the body of the request as key-value pairs separated by an equals sign.

Using Requests Library with x-www-form-urlencoded Body

To send a POST request with an x-www-form-urlencoded body using the requests library, you can use the data parameter for the request. The data should be provided in the form of a dictionary with keys and values for each field you want to send.


import requests

url = 'https://example.com/api'
data = {
    'name': 'John Doe',
    'email': '[email protected]'
}
response = requests.post(url, data=data)

In the example above, we're sending a POST request to https://example.com/api with two fields "name" and "email" and their corresponding values "John Doe" and "[email protected]".

Using urllib.parse to Encode Data

If you don't have a dictionary of key-value pairs and instead have a string of data you want to send, you can use the urllib.parse library to encode it in the x-www-form-urlencoded format.


import requests
from urllib.parse import urlencode

url = 'https://example.com/api'
data = 'name=John+Doe&email=johndoe%40example.com'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(url, data=data, headers=headers)

The example above shows how to use urlencode to encode the data before sending a POST request. We're also including the Content-Type header to specify that we're sending an x-www-form-urlencoded body.

Conclusion

Sending POST requests with an x-www-form-urlencoded body is a common task in web development. Using the requests library and the data parameter, it's easy to send key-value pairs in the body of a request. If you have a string of data, you can use the urllib.parse library to encode it before sending the request.