Sirv REST API - Python Examples
Short answer
Create an API client in your Sirv account, then use its client ID and secret in a Python script to request a bearer token. Send that token with every other API call. The upload example on this page sends a file from your computer to a folder in your Sirv account.
After reading this you will know
- How to get a bearer token with Python
- How to upload a file with Python
- Where to find every REST API method
Use the Sirv REST API to perform more than 60 common tasks on your Sirv account.
Visit the REST API reference for all methods.
Connect to Sirv with Python
Section titled “Connect to Sirv with Python”Create an API client via your Sirv account, if you’ve not created one already. You’ll be given a client ID and client Secret.
Keep your client ID and secret in the SIRV_CLIENT_ID and SIRV_CLIENT_SECRET environment variables, not in the code. This script requests a token with them:
import osimport requestsimport json
url = 'https://api.sirv.com/v2/token'
payload = { 'clientId': os.environ['SIRV_CLIENT_ID'], 'clientSecret': os.environ['SIRV_CLIENT_SECRET']}headers = {'content-type': 'application/json'}
response = requests.request('POST', url, data=json.dumps(payload), headers=headers)
token = response.json()['token']Now that you have a token, you can perform any of the more than 60 API commands.
Python upload example
Section titled “Python upload example”Upload a file to your Sirv account.
- Endpoint: https://api.sirv.com/v2/files/upload
- Documentation: Upload file
Example upload script:
url = 'https://api.sirv.com/v2/files/upload'
querystring = {'filename':'/path/to/uploaded-image.jpg'}
payload = open('/path/to/local-image.jpg', 'rb')
headers = { 'content-type': 'image/jpeg', 'authorization': 'Bearer %s' % token}
response = requests.request('POST', url, data=payload, headers=headers, params=querystring)
print(response)Including the connection to Sirv, to fetch a token, the script would look like this:
import osimport requestsimport json
# First, get a token
url = 'https://api.sirv.com/v2/token'
payload = { 'clientId': os.environ['SIRV_CLIENT_ID'], 'clientSecret': os.environ['SIRV_CLIENT_SECRET']}
headers = {'content-type': 'application/json'}
response = requests.request('POST', url, data=json.dumps(payload), headers=headers)
token = response.json()['token']
# Now upload a file
url = 'https://api.sirv.com/v2/files/upload'
querystring = {'filename':'/path/to/uploaded-image.jpg'}
payload = open('/path/to/local-image.jpg', 'rb')
headers = { 'content-type': 'image/jpeg', 'authorization': 'Bearer %s' % token}
response = requests.request('POST', url, data=payload, headers=headers, params=querystring)
print(response)A response of 200 means the file was uploaded to your Sirv account.
