Zendesk API: Oauth Tokens management documentation

Python use cases on the Zendesk API

This section describes how I created use cases in Python for the Zendesk API and how I documented them.

I created a Python program for a customer that uses the Zendesk API to manage access tokens. They needed a program that could manage access tokens on behalf of their customers to help the support team in their daily tasks, making customers do some operations for them.

The complete program and documentation can't be shown, so, in this section, I recreated some of the functions, with different code, to show you how I document APIs.

Here's what you'll find here:


Prerequisites

Get a Zendesk subdomain

To use the code in this section, you first need to have a Zendesk subdomain registered.

Here's the API reference with its documentation for further basic knowledge.

Create an API token

After gaining a Zendesk domain with an admin account, you can create an API token as follows:

Log in to your Zendesk account and go to the Admin Center:

Click on Apps and integrations and then on Zendesk API:

Click on Settings. Then, enable the Token access. Finally, click on Add API token:

Copy and paste the API token somewhere safe: it won't be shown again.

Then, save and you're done.

NOTE: to create OAuth tokens on behalf of clients you'll need to insert your API token in the program as this is an admin token.

Python prerequisites

To run the program you need:

  • Python 3 or later.

  • The library requests.

Since the library requests is not in the Python standard library you need to install it via the command:

$ pip install requests


Use cases implementation

This section shows Python code as use cases for the Zendesk API.

Here's what you'll find here:

Admin authenticator

If you're working with colleagues, each colleague can be an admin, create an admin API token, and use this program.

This program is called initial.py. It asks you for your:

After authentication, it creates a file called settings.py that stores your:

  • Zendesk login email.

  • API token.

  • Client ID.

NOTE: you'll provide your email and API token via CLI. The client ID is retrieved by the software automatically.

Here's the Python code:

import requests

# Define the Zendesk subdomain
ZENDESK_SUBDOMAIN = "" # Write your Zendesk subdomain

# Insert user email
email = input(f"\nPlease, insert your Zendesk login email:\n")
# Insert user API token
token = input(f"\nPlease, insert your Zendesk API token:\n")
 
def generate_settings(email, token)->None:
    """ Generates the settings.py file needed to use the main program"""
    # API request
    url = f'https://{ZENDESK_SUBDOMAIN}.zendesk.com/api/v2/oauth/clients'
    auth = (email + '/token', token)
    headers = {
    	"Content-Type": "application/json",
    }

    try:
        # Get response
        response = requests.get(url, auth=auth, headers=headers)
        # Get the clients in the JSON response
        number_of_ids = len(response.json()["clients"])
    
        # Iterate to get the client ID
        for id in range(number_of_ids):
            print(response.json()["clients"][id]["id"])
            client_id = response.json()["clients"][id]["id"]
    except Exception as e:
        print(e)

    # Write credentials to settings.py file
    with open("settings.py", "w") as settings_file:
        settings_file.write(f'EMAIL = "{email}"\n')
        settings_file.write(f'CLIENT_ID = "{client_id}"\n')
        settings_file.write(f'API_TOKEN = "{token}"\n')
        settings_file.close()
    print(f"\nSuccesfully created your settings file!")

if __name__ == "__main__":
    generate_settings(email, token)

WARNING: before using this program, you have to retrieve a Zendesk subdomain and write it in the above code. Then, you can launch the program via CLI and use it.

How to create an OAuth token

This program retrieves the information of an admin (Zendesk email and API token) stored in the settings.py file and:

  • Gets authentication to the Zendesk API.

  • Creates an OAuth token.

Your customers can use the OAuth token in other Python files you have written to authenticate to the Zendesk API and make some actions on your behalf.

For example, you may want to write a Python file that retrieves the logs on a customer machine and loads them on a Zendesk ticket; let's call it operator.py. To load them on a Zendesk ticket you need to authenticate your customer and you can safely do so via a OAuth token.

NOTE: the following code will ask you for a Zendesk ticket. Since you have a Zendesk subdomain, you can create one to test the code.

