EducationSoftwareStrategy.com
StrategyCommunity

Knowledge Base

Product

Community

Knowledge Base

TopicsBrowse ArticlesDeveloper Zone

Product

Download SoftwareProduct DocumentationSecurity Hub

Education

Tutorial VideosSolution GalleryEducation courses

Community

GuidelinesGrandmastersEvents
x_social-icon_white.svglinkedin_social-icon_white.svg
Strategy logoCommunity

© Strategy Inc. All Rights Reserved.

LegalTerms of UsePrivacy Policy
  1. Home
  2. Topics

Using MicroStrategy REST API to quickly create a sandbox project (Python script)


Robert Prochowicz

Manager, Sales Engineering • MicroStrategy


Sometimes you need a demo project or a project that you can use as a sandbox. If you want to be sure that only you have access to it you need to perform some steps like creating a new project, new user, new security role and several others. If you create such projects often you can automate this process. The Python script below can be used for such an automation. From this script you can learn how to use all those various MicroStrategy REST APIs.

This script will perform the following:
# Authenticate: log in / Log out
# Create a new MSTR Project
# Create a new User Group
# Create a new User
# Create a new Security Role
# With the new User Group - assign new Security Role to the new Project
# With the new User Group - give MODIFY access to Shared Reports folder
# Remove default Security Role assignment for User Group EVERYONE
Video
Note - I've added color formatting in the code below (http://hilite.me/). Code copied from here might not work due to indentation issues. In that case, use attached file with sample code.
Also this CRM is adding ';' near URLs (see below variable base_url)


### Tested with MSTR 2020
### Robert Prochowicz / 2020-04-08
### Strategy REST API - fast new project creation - this script will perform the following:
# Authenticate: log in / Log out
# Create a new MSTR Project
# Create a new User Group
# Create a new User
# Create a new Security Role
# With the new User Group - assign new Security Role to the new Project
# With the new User Group - give MODIFY access to Shared Reports folder
# Remove default Security Role assignment for User Group EVERYONE
### All the new object names (and user password) will be the same as the new Project name (user input)
### It was written for MSTR Cloud instance (AWS), but you can easily change that to any other server

import requests
from time import sleep
from datetime import datetime

### INPUT VARIABLES ###
keyword      = str(input("Project name           : "))
AWS_No       = str(input("AWS instance number    : "))
api_password = str(input("Password of 'mstr' user: "))
    
### Parameters ###
api_login = 'mstr'
base_url = 'https://env-' +AWS_No+ '.customer.cloud.Strategy.com/MicroStrategyLibrary/api/'


#### FUNCTIONS ###
def login(base_url,api_login,api_password):
    print("Getting token...")
    data_get = {'username': api_login,
                'password': api_password,
                'loginMode': 1}
    r = requests.post(base_url + 'auth/login', data=data_get)
    if r.ok:
        authToken = r.headers['X-MSTR-AuthToken']
        cookies = dict(r.cookies)
        print("Token: " + authToken)
        return authToken, cookies
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))


def logout(authToken, cookies):
    headers = set_headers(authToken)
    print("\nLogging out...")
    r = requests.post(base_url + "auth/logout", headers=headers, cookies=cookies)
    if r.ok:
        print("OK")
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))    


def set_headers(authToken):
    headers = {'X-MSTR-AuthToken': authToken, 'Content-Type': 'application/json'}
    return headers


def set_headers2(authToken,project_id):
    headers = {'X-MSTR-AuthToken': authToken,
               'Content-Type': 'application/json',#IMPORTANT!
               'Accept': 'application/json',
               'X-MSTR-ProjectID': project_id}
    return headers


