python requests form data

Python Requests Form Data

When working with HTTP requests and RESTful APIs, sending form data is a common practice. In Python, the Requests library provides a simple way to send form data in a POST request.

Sending Form Data with Requests

To send form data using the Requests library, simply pass in a dictionary of key-value pairs representing the form data to the data parameter in the requests.post() method.


import requests

# Example form data
form_data = {
    "name": "John Doe",
    "email": "[email protected]",
    "message": "Hello world!"
}

response = requests.post("https://example.com/contact", data=form_data)

In the example above, we create a dictionary of form data and pass it to the data parameter in the requests.post() method. The resulting HTTP request will include the form data in the request body.

Sending File Uploads with Requests

In addition to sending regular form data, Requests also supports uploading files as part of a form submission.

To upload a file using Requests, pass in a dictionary that includes both the file and any additional form data to the files parameter in the requests.post() method.


import requests

# Example file upload
file_upload = {
    "file": ("example.png", open("example.png", "rb")),
    "name": "John Doe",
    "email": "[email protected]"
}

response = requests.post("https://example.com/upload", files=file_upload)

In the example above, we create a dictionary that includes both the file we want to upload and additional form data. We then pass this dictionary to the files parameter in the requests.post() method.

Conclusion

Sending form data is an important part of many HTTP requests. With the Requests library in Python, sending form data is a simple process that can be easily customized to fit specific use cases.