However, the request for the ticket is thought to follow this process:

  • A customer opens a ticket on Zendesk.

  • You realize that the customer can perform an action on their own using your operator.py file, so you create an OAuth token inserting the ticket number related to the customer.

  • You give the customer the OAuth token and tell them to run the operator.py file: this way, the ticket will be automatically updated without any intervention from your team.

Here's the code:

import base64
import json
import requests
import settings


# Define the Zendesk subdomain
ZENDESK_SUBDOMAIN = "" # Write your Zendesk domain

# Retrieve info from the settings file
email = settings.EMAIL
token = settings.API_TOKEN
client_id = settings.CLIENT_ID
auth = (email + '/token', token)

def generate_token(client_id:str, auth:str)->base64:
    """Creates an OAuth Token for the Zendesk API"""
    
    # API request to generate a new token
    url = f"https://{ZENDESK_SUBDOMAIN}.zendesk.com/api/v2/oauth/tokens.json"

    headers = {
        "Content-Type": "application/json"
    }

    data = {
        "token": {
            "client_id": client_id,
            "scopes": ["read", "write"]
        }
    }

    response = requests.post(url, headers=headers, json=data, auth=auth)
    
    # Get token ID
    oauth_id = str(response.json()["token"]["id"])
    # Get full token
    oauth_token = str(response.json()["token"]["full_token"])

    # Insert ticket number
    zendesk_ticket_number = input(f"Insert the Zendesk Ticket number: ")

    # Mix ticket number, token id, and full token
    clear_text_msg = f"{zendesk_ticket_number}:{oauth_id}:{oauth_token}"
    # Encode the mixed values
    encoded_msg = base64.b64encode(clear_text_msg.encode('utf-8')).decode('utf-8')

    # Return the mixed values
    print("\nHere's your new token!\n")
    return encoded_msg
    
if __name__ == "__main__":
    generate_token(client_id, auth)

WARNING: before using this program, you have to retrieve a Zendesk subdomain and write it in the above code. Then, you can launch the program via CLI and use it.

How to revoke active OAuth tokens

When you create OAuth tokens, they will remain stored in the web server, taking space.

It is a good practice to revoke all the active tokens, from time to time.

The following program revokes all the active tokens:

import json
import requests
import settings


# Define the Zendesk subdomain
ZENDESK_SUBDOMAIN = "" # Write your Zendesk domain

# Retrieve info from the settings file
email = settings.EMAIL
token = settings.API_TOKEN
client_id = settings.CLIENT_ID
auth = (email + '/token', token)

def revoke_all_tokens(auth:str)->None:
    """Revokes all the OAuth Tokens generated for the Zendesk API"""

    # API request to revoke all the tokens
    url = f"https://{ZENDESK_SUBDOMAIN}.zendesk.com/api/v2/oauth/tokens.json"

    headers = {
        "Content-Type": "application/json"
    }

    response = requests.get(url, headers=headers, auth=auth)

    # Calculate the number of existing tokens
    number_of_tokens = len(response.json()["tokens"])

    # Store response to a variable
    response_json = response.json()

    # Iterate to revoke all the existing tokens
    for arrayn in range(number_of_tokens):
        token_id = response_json["tokens"][arrayn]["id"] # Get token id
        url = f'https://{ZENDESK_SUBDOMAIN}.zendesk.com/api/v2/oauth/tokens/{token_id}.json'
        response = requests.delete(url, auth=auth) # Revoke tokens

        # Verify response
        try: 
            if response.status_code == 204:
                print("\nAll the tokens been revoked!\n")
            else:
                print("\nThere was a problem while revoking the tokens!\n")
        except Exception as e:
            print("\nAn exception occurred: ", e)
            
if __name__ == "__main__":
    revoke_all_tokens(auth)

WARNING: before using this program, you have to retrieve a Zendesk subdomain and write it in the above code. Then, you can launch the program via CLI and use it.

Last updated