def create_project(base_url, authToken, cookies, keyword):
    headers = set_headers(authToken)
    print("\nCreating new Project...")
    project_def = '{"name":"'+keyword+'", "description":"'+keyword+'"}'
    r = requests.post(base_url + "projects", headers=headers, data=project_def, cookies=cookies)
    if r.ok:
        print("Project CREATED successfully")
        print("Project: ", keyword)
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))

        
def get_projectid(base_url, authToken, cookies, keyword):
    headers = set_headers(authToken)
    print("\nGetting ProjectID...")
    r = requests.get(base_url + "projects/" + keyword, headers=headers, cookies=cookies)
    if r.ok:
        print("Success")
        print("Project Name: " + keyword)
        print("Project ID:   " + r.json()['id'])
        return r.json()['id']
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))      

        
def create_user_group(base_url, authToken, cookies, keyword):
    headers = set_headers(authToken)
    print("\nCreating new User Group...")
    group_def = '{"name":"'+keyword+'", "description":"'+keyword+'", "memberships":[], "members":[]}'
    r = requests.post(base_url + "usergroups", headers=headers, data=group_def, cookies=cookies)
    if r.ok:
        print("User Group CREATED successfully")
        print("User Group: ", keyword)
        print("Group ID:     " + r.json()['id'])
        return r.json()['id']
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))


def create_user(base_url, authToken, cookies, keyword, ug):
    headers = set_headers(authToken)
    print("\nCreating new User...")
    user_def = ('{"username":"'+keyword+'", "fullName":"'+keyword+
                '", "description":"'+keyword+'", "password":"'+keyword+
                '", "enabled":"true", "passwordModifiable":"true", "standardAuth":"true"'
                ', "memberships":["'+ug+'"]}'
               )
    r = requests.post(base_url + "users", headers=headers, data=user_def, cookies=cookies)
    if r.ok:
        print("User CREATED successfully")
        print("User: ", keyword)
        print("User ID:     " + r.json()['id'])
        return r.json()['id']
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))    


# privileges for the new Security Role 
# (almost all, except some potentially harmful admin and architect privileges)
# you can see all the privileges (with IDs) by running this API: GET /api/iserver/privileges
privil = str([{"id":"1"},{"id":"3"},{"id":"4"},{"id":"6"},{"id":"8"},{"id":"9"},{"id":"12"},{"id":"13"},{"id":"18"},{"id":"19"},
          {"id":"20"},{"id":"21"},{"id":"22"},{"id":"23"},{"id":"24"},{"id":"25"},{"id":"26"},{"id":"27"},{"id":"28"},
          {"id":"29"},{"id":"30"},{"id":"31"},{"id":"36"},{"id":"37"},{"id":"38"},{"id":"39"},{"id":"40"},{"id":"41"},
          {"id":"42"},{"id":"43"},{"id":"44"},{"id":"46"},{"id":"47"},{"id":"49"},{"id":"60"},{"id":"66"},{"id":"68"},
          {"id":"69"},{"id":"71"},{"id":"72"},{"id":"73"},{"id":"74"},{"id":"75"},{"id":"76"},{"id":"77"},{"id":"78"},
          {"id":"79"},{"id":"80"},{"id":"82"},{"id":"84"},{"id":"86"},{"id":"87"},{"id":"88"},{"id":"89"},{"id":"90"},
          {"id":"91"},{"id":"94"},{"id":"96"},{"id":"98"},{"id":"100"},{"id":"101"},{"id":"102"},{"id":"106"},{"id":"110"},
          {"id":"111"},{"id":"112"},{"id":"113"},{"id":"114"},{"id":"115"},{"id":"116"},{"id":"117"},{"id":"118"},
          {"id":"119"},{"id":"120"},{"id":"125"},{"id":"126"},{"id":"127"},{"id":"128"},{"id":"129"},{"id":"130"},
          {"id":"132"},{"id":"134"},{"id":"136"},{"id":"137"},{"id":"138"},{"id":"160"},{"id":"161"},{"id":"162"},
          {"id":"163"},{"id":"164"},{"id":"180"},{"id":"185"},{"id":"186"},{"id":"187"},{"id":"188"},{"id":"189"},
          {"id":"190"},{"id":"191"},{"id":"192"},{"id":"193"},{"id":"194"},{"id":"195"},{"id":"196"},{"id":"197"},
          {"id":"200"},{"id":"202"},{"id":"203"},{"id":"204"},{"id":"205"},{"id":"206"},{"id":"207"},{"id":"208"},
          {"id":"209"},{"id":"210"},{"id":"211"},{"id":"213"},{"id":"215"},{"id":"216"},{"id":"217"},{"id":"218"},
          {"id":"219"},{"id":"220"},{"id":"222"},{"id":"223"},{"id":"224"},{"id":"225"},{"id":"226"},{"id":"227"},
          {"id":"228"},{"id":"232"},{"id":"233"},{"id":"234"},{"id":"235"},{"id":"236"},{"id":"237"},{"id":"238"},
          {"id":"239"},{"id":"240"},{"id":"241"},{"id":"242"},{"id":"250"},{"id":"251"},{"id":"252"},{"id":"255"},
          {"id":"256"},{"id":"257"},{"id":"258"},{"id":"260"},{"id":"261"},{"id":"262"},{"id":"263"},{"id":"265"},
          {"id":"266"},{"id":"267"},{"id":"270"},{"id":"271"},{"id":"272"},{"id":"273"},{"id":"274"},{"id":"275"},
          {"id":"276"},{"id":"285"},{"id":"286"}]).replace("\'","\"")


