Thorn Tech Marketing Ad
Skip to main content
Version: 1.2.0

Upload Files via API

TLDR

Purpose: Upload files to StorageLink using a Python script via the REST API.

Requirements:

  • Python 3 with requests library
  • CLIENT_ID and CLIENT_SECRET from /opt/swiftgw/application.properties
  • StorageLink username and password

Quick Start:

  1. Configure variables: BASE_URL, CLIENT_ID, CLIENT_SECRET, USERNAME, PASSWORD, UPLOAD_PATH, LOCAL_FILE_PATH
  2. Run: python upload_files.py

Success Response: "File uploaded successfully!" (HTTP 200, 201, or 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, open the configuration file by running:

cat /opt/swiftgw/application.properties

Locate the entries for CLIENT_ID and CLIENT_SECRET within the file. Note these down as they will be used in your script to authenticate API requests.

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://20.121.115.88/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:

python 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.
  • LOCAL_FILE_PATH: The local path to the file you wish to upload. Ensure this path points to the file you intend to upload.