python requests post file and data

Python Requests Post File and Data

When working with web applications, it's quite common to send data along with a file as a multipart/form-data request. In Python, the requests library provides an easy-to-use interface for sending HTTP/1.1 requests. In this tutorial, we'll learn how to use the requests library to send a POST request with both file and data parameters:

Using requests.post()

The requests.post() method is used to send a POST request to a specified URL with the specified data and/or files. The syntax of the post() method is as follows:

import requests

url = 'https://example.com/upload'
files = {'file': open('example.txt', 'rb')}
data = {'key': 'value'}

response = requests.post(url, files=files, data=data)
print(response.text)
  • url: The URL to which the request is sent.
  • files: A dictionary containing the name and file object for each file to be uploaded. The key is the name of the file input field in the HTML form.
  • data: A dictionary containing the key-value pairs of form data to be sent along with the file.

The response object returned by the post() method contains the server's response to the request. The response object includes various attributes such as status_code, headers, text, content, etc.

Example Code

Let's take a look at an example that demonstrates how to use requests.post() to send a file and data:




hljs.highlightAll();

import requests

url = 'https://example.com/upload'
files = {'file': open('example.txt', 'rb')}
data = {'key': 'value'}

response = requests.post(url, files=files, data=data)
print(response.text)

Alternative Method

Another way to send a file and data in a POST request is to use the requests.request() method. Here's how:

import requests

url = 'https://example.com/upload'
files = {'file': ('example.txt', open('example.txt', 'rb'), 'text/plain')}
data = {'key': 'value'}

response = requests.request("POST", url, files=files, data=data)
print(response.text)

In this example, we specify the file name, file object, and content type (MIME type) for each file in the files dictionary. The requests.request() method is then used to send the POST request with the specified files and data.

These are the two ways you can use Python requests to send a file and data in a POST request. Choose whichever approach suits your needs best!