How To: Simple Python Script to Upload File

How To: Simple Python Script to Upload File

Creating a simple Python script to upload a file to a REST API

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