API Python Workspace and Model IDs

DaanishSoomar
Certified Master Anaplanner

API Python Workspace and Model IDs

Hello,

 

I have successfully setup my Python environment. I did have a question around a specific requirement.

 

https://community.anaplan.com/t5/Best-Practices/Using-Python-3-with-the-Anaplan-API/ta-p/33150

 

From the above link, I have tried the “get models”, “get modelinfo”, and “getworkspaces” Python scripts. What I am looking for is a Python API script which can return the following fields:

 

1) Model ID

2) Model Name

3) Workspace ID

4) Workspace Name

 

Unfortunately the templates I mentioned above return at most 3 of these 4 requirements. I am able to get all of these fields if I run 2 separate scripts. 1 to return Model ID, Model Name, and Workspace ID and another to get Workspace ID and Workspace Name.

 

Is there a way to get all of the above information in 1 Get request? And then write to CSV (I know how to do this part based on some Googling)? 

Any help here would be greatly appreciated!

1 ACCEPTED SOLUTION

Accepted Solutions
kevin.cho
Certified Master Anaplanner

Re: API Python Workspace and Model IDs

Hi daanish,

 

You won't get all of this info in one single request, but there's no reason why you can't extend the script to have multiple requests and then write out to a single CSV.

 

The below snip will do what you are after. Replace username and password with your own. 

 

It'll loop through all workspaces, and all models in each workspace (ignoring those that are Archived) and write out to a file called "community.csv).


Remember to install the csv module if not already.

I added some comments to the code explaining what each line does. 

 

 

import requests
from base64 import b64encode
import csv

# This block is all about setting up the authentication header - just one way to do it. This is using the Basic Authentication method, but you can also authenticate via certificate

# Initialise the headers variable that we are going to pass through for the authentication request
init_auth_headers = {}

# Convert our username and password into the Base64 format as required by the Authentication API 
init_auth_string = b64encode(b'username:password').decode()

# If we didn't initialise the header on line 8, this next line would throw an error 
init_auth_headers['Authorization'] = 'Basic ' + init_auth_string

# Make a call to the Authentication API using the credentials we just initialised - it's a POST call to 'https://auth.anaplan.com/token/authenticate' and we have to pass our Authorization string in the headers
# This stores the result in a JSON format in a variable called "init_auth_token"
init_auth_token = requests.post('https://auth.anaplan.com/token/authenticate', headers=init_auth_headers).json()

# We then need to retrieve the specific element of the JSON, which is in tokenInfo.tokenValue
auth_token = init_auth_token.get('tokenInfo').get('tokenValue')

# Same thing here as in line 8, initialising our header variable that we will use for the rest of our calls
auth_headers = {}

# Set up the Anaplan authentication header
auth_headers['Authorization'] = 'AnaplanAuthToken ' + auth_token

# Make our request to the workspaces API to retrieve all workspaces - this is again stored in a JSON format in a variable called "workspaces_json" 
workspaces_json = requests.get('https://api.anaplan.com/2/0/workspaces/', headers=auth_headers).json()


# Now we can start to open up our file that we are going to write into 
with open('community.csv', 'w', newline='') as write_file:
    # Initialise our csv writer object, using commas as our delimiters 
    model_writer = csv.writer(write_file,delimiter = ',')
    # Write a header row
    model_writer.writerow(['Model ID', 'Model Name', 'Workspace ID', 'Workspace Name'])
    # Our workspaces_json variable has an element called "workspaces" that will have each workspace that you have access to
    # We can loop through this to then get each model in each workspace
    for wsp in workspaces_json['workspaces']:
        # With the specific workspace in mind (changing each loop), we can pass through the workspace id to our models API call 
        model_json = requests.get('https://api.anaplan.com/2/0/workspaces/{}/models'.format(wsp['id']), headers=auth_headers).json()
        # Similar thing here with the workspaces call, the model_json variable has an element called "models" that will have each model you have access to
        # We can iterate through each model to get each model specific detail
        for mdl in model_json['models']:
            # I ignore archived models because we have so many backups, you can ignore this if you want, or even add more conditions here
            if mdl['activeState'] != 'ARCHIVED':
                model_writer.writerow(['{}'.format(mdl['id']), '{}'.format(mdl['name']), '{}'.format(wsp['id']),'{}'.format(wsp['name'])])
            
         

 

 

 

 