def create_secrole(base_url, authToken, cookies, keyword, privileges):
    headers = set_headers(authToken)
    print("\nCreating new Security Role...")
    secrole_def = ('{"name":"'+keyword+'", "description":"'+keyword+'", "privileges":'+privileges+'}')
    r = requests.post(base_url + "securityRoles", headers=headers, data=secrole_def, cookies=cookies)
    if r.ok:
        print("Security Role CREATED successfully")
        print("Security Role: ", keyword)
        print("Security Role ID:     " + r.json()['id'])
        return r.json()['id']
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))
         
        
def secrole_assignment(base_url, authToken, cookies, ug_id, pr_id, secrole_id, operation): # one user group only
    # Use addElement, replace or removeElement operation to be performed
    headers = set_headers(authToken)
    print("\nChanging Security Role assignment...")
    secrole_def = ('{"operationList":[{"op":"'+operation+'","path":"/members", "value" : {"projectId": "'
                   +pr_id+'", "memberIds":["'+ug_id+'"]}}]}')
    r = requests.patch(base_url + "securityRoles/" + secrole_id, headers=headers, data=secrole_def, cookies=cookies)
    if r.ok:
        print("Security Role Assignment MODIFIED successfully")
        print("Operation:            " + operation)
        print("Security Role ID:     " + r.json()['id'])
        print("Security Role Name:   " + r.json()['name'])
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))

        
def set_acl(base_url, authToken, cookies, folder_id, project_id, ug_id, operation, acl_code):
    headers = set_headers2(authToken,project_id)
    print("\nChanging ACL settings...")
    acl_def = ('{"acl":[{"op":"'+operation+'","trustee":"'+ug_id+'","rights":'+acl_code+'}],"propagateACLToChildren":true}')
    r = requests.put(base_url + "objects/" + folder_id + "?type=8", headers=headers, data=acl_def, cookies=cookies)
    if r.ok:
        print("ACL MODIFIED successfully")
        print("Operation:            " + operation)
    else:
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))

### Main script
       
dt=datetime.now()

authToken, cookies = login(base_url,api_login,api_password)

create_project(base_url, authToken, cookies, keyword)
ug_id = create_user_group(base_url, authToken, cookies, keyword)
uid = create_user(base_url, authToken, cookies, keyword, ug_id)
sc = create_secrole(base_url, authToken, cookies, keyword, privil)
pr_id = ''
while not pr_id:
    pr_id = get_projectid(base_url, authToken, cookies, keyword)    
    print("\nTrying again")
    sleep(3)

### Remove default assignment for User Group EVERYONE
# User Group 'Everyone' + Newly created Project + default Security Role 'Normal Users'
secrole_assignment(base_url, authToken, cookies, "C82C6B1011D2894CC0009D9F29718E4F", pr_id,
                   "73F7482111D3596C60001B8F67019608", "removeElement")
### Add assignment
# Newly created User Group + Newly created Project + Newly created Security Role
secrole_assignment(base_url, authToken, cookies, ug_id, pr_id, sc, 'addElement')

# Assigning access rights to "Shared Reports" folder
# acl_code 223 means MODIFY
set_acl(base_url, authToken, cookies, "D3C7D461F69C4610AA6BAA5EF51F4125", pr_id, ug_id, "ADD", "223")

print("\n#############\nProject fully created\nExecution time: ", datetime.now()-dt)

logout(authToken, cookies)


Comment

0 comments

Details

Example

Published:

April 9, 2020

Last Updated:

November 21, 2022