API Reference
Session classes
- class mstr.requests.MSTRRESTSession(base_url=None)[source]
Bases:
AuthMixin,SessionsMixin,ProjectsMixin,SessionPersistenceMixin,MSTRBaseSessionFull-featured session for the MicroStrategy REST API.
Combines authentication, session management, project helpers, and serialisation into a single
requests.Sessionsubclass. Use this class directly when you need manual control over the session lifecycle, or preferAuthenticatedMSTRRESTSessionfor automatic login/logout via a context manager.- close()
Closes all adapters and as such the session
- create_url(url)
Create the URL based off this partial path.
- delegate(identity_token: str) Response
Authenticate with a delegated identity token via
POST /auth/delegate.- Parameters:
identity_token – A valid MicroStrategy identity token.
- Returns:
A
requests.Responsefor the delegate request.- Raises:
requests.HTTPError – If the server returns a non-204 status.
- delete(url, **kwargs)
Sends a DELETE request. Returns
Responseobject.- Parameters:
url – URL for the new
Requestobject.**kwargs – Optional arguments that
requesttakes.
- Return type:
- extend_session() Response
Prolong the current session.
Convenience alias for
put_sessions().
- classmethod from_dict(session_dict: Dict[str, Any]) _T
Create a new session instance from a dict snapshot.
Subclasses must accept
base_urlas their first constructor argument.- Parameters:
session_dict – A dict previously produced by
to_dict().- Returns:
A new session with state restored from session_dict.
- get(url, **kwargs)
Sends a GET request. Returns
Responseobject.- Parameters:
url – URL for the new
Requestobject.**kwargs – Optional arguments that
requesttakes.
- Return type:
- get_adapter(url)
Returns the appropriate connection adapter for the given URL.
- Return type:
- get_project_id(project_name: str) str | None
Return the project ID for project_name, or
Noneif not found.load_projects()must be called first.- Parameters:
project_name – The display name of the project.
- Raises:
SessionException – If
load_projects()has not been called.
- get_projects() list[dict[str, Any]]
Fetch the list of projects via
GET /projects.- Returns:
A list of project dicts as returned by the REST API.
- get_redirect_target(resp)
Receives a Response. Returns a redirect URI or
None
- get_session_info() Response
Get the current session’s status.
Convenience alias for
get_sessions().
- get_sessions() Response
Retrieve session status via
GET /sessions.- Returns:
- get_sessions_userinfo() Response
Retrieve user information via
GET /sessions/userInfo.- Returns:
A
requests.Responsewhose JSON body contains user details.
- get_userinfo() Response
Get the current user’s information.
Convenience alias for
get_sessions_userinfo().
- head(url, **kwargs)
Sends a HEAD request. Returns
Responseobject.- Parameters:
url – URL for the new
Requestobject.**kwargs – Optional arguments that
requesttakes.
- Return type:
- load_projects() None
Fetch projects and populate
projects_by_name/projects_by_idlook-ups.After calling this method you can resolve project names to IDs with
get_project_id().
- login(username: str | None = None, password: str | None = None, api_key: str | None = None, application_type: int = 8) Response
Log in to the MicroStrategy REST API.
Convenience alias for
post_login(). If no credentials are provided the session attempts an anonymous connection.- Parameters:
username – MicroStrategy username or API key.
password – Password for standard authentication.
api_key – API key for trusted authentication.
application_type – MicroStrategy application type identifier.
- Returns:
A
requests.Responsefor the login request.
- logout() None
Log out and close the current REST API session.
Convenience alias for
post_logout().
- merge_environment_settings(url, proxies, stream, verify, cert)
Check the environment and merge it with some settings.
- Return type:
- mount(prefix, adapter)
Registers a connection adapter to a prefix.
Adapters are sorted in descending order by prefix length.
- options(url, **kwargs)
Sends a OPTIONS request. Returns
Responseobject.- Parameters:
url – URL for the new
Requestobject.**kwargs – Optional arguments that
requesttakes.
- Return type:
- patch(url, data=None, **kwargs)
Sends a PATCH request. Returns
Responseobject.- Parameters:
url – URL for the new
Requestobject.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request.**kwargs – Optional arguments that
requesttakes.
- Return type:
- post(url, data=None, json=None, **kwargs)
Sends a POST request. Returns
Responseobject.- Parameters:
url – URL for the new
Requestobject.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request.json – (optional) json to send in the body of the
Request.**kwargs – Optional arguments that
requesttakes.
- Return type:
- post_login(username: str | None = None, password: str | None = None, api_key: str | None = None, application_type: int = 8) Response
Create an authenticated session via
POST /auth/login.The login mode is inferred from which arguments are supplied:
usernameandpassword– standard auth (mode 1).usernameonly – trusted / API-key auth (mode 4096).Neither – anonymous auth (mode 8).
- Parameters:
username – MicroStrategy username or API key.
password – Password for standard authentication.
api_key – API key for trusted authentication.
application_type – MicroStrategy application type identifier.
- Returns:
A
requests.Responsefor the login request.- Raises:
requests.HTTPError – If the server returns a non-204 status.
- post_logout() None
Close the session via
POST /auth/logout.On success the auth token is removed from the session headers.
- prepare_request(request, *args, **kwargs)
Prepare the request after generating the complete URL.
- put(url, data=None, **kwargs)
Sends a PUT request. Returns
Responseobject.- Parameters:
url – URL for the new
Requestobject.data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the
Request.**kwargs – Optional arguments that
requesttakes.
- Return type:
- put_sessions() Response
Prolong the session via
PUT /sessions.- Returns:
- rebuild_auth(prepared_request, response)
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
- rebuild_method(prepared_request, response)
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
- rebuild_proxies(prepared_request, proxies)
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).
This method also replaces the Proxy-Authorization header where necessary.
- Return type:
- request(method: str, url: str, include_auth: bool = True, project_id: str | None = None, *args, **kwargs) Response
Send a request, injecting MicroStrategy headers automatically.
- Parameters:
method – HTTP method (
GET,POST, etc.).url – URL path relative to the session’s base_url.
include_auth – Attach the
X-MSTR-AuthTokenheader whenTrue(the default).project_id – If given, sent as the
X-MSTR-ProjectIDheader.*args – Passed through to
requests.Session.request().**kwargs – Passed through to
requests.Session.request().
- Returns:
- Raises:
LoginFailureException – On
ERR003responses.IServerException – On
ERR002/ERR0013responses.ResourceNotFoundException – On
ERR004responses.InvalidRequestException – On
ERR005/ERR006/ERR007.SessionException – On
ERR009responses.InsufficientPrivilegesException – On
ERR0014/ERR0017.ObjectAlreadyExistsException – On
ERR0015responses.MSTRException – On any other MicroStrategy error response.
- resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
Receives a Response. Returns a generator of Responses or Requests.
- send(request, **kwargs)
Send a given PreparedRequest.
- Return type:
- should_strip_auth(old_url, new_url)
Decide whether Authorization header should be removed when redirecting
- to_dict() Dict[str, Any]
Return a dict snapshot of the session state.
The dict contains
base_url,cookies, andheaders.
- update_from_json(data: Dict[str, Any] | str) None
Restore session state from a dict or JSON string.
- Parameters:
data – A dict (or JSON string) previously produced by
to_dict()orjson().- Raises:
SessionException – If required keys are missing from data.
- headers
A case-insensitive dictionary of headers to be sent on each
Requestsent from thisSession.
- auth
Default Authentication tuple or object to attach to
Request.
- proxies
Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each
Request.
- hooks
Event-handling hooks.
- params
Dictionary of querystring data to attach to each
Request. The dictionary values may be lists for representing multivalued query parameters.
- stream
Stream response content default.
- verify
SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing.
- cert
SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
- max_redirects
Maximum number of redirects allowed. If the request exceeds this limit, a
TooManyRedirectsexception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30.
- trust_env
Trust environment settings for proxy configuration, default authentication and similar.
- cookies
A CookieJar containing all currently outstanding cookies set on this session. By default it is a
RequestsCookieJar, but may be any othercookielib.CookieJarcompatible object.
- class mstr.requests.AuthenticatedMSTRRESTSession(base_url: str | Callable[[], str] | None = None, username: str | Callable[[], str] | None = None, password: str | Callable[[], str] | None = None, identity_token: str | Callable[[], str] | None = None, api_key: str | Callable[[], str] | None = None, application_type: int = 8)[source]
Bases:
MSTRRESTSessionContext-managed session that logs in on entry and out on exit.
All credential parameters accept a
Credential– either a plain string or a zero-argument callable returning a string. Callables are resolved when the context manager is entered, not at construction time. This enables integration with secrets managers and other deferred-lookup strategies.Example:
with AuthenticatedMSTRRESTSession( base_url="https://env.example.com/api/", username=lambda: fetch_username(), password=lambda: fetch_password(), ) as session: session.get("projects")
- Parameters:
base_url – MicroStrategy REST API root URL (or callable).
username – Username for standard authentication (login mode 1).
password – Password for standard authentication.
identity_token – Token for delegated authentication (login mode -1).
api_key – API key for trusted authentication (login mode 4096).
application_type – MicroStrategy application type identifier.
- mstr.requests.Credential = str | collections.abc.Callable[[], str] | None
Represent a PEP 604 union type
E.g. for int | str
Base session
- class mstr.requests.rest.base.MSTRBaseSession(base_url=None)[source]
Bases:
BaseUrlSessionLow-level session that manages auth-token headers and error translation.
Extends
BaseUrlSessionso that every request is automatically scoped to the MicroStrategy REST API base URL. Response headers beginning withX-MSTRare captured and stored on the session, and JSON error payloads are translated intoexceptionstypes.- request(method: str, url: str, include_auth: bool = True, project_id: str | None = None, *args, **kwargs) Response[source]
Send a request, injecting MicroStrategy headers automatically.
- Parameters:
method – HTTP method (
GET,POST, etc.).url – URL path relative to the session’s base_url.
include_auth – Attach the
X-MSTR-AuthTokenheader whenTrue(the default).project_id – If given, sent as the
X-MSTR-ProjectIDheader.*args – Passed through to
requests.Session.request().**kwargs – Passed through to
requests.Session.request().
- Returns:
- Raises:
LoginFailureException – On
ERR003responses.IServerException – On
ERR002/ERR0013responses.ResourceNotFoundException – On
ERR004responses.InvalidRequestException – On
ERR005/ERR006/ERR007.SessionException – On
ERR009responses.InsufficientPrivilegesException – On
ERR0014/ERR0017.ObjectAlreadyExistsException – On
ERR0015responses.MSTRException – On any other MicroStrategy error response.
Protocol
- class mstr.requests.rest.protocols.MSTRSessionProtocol(*args, **kwargs)[source]
Structural contract that all API mixins expect from the host session.
MSTRBaseSessionsatisfies this protocol via its inheritance fromBaseUrlSessionandrequests.Session.
Mixins
- class mstr.requests.rest.api.auth.AuthMixin[source]
Mixin providing MicroStrategy REST API authentication methods.
- post_login(username: str | None = None, password: str | None = None, api_key: str | None = None, application_type: int = 8) Response[source]
Create an authenticated session via
POST /auth/login.The login mode is inferred from which arguments are supplied:
usernameandpassword– standard auth (mode 1).usernameonly – trusted / API-key auth (mode 4096).Neither – anonymous auth (mode 8).
- Parameters:
username – MicroStrategy username or API key.
password – Password for standard authentication.
api_key – API key for trusted authentication.
application_type – MicroStrategy application type identifier.
- Returns:
A
requests.Responsefor the login request.- Raises:
requests.HTTPError – If the server returns a non-204 status.
- post_logout() None[source]
Close the session via
POST /auth/logout.On success the auth token is removed from the session headers.
- login(username: str | None = None, password: str | None = None, api_key: str | None = None, application_type: int = 8) Response[source]
Log in to the MicroStrategy REST API.
Convenience alias for
post_login(). If no credentials are provided the session attempts an anonymous connection.- Parameters:
username – MicroStrategy username or API key.
password – Password for standard authentication.
api_key – API key for trusted authentication.
application_type – MicroStrategy application type identifier.
- Returns:
A
requests.Responsefor the login request.
- logout() None[source]
Log out and close the current REST API session.
Convenience alias for
post_logout().
- delegate(identity_token: str) Response[source]
Authenticate with a delegated identity token via
POST /auth/delegate.- Parameters:
identity_token – A valid MicroStrategy identity token.
- Returns:
A
requests.Responsefor the delegate request.- Raises:
requests.HTTPError – If the server returns a non-204 status.
- class mstr.requests.rest.api.sessions.SessionsMixin[source]
Mixin providing MicroStrategy session-management endpoints.
- get_sessions_userinfo() Response[source]
Retrieve user information via
GET /sessions/userInfo.- Returns:
A
requests.Responsewhose JSON body contains user details.
- extend_session() Response[source]
Prolong the current session.
Convenience alias for
put_sessions().
- get_userinfo() Response[source]
Get the current user’s information.
Convenience alias for
get_sessions_userinfo().
- get_session_info() Response[source]
Get the current session’s status.
Convenience alias for
get_sessions().
- class mstr.requests.rest.api.projects.ProjectsMixin[source]
Mixin providing MicroStrategy project-related helpers.
- get_projects() list[dict[str, Any]][source]
Fetch the list of projects via
GET /projects.- Returns:
A list of project dicts as returned by the REST API.
- load_projects() None[source]
Fetch projects and populate
projects_by_name/projects_by_idlook-ups.After calling this method you can resolve project names to IDs with
get_project_id().
- get_project_id(project_name: str) str | None[source]
Return the project ID for project_name, or
Noneif not found.load_projects()must be called first.- Parameters:
project_name – The display name of the project.
- Raises:
SessionException – If
load_projects()has not been called.
- class mstr.requests.rest.mixins.SessionPersistenceMixin[source]
Mixin that adds serialisation and deserialisation to a session.
Allows a session (including its auth token and cookies) to be exported as JSON and later restored, which is useful for passing authenticated sessions between processes.
- to_dict() Dict[str, Any][source]
Return a dict snapshot of the session state.
The dict contains
base_url,cookies, andheaders.
- update_from_json(data: Dict[str, Any] | str) None[source]
Restore session state from a dict or JSON string.
- Parameters:
data – A dict (or JSON string) previously produced by
to_dict()orjson().- Raises:
SessionException – If required keys are missing from data.
- classmethod from_dict(session_dict: Dict[str, Any]) _T[source]
Create a new session instance from a dict snapshot.
Subclasses must accept
base_urlas their first constructor argument.- Parameters:
session_dict – A dict previously produced by
to_dict().- Returns:
A new session with state restored from session_dict.
Exceptions
- exception mstr.requests.rest.exceptions.MSTRException(message: str | None = None, *args, **kwargs)[source]
Bases:
ExceptionBase exception for all MicroStrategy REST API errors.
- code
The MicroStrategy error code (e.g.
ERR001), or"N/A".
- message
Human-readable error description.
- iserver_code
Optional I-Server error code, when present in the API response.
- iserver_message
Looked-up description for iserver_code.
- exception mstr.requests.rest.exceptions.MSTRUnknownException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised when the error response lacks a recognised
codefield.
- exception mstr.requests.rest.exceptions.LoginFailureException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised when authentication fails (
ERR003).
- exception mstr.requests.rest.exceptions.IServerException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised on Intelligence Server errors (
ERR002,ERR0013).
- exception mstr.requests.rest.exceptions.ResourceNotFoundException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised when a requested resource does not exist (
ERR004).
- exception mstr.requests.rest.exceptions.InvalidRequestException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised on invalid input or missing required fields (
ERR005,ERR006,ERR007).
- exception mstr.requests.rest.exceptions.SessionException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised when the session is invalid or has timed out (
ERR009).
- exception mstr.requests.rest.exceptions.InsufficientPrivilegesException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised when the user lacks required privileges or permissions (
ERR0014,ERR0017).
- exception mstr.requests.rest.exceptions.ObjectAlreadyExistsException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised when attempting to create an object that already exists (
ERR0015).
- exception mstr.requests.rest.exceptions.ExecutionCancelledException(message: str | None = None, *args, **kwargs)[source]
Bases:
MSTRExceptionRaised when a report or cube execution is cancelled.
Credential providers
AWS
AWS credential providers for Secrets Manager and SSM Parameter Store.
Requires boto3, which is installed automatically with the aws extra:
pip install mstr-rest-requests[aws]
Secrets Manager
secrets_manager()– returns a single-value callable, suitable when each secret holds one credential or you need to extract a single key from a JSON secret.SecretsManagerSecret– wraps a JSON secret containing multiple fields and caches the fetch so that all fields share a single API call.
SSM Parameter Store
parameter_store()– returns a single-value callable for one SSM parameter.ParameterStoreValues– groups several parameter paths and caches each fetch so that repeated resolutions of the same parameter do not make extra API calls.
- mstr.requests.credentials.aws.secrets_manager(secret_id: str, key: str | None = None, region_name: str | None = None) Callable[[], str][source]
Return a callable that fetches a value from AWS Secrets Manager when invoked.
The returned callable takes no arguments and returns a string.
boto3is imported lazily so it only needs to be installed when the callable is actually called.- Parameters:
secret_id – The ARN or name of the secret.
key – If the secret value is a JSON object, extract this key. When
Nonethe rawSecretStringis returned.region_name – AWS region override. When
Nonethe default boto3 session region is used.
- class mstr.requests.credentials.aws.SecretsManagerSecret(secret_id: str, region_name: str | None = None)[source]
Bases:
objectA single Secrets Manager secret containing multiple fields.
The secret is fetched lazily on the first
.field()resolution and cached so that all fields share one API call. Each.field(key)call returns a zero-argument callable compatible withCredential.Example:
secret = SecretsManagerSecret("my-secret-id") with AuthenticatedMSTRRESTSession( base_url=secret.field("base_url"), username=secret.field("username"), password=secret.field("password"), ) as session: ...
- Parameters:
secret_id – The ARN or name of the secret.
region_name – AWS region override. When
Nonethe default boto3 session region is used.
- mstr.requests.credentials.aws.parameter_store(name: str, region_name: str | None = None) Callable[[], str][source]
Return a callable that fetches an SSM Parameter Store value when invoked.
The returned callable takes no arguments and returns a string.
boto3is imported lazily so it only needs to be installed when the callable is actually called. Parameters are always fetched with decryption enabled so thatSecureStringparameters are returned in plain text.- Parameters:
name – The name or ARN of the parameter.
region_name – AWS region override. When
Nonethe default boto3 session region is used.
- class mstr.requests.credentials.aws.ParameterStoreValues(region_name: str | None = None)[source]
Bases:
objectA group of SSM Parameter Store parameters that share a cache.
Each
parameter()call returns a zero-argument callable compatible withCredential. Parameters are fetched individually on first resolution and cached so that subsequent resolutions of the same name do not make extra API calls.Example:
params = ParameterStoreValues() with AuthenticatedMSTRRESTSession( base_url=params.parameter("/myapp/base_url"), username=params.parameter("/myapp/username"), password=params.parameter("/myapp/password"), ) as session: ...
- Parameters:
region_name – AWS region override. When
Nonethe default boto3 session region is used.
Azure
Azure Key Vault credential providers.
Requires azure-identity and azure-keyvault-secrets, which are
installed automatically with the azure extra:
pip install mstr-rest-requests[azure]
Two helpers are provided:
key_vault()– returns a single-value callable for one Key Vault secret.KeyVaultSecret– wraps a JSON-valued Key Vault secret containing multiple fields and caches the fetch so that all fields share a single API call.
- mstr.requests.credentials.azure.key_vault(vault_url: str, secret_name: str, key: str | None = None) Callable[[], str][source]
Return a callable that fetches a value from Azure Key Vault when invoked.
The returned callable takes no arguments and returns a string.
azure-identityandazure-keyvault-secretsare imported lazily so they only need to be installed when the callable is actually called.Authentication uses
DefaultAzureCredential, which supports managed identity, environment variables, Azure CLI, and other methods automatically.- Parameters:
vault_url – The vault URL, e.g.
"https://my-vault.vault.azure.net/".secret_name – Name of the secret within the vault.
key – If the secret value is a JSON object, extract this key. When
Nonethe raw secret string is returned.
- class mstr.requests.credentials.azure.KeyVaultSecret(vault_url: str, secret_name: str)[source]
Bases:
objectA single Key Vault secret containing multiple JSON fields.
The secret is fetched lazily on the first
.field()resolution and cached so that all fields share one API call. Each.field(key)call returns a zero-argument callable compatible withCredential.Example:
secret = KeyVaultSecret( "https://my-vault.vault.azure.net/", "my-mstr-secret" ) with AuthenticatedMSTRRESTSession( base_url=secret.field("base_url"), username=secret.field("username"), password=secret.field("password"), ) as session: ...
- Parameters:
vault_url – The vault URL.
secret_name – Name of the secret within the vault.
GCP
Google Cloud Secret Manager credential providers.
Requires google-cloud-secret-manager, which is installed automatically
with the gcp extra:
pip install mstr-rest-requests[gcp]
Two helpers are provided:
secret_manager()– returns a single-value callable for one secret version.SecretManagerSecret– wraps a JSON-valued secret containing multiple fields and caches the fetch so that all fields share a single API call.
- mstr.requests.credentials.gcp.secret_manager(project: str, secret_id: str, version: str = 'latest', key: str | None = None) Callable[[], str][source]
Return a callable that fetches a value from GCP Secret Manager when invoked.
The returned callable takes no arguments and returns a string.
google-cloud-secret-manageris imported lazily so it only needs to be installed when the callable is actually called.Authentication uses Application Default Credentials (ADC).
- Parameters:
project – GCP project ID or number.
secret_id – Name of the secret.
version – Secret version (default
"latest").key – If the secret payload is a JSON object, extract this key. When
Nonethe raw payload string is returned.
- class mstr.requests.credentials.gcp.SecretManagerSecret(project: str, secret_id: str, version: str = 'latest')[source]
Bases:
objectA single GCP Secret Manager secret containing multiple JSON fields.
The secret is fetched lazily on the first
.field()resolution and cached so that all fields share one API call. Each.field(key)call returns a zero-argument callable compatible withCredential.Example:
secret = SecretManagerSecret("my-gcp-project", "my-mstr-secret") with AuthenticatedMSTRRESTSession( base_url=secret.field("base_url"), username=secret.field("username"), password=secret.field("password"), ) as session: ...
- Parameters:
project – GCP project ID or number.
secret_id – Name of the secret.
version – Secret version (default
"latest").