Save to file

What are you building here

We're going to consume all the calls available on the Activate API and save each of them in a JSON file.

Please note that at some point, the number of calls exposed by the API can be in the thousands, or hundreds of thousands. You might want to implement some limit if this is the case.

To name the JSON file, we're pre-supposing that a field original_file exists in the metadata field of each call. For this to be true, you have to provide it using our JUpload API. As a fallback, the code will use the Unique ID our system has given to the call on input.

Code

For this test, we name the python file save_to_file.py. Yes, this is quite original!

First things first, you need to retrieve an access token from our SSO service, and pass it in an Authorization header when requesting the Activate API.

We recommend you pass client ID and secret to the script as environment variables, or persist them in a database that is accessed at runtime. Running in a shell, you can pass the values to the script like this for example:

CLIENT_ID="acme-corp" CLIENT_SECRET="some-secret-value" python save_to_file.py

The code itself looks like:

import json
import os
import requests

# Retrieve an Access Token from the SSO service
payload = {
"client_id": os.getenv("CLIENT_ID"),
"client_secret": os.getenv("CLIENT_SECRET"),
"grant_type" : "client_credentials"
}
r = requests.post("https://id.uh.live/realms/uhlive/protocol/openid-connect/token", data=payload)
r.raise_for_status()
access_token = r.json()['access_token']

# Now we request the Activate API
headers = {"Authorization": f"Bearer {access_token}"}
LIMIT = 20
offset = 0

while True: # Careful here if you have a lot of calls on your account
r = requests.get(f"https://activate.uh.live/calls?limit={LIMIT}&offset={offset}", headers=headers)
r.raise_for_status()
data = r.json()
if not data['data']:
# No more data to parse
break
for call in data['data']:
if call['metadata'].get('original_file'):
filename = call['metadata']['original_file'] # for example: `my_audio_123.mp3`
else:
filename = call['unique_id']
filename = f"{filename}.json" # following our example: `my_audio_123.mp3.json`
with open(filename, 'w') as jsonfile:
# Save the call payload to a dedicated file
json.dump(call, jsonfile)
offset += LIMIT