Last modified: Nov 22, 2024 By Alexander Williams

Python Requests: Complete Guide to POST Files with Examples

Uploading files using Python's Requests library is a common task in web development. This guide will show you how to effectively POST files using the requests library in Python.

Basic File Upload

To upload a single file using Python Requests, you'll need to use the files parameter in your POST request. Here's a simple example:


import requests

# Open file in binary mode
with open('example.txt', 'rb') as file:
    # Create files dictionary
    files = {'file': file}
    # Make POST request
    response = requests.post('https://api.example.com/upload', files=files)

# Check if upload was successful
print(response.status_code)

Multiple File Upload

For uploading multiple files simultaneously, you can include multiple file entries in the files dictionary. Here's how:


import requests

# Prepare multiple files
files = {
    'file1': open('document1.pdf', 'rb'),
    'file2': open('image.jpg', 'rb'),
    'file3': open('data.csv', 'rb')
}

# Upload files
try:
    response = requests.post('https://api.example.com/upload', files=files)
    print(f"Upload Status: {response.status_code}")
finally:
    # Important: Close all file handles
    for file in files.values():
        file.close()

Custom File Names and MIME Types

Sometimes you need to specify custom filenames or MIME types. You can achieve this by using tuples in the files dictionary:


import requests

# Using tuple format: (filename, file_object, content_type)
files = {
    'file': ('custom_name.txt', open('original.txt', 'rb'), 'text/plain'),
    'image': ('photo.jpg', open('image.jpg', 'rb'), 'image/jpeg')
}

response = requests.post('https://api.example.com/upload', files=files)
print(response.json())

Handling Large Files

When dealing with large files, it's important to stream them to avoid memory issues. Here's how to handle large file uploads:


import requests
from requests_toolbelt import MultipartEncoder
import os

# Create MultipartEncoder for streaming
file_path = 'large_file.zip'
m = MultipartEncoder(
    fields={'file': ('filename', open(file_path, 'rb'), 'application/zip')}
)

# Make the request with proper headers
response = requests.post(
    'https://api.example.com/upload',
    data=m,
    headers={'Content-Type': m.content_type}
)

For more information about downloading files using requests, check out our guide on downloading files with Python Requests.

If you're interested in handling images specifically, you might want to read our guide on downloading images using Requests.

Error Handling

Always implement proper error handling when uploading files. Here's a robust example:


import requests
from requests.exceptions import RequestException

def upload_file(file_path, upload_url):
    try:
        with open(file_path, 'rb') as file:
            files = {'file': file}
            response = requests.post(upload_url, files=files)
            response.raise_for_status()  # Raise exception for bad status codes
            return response.json()
    except FileNotFoundError:
        print(f"Error: File {file_path} not found")
    except RequestException as e:
        print(f"Upload failed: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

Conclusion

Uploading files with Python Requests is straightforward when you understand the basics. Remember to always close file handles and implement proper error handling for robust applications.

For more advanced topics on Python Requests, check out our article on SSL verification in Python Requests.