Thorn Tech Marketing Ad
Skip to main content
Version: 1.3.1

Upload Files via API

TLDR

Purpose: Upload a file to StorageLink with a Python script that calls the REST API

Requirements:

  • Python 3 with the requests library
  • The client ID and secret: security.client-id and security.client-secret in /opt/swiftgw/application.properties
  • A StorageLink username and password

Quick Start:

  1. Set BASE_URL, CLIENT_ID, CLIENT_SECRET, USERNAME, PASSWORD, UPLOAD_PATH (the StorageLink destination folder, starting with /) and LOCAL_FILE_PATH (the file to upload)
  2. Run python3 upload_files.py

Success Response: The script prints File uploaded successfully! when the API returns HTTP 200, 201 or 204 (StorageLink returns 204)

Product: StorageLink by Thorn Technologies — cloud storage gateway for secure file sharing

How to Use the Python Script to Upload Files​

This article guides you through the process of using a Python script to upload files to an API. The script requires specific credentials that you can obtain from your server's configuration files.

Obtaining CLIENT_ID and CLIENT_SECRET​

To authenticate and interact with the API, you will need a CLIENT_ID and CLIENT_SECRET. These can be obtained by accessing your server's configuration files: SSH into your server where the API is hosted. Once logged in, show the two entries by running:

sudo grep -E '^security.client-(id|secret)=' /opt/swiftgw/application.properties

The values of security.client-id and security.client-secret are the CLIENT_ID and CLIENT_SECRET your script uses to authenticate API requests. (Avoid cat on this file: it also prints the database password and the token signing secret.)

Using the Provided Script​

Below is the Python script you will use to upload files to the API. It is pre-configured with placeholder values for the variables you will replace with actual credentials and paths:

import requests
import base64
import urllib3
import os

# Suppress warnings for self-signed SSL certificates
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Variables to be configured
BASE_URL = "https://your-storagelink-host/backend"
CLIENT_ID = "Your_CLIENT_ID_here"
CLIENT_SECRET = "Your_CLIENT_SECRET_here"
USERNAME = "Your_Username_here"
PASSWORD = "Your_Password_here"
UPLOAD_PATH = "/Your_Upload_Path_here"
LOCAL_FILE_PATH = "/path/to/your/file"

def get_oauth_token():
"""Retrieve OAuth token using client credentials."""
url = f"{BASE_URL}/login"
credentials = f"{CLIENT_ID}:{CLIENT_SECRET}"
auth_header = base64.b64encode(credentials.encode()).decode()
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"Basic {auth_header}"
}
data = {
"grant_type": "password",
"username": USERNAME,
"password": PASSWORD
}
response = requests.post(url, headers=headers, data=data, verify=False)
if response.status_code == 200:
return response.json().get("access_token")
else:
print(f"Error getting token: {response.text}")
return None

def upload_file(token):
"""Upload file to StorageLink API"""
url = f"{BASE_URL}/1.0.0/filesystem{UPLOAD_PATH}"
headers = {
"Authorization": f"Bearer {token}"
}
with open(LOCAL_FILE_PATH, "rb") as file:
files = {"data": file}
response = requests.post(url, headers=headers, files=files, verify=False)
if response.status_code in [200, 201, 204]:
print("File uploaded successfully!")
else:
print(f"Error uploading file: {response.text}")

if __name__ == "__main__":
token = get_oauth_token()
if token:
upload_file(token)

Replace the placeholder values in the script with the credentials you obtained and the specific paths relevant to your API's environment.

Executing the Script​

To execute the script:

Save the script to a local file with a .py extension, for example, upload_files.py. Open a command line interface (CLI), navigate to the directory where your script is saved.

Run the script by typing:

python3 upload_files.py

This will execute the script, and it should output the authentication status followed by a success message if the file is uploaded successfully, or an error message if not.

Understanding and Configuring Script Variables​

The script contains several variables that you need to configure according to your environment. Here's what each variable means and how you can adjust them:

  • BASE_URL: The URL of the API backend. Replace this with the URL provided to you by your API administrator.
  • CLIENT_ID and CLIENT_SECRET: These are credentials provided to you by the API provider. They are used to authenticate your script's access to the API.
  • USERNAME and PASSWORD: Your API user credentials. These may differ depending on your role or the permissions assigned to you.
  • UPLOAD_PATH: The path on the API where the files will be uploaded. Change this path based on where you need the files stored. Folders in the path that don't exist yet are created.
  • LOCAL_FILE_PATH: The local path to the file you wish to upload. Ensure this path points to the file you intend to upload.