SearchCtrl K



When your token expires, hit refresh and protect your API key

April 21, 2021 - Erikka Innes in Authenticate, Python

If you'd prefer to watch this tutorial, here's a video version (without the Python client):

                    <iframe src="https://embed.api.video/vod/vi1cigI8kYmZL5vr4cTJGch6" width="100%" height="100%" frameborder="0" scrolling="no" allowfullscreen="true"></iframe>   

api.video issues a refresh token alongside an access token. You may have seen this if you've examined the json that comes back when you authenticate with your api key. It looks like this (I edited the access_token and refresh_token a lot, they're very long strings in an actual response):

    'token_type': 'Bearer', 
    'expires_in': 3599, 
    'access_token': 'eyJ0eXAiOiJKV1.eyJhdWQiOiJsaXM.Cq4hM2chE_muUA', 
    'refresh_token': 'def502001b8f7547444f2'

Each access token is good for one hour, then it expires. You have three ways you can deal with this ongoing expiration:

  • Delegated tokens - If you want, you can use delegated tokens for some of your work. Delegated tokens can have any expiration time you want, so you can avoid dealing with the regular expiration. Delegated tokens are only for use with uploads though.
  • Authenticate again - You can use your API key every time your access token expires, and get a new token. Or, you can use it before your access token expires.
  • Use a refresh token - A refresh token lets you get a new access token without exposing your API credentials.

In many situations, using a refresh token will be the best option. When you authenticate, store the refresh token somewhere secure so you can use it later. Today's code sample shows you how to retrieve the refresh token, then use it to get a new token.

# Retrieve a refresh token 

import requests

# Get api.video token 

url = "https://ws.api.video/auth/api-key"

payload = {"apiKey": "your api key here"}
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json"

response = requests.request("POST", url, json=payload, headers=headers)
response = response.json()
token = response.get("refresh_token")

url = "https://ws.api.video/auth/refresh"

payload = {"refreshToken": token}
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json"

response = requests.request("POST", url, json=payload, headers=headers)
response = response.json()

# A new access token and refresh token are returned. 

And that's it! You can continue developing, or continue services in your system that need a new token to complete tasks.

Erikka Innes

Developer Evangelist

Create your free account

Start building with video now