Python examples

Authorization via JWT

Sign in once, then send the user token in a header.

Before you start

  • A current Python release and the requests package.
  • Put the API address that came with your access into the environment variable API_BASE_URL. The samples never hard-code an address.
  • Keep tokens and passwords out of the script and out of a repository. The samples read them from environment variables.

When to use a user token

A user token represents a signed-in dashboard user. Use it for the operations that act on behalf of a user, such as the token methods and the image links of a session. For ordinary server-to-server calls a permanent API token is simpler.

Sign in

User authorization returns the token. The token is valid for the lifetime set on the account group, or for the number of days you send in valid_days when the group sets none.

import os
import sys

import requests

API = os.environ["API_BASE_URL"]


def login(email: str, password: str, valid_days: int = 1) -> str:
    reply = requests.post(
        f"{API}/user/login",
        json={"email": email, "password": password, "valid_days": valid_days},
        timeout=30,
    )
    if reply.status_code != 200:
        # A refused login is a 403. The body still says "ok", so the HTTP code is the signal here.
        sys.exit(f"login refused: HTTP {reply.status_code}")
    return reply.json()["token"]


token = login(os.environ["DASHBOARD_EMAIL"], os.environ["DASHBOARD_PASSWORD"])

Use the token

Send it in the token header. The example lists the permanent API tokens of the account with list tokens.

reply = requests.post(f"{API}/tokens", headers={"token": token}, json={}, timeout=30)
print(reply.status_code)

Notes

  • The token header is not the body field. Do not send the user token in the body.
  • Do not log the token, and do not write it to disk.
  • When the token expires, sign in again.

Questions while integrating?

Write to us with the details and we will help.

Talk to us