View solution in original post

5 REPLIES 5
kevin.cho
Certified Master Anaplanner

Re: API Python Workspace and Model IDs

Hi daanish,

 

You won't get all of this info in one single request, but there's no reason why you can't extend the script to have multiple requests and then write out to a single CSV.

 

The below snip will do what you are after. Replace username and password with your own. 

 

It'll loop through all workspaces, and all models in each workspace (ignoring those that are Archived) and write out to a file called "community.csv).


Remember to install the csv module if not already.

I added some comments to the code explaining what each line does. 

 

 

import requests
from base64 import b64encode
import csv

# This block is all about setting up the authentication header - just one way to do it. This is using the Basic Authentication method, but you can also authenticate via certificate

# Initialise the headers variable that we are going to pass through for the authentication request
init_auth_headers = {}

# Convert our username and password into the Base64 format as required by the Authentication API 
init_auth_string = b64encode(b'username:password').decode()

# If we didn't initialise the header on line 8, this next line would throw an error 
init_auth_headers['Authorization'] = 'Basic ' + init_auth_string

# Make a call to the Authentication API using the credentials we just initialised - it's a POST call to 'https://auth.anaplan.com/token/authenticate' and we have to pass our Authorization string in the headers
# This stores the result in a JSON format in a variable called "init_auth_token"
init_auth_token = requests.post('https://auth.anaplan.com/token/authenticate', headers=init_auth_headers).json()

# We then need to retrieve the specific element of the JSON, which is in tokenInfo.tokenValue
auth_token = init_auth_token.get('tokenInfo').get('tokenValue')

# Same thing here as in line 8, initialising our header variable that we will use for the rest of our calls
auth_headers = {}

# Set up the Anaplan authentication header
auth_headers['Authorization'] = 'AnaplanAuthToken ' + auth_token

# Make our request to the workspaces API to retrieve all workspaces - this is again stored in a JSON format in a variable called "workspaces_json" 
workspaces_json = requests.get('https://api.anaplan.com/2/0/workspaces/', headers=auth_headers).json()


# Now we can start to open up our file that we are going to write into 
with open('community.csv', 'w', newline='') as write_file:
    # Initialise our csv writer object, using commas as our delimiters 
    model_writer = csv.writer(write_file,delimiter = ',')
    # Write a header row
    model_writer.writerow(['Model ID', 'Model Name', 'Workspace ID', 'Workspace Name'])
    # Our workspaces_json variable has an element called "workspaces" that will have each workspace that you have access to
    # We can loop through this to then get each model in each workspace
    for wsp in workspaces_json['workspaces']:
        # With the specific workspace in mind (changing each loop), we can pass through the workspace id to our models API call 
        model_json = requests.get('https://api.anaplan.com/2/0/workspaces/{}/models'.format(wsp['id']), headers=auth_headers).json()
        # Similar thing here with the workspaces call, the model_json variable has an element called "models" that will have each model you have access to
        # We can iterate through each model to get each model specific detail
        for mdl in model_json['models']:
            # I ignore archived models because we have so many backups, you can ignore this if you want, or even add more conditions here
            if mdl['activeState'] != 'ARCHIVED':
                model_writer.writerow(['{}'.format(mdl['id']), '{}'.format(mdl['name']), '{}'.format(wsp['id']),'{}'.format(wsp['name'])])
            
         

 

 

 

 

View solution in original post

DaanishSoomar
Certified Master Anaplanner

Re: API Python Workspace and Model IDs

This worked great! Thank you @kevin.cho.

 

Yes I appreciate the level of detail. I wanted to see if there was a quick script available to achieve this before going down the path of creating my own custom script.

 

This is awesome.

JaredDolich
Moderator

Re: API Python Workspace and Model IDs

Nice one @kevin.cho - just added this to my private list of best practices. Kudos. Would make a great best practice.


Jared Dolich
kevin.cho
Certified Master Anaplanner

Re: API Python Workspace and Model IDs

I'm in the process of writing up some documentation for my team, and have also started a draft article in the Community Content/Best Practices section 🙂 

DaanishSoomar
Certified Master Anaplanner

Re: API Python Workspace and Model IDs

Amazing! I am sure both @JaredDolich and I (along with the rest of the Anaplan/Python Community) would be thrilled to see all of the gems of knowledge you've got up your sleeve 🙂 @kevin.cho