API Navigator Logo

Python Requests with File Upload

Author: Newtum

This example shows how to upload a file using an HTTP POST request with the Python Requests library.

Uploading a File

To upload a file, you pass a dictionary to the `files` parameter of `requests.post()`. The key is the field name the server expects, and the value is a file-like object opened in binary mode.

import requests
# In a real script, you would have a file to upload.
# with open('my_file.txt', 'rb') as f:
#     response = requests.post('https://httpbin.org/post', files={'file': f})
#     print(response.json())

# Here we simulate the file in memory
file_content = b"This is the content of the file."
files = {'upload_file': ('test_file.txt', file_content, 'text/plain')}

response = requests.post('https://httpbin.org/post', files=files)

print("Status Code:", response.status_code)
print("The 'files' part of the response shows the uploaded file's details:")
print(response.json()['files'])