How To: Simple Python Script to Upload File
Creating a simple Python script to upload a file to a REST API

I am a developer from the Greater Boston area, I have a M.S. in Computer Science and Engineering from the University of Connecticut, focused on Bayesian Networks and Bayesian Knowledge Bases. I have experience working on 3D laser scanners, motion platforms, DARPA projects, 3D simulations using the Unity game engine for robotics in synthetic environments (game generated and scanned), mobile development in both Android and iOS.
My strengths are in rapid prototyping and taking an idea into a release candidate. The process is a winding road that takes a lot of time
This is a small script that we can use to test uploading a file onto your backend. This comes in handy when trying to debug your code or a service. Here we set the endpoint, headers, and filename. Then we create a file_options object and then a file_data object. Finally we use the requests library to POST the file to the provided endpoint.
import requests
import json
def main():
endpoint = 'http://localhost:8080/upload'
headers = {'Authorization': 'Bearer {{bearer_token}}'}
filename = 'test_image.png'
file_options = {
'access': 'PRIVATE',
'ttl': 'P1M',
"overwrite": False,
'duplicateValidationStrategy': 'REJECT',
'duplicateValidationScope': 'EXACT_FOLDER'
}
files_data = {
'file': (filename, open(filename, 'rb'), 'application/octet-stream'),
'options': (None, json.dumps(file_options), 'text/strings'),
'folderPath': (None, '/parcelhub-attachments', 'text/strings')
}
response = requests.post(endpoint, headers=headers, files=files_data)
if __name__ == "__main__":
main()
For context, I enjoy writing short posts as it helps me document helpful tools for myself.
Hope this helps!
NOTE: The image of the title of this article was created using DALL-E.
References
https://community.hubspot.com/t5/APIs-Integrations/Powershell-text-file-upload/m-p/441175






