Package: mistapi
MISTAPI - Python Package to use MIST APIMIT LICENSECopyright (c) 2023 Thomas MunzerPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the  Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.FeaturesThis package is build from theMist OpenAPI specificationsand is designed to simplify the use of the Mist APIs with Python scripts.Manage Mist Authentication with login/password (and 2FA if required) or API TokenProvide interactive user inputs for login and org/site selectionsProvide easy access to Mist APIs endpoints and documentationInstallationThis Python Package can be install withpip:# Linux/macOSpython3-mpipinstallmistapi# Windowspy-mpipinstallmistapiUpgrade# Linux/macOSpython3-mpipinstall--upgrademistapi# Windowspy-mpipinstall--upgrademistapiConfigurationConfiguration is optional. All the required information can be passed as APISession parameter.
However, it is possible to set them in an.envfile. The location of this file must be provided during when calling the APISession class with theenv_fileparameter:>importmistapi>apisession=mistapi.APISession(enf_file="path/to/the/.env")Environment VariablesVariable NameTypeDefaultCommentMIST_HOSTstringNoneThe Mist Cloud to use. It must be the "api" one (e.g.api.mist.com,api.eu.mist.com, ...)MIST_APITOKENstringNoneThe API Token to use.MIST_USERstringNoneThe login to use if no API Token is provided (apitoken use is prefered)MIST_PASSWORDstringNoneThe password to use if no API Token is provided (apitoken use is prefered)CONSOLE_LOG_LEVELint20The minimum log level to display on the console, usingloggingschema (0 = Disabled, 10 = Debug, 20 = Info, 30 = Warning, 40 = Error, 50 = Critical)LOGGING_LOG_LEVELint10The minimum log level to log on the file, usingloggingschema (0 = Disabled, 10 = Debug, 20 = Info, 30 = Warning, 40 = Error, 50 = Critical). This is only used when the script callingmistapiis using Pythonloggingpackage and is configured to log to a fileAn example of the environment file content is:MIST_HOST = api.mist.com
MIST_APITOKEN = xxxxxxUsageUsage examples are available in themist_library repository.To use it,1.APISessionmust be instanciated:>>>importmistapi>>>apisession=mistapi.APISession()This class accepts different parameters, all optionals:Parameter NameTypeDefaultCommentemailstrNoneused if login/password is used. Can be defined laterpasswordstrNoneused if login/password is used. Can be defined laterapitokenstrNoneused if API Token is used. Can de defined laterhoststrNoneMist Cloud to reach (e.g. "api.mist.com"). Can de defined laterenv_filestrNonepath to the env file to load. See README.md for allowed variablesconsole_log_leveint20The minimum log level to display on the console, usingloggingschema (0 = Disabled, 10 = Debug, 20 = Info, 30 = Warning, 40 = Error, 50 = Critical)logging_log_leveint10The minimum log level to log on the file, usingloggingschema (0 = Disabled, 10 = Debug, 20 = Info, 30 = Warning, 40 = Error, 50 = Critical). This is only used when the script callingmistapiis using Pythonloggingpackage and is configured to log to a file2.login()function must be called to validate the authentication.2.1. If the env file is provided and all the required information are valid, the session is validated:>>>importmistapi>>>apisession=mistapi.APISession(env_file="~/.mist_env")>>>apisession.login()--------------------------------Authenticated---------------------------------WelcomeThomasMunzer!>>>apisession.get_authentication_status()True2.2. If the env file is not provided or does not contain the required valid information, the missing information will be requested:If nohosthas been configured, an interactive input will ask for it.>>>apisession.login()-----------------------------MistCloudSelection-----------------------------0)APAC01(host:api.ac5.mist.com)1)Europe01(host:api.eu.mist.com)2)Global01(host:api.mist.com)3)Global02(host:api.gc1.mist.com)4)Global03(host:api.ac2.mist.com)5)Global04(host:api.gc2.mist.com)SelectaCloud(0to5,orqtoexit):if not authentication (apitokenoremail/password) has been configured, an interactive input will ask for it. If login/password authentication is used and 2FA is requested by the Mist Cloud, the 2FA code will be asked.>>>apisession.login()---------------------------Login/Pwdauthentication---------------------------Login:tmunzer@juniper.netPassword:[INFO]Authenticationsuccessful!TwoFactorAuthenticationcoderequired:122749[INFO]2FAauthenticationsuccessed--------------------------------Authenticated---------------------------------WelcomeThomasMunzer!3. It is now possible to request Mist APIs>>>device_models=mistapi.api.v1.const.device_models.getDeviceModels(apisession)>>>device_models.url'https://api.mist.com/api/v1/const/device_models'>>>device_models.status_code200>>>device_models.data[{'model':'AP41','type':'ap','ap_type':'aph','description':'AP-41','display':'AP41','has_wifi_band5':True,'has_wifi_band24':True,'has_scanning_radio':True,'has_usb':True,'has_vble':True,'vble':{'power':8,'beacon_rate':4,'beams':8},'band24':{'max_clients':128,'max_power':19,'min_power':8},'fcc_dfs_ok':...Usefull functionseasily find an Org Id from the current account withmistapi.cli.select_org(apisession)>>>mistapi.cli.select_org(apisession)Availableorganizations:0)000_TM-LAB(id:6374a757-xxxx-xxxx-xxxx-361e45b2d4ac)...41)TM-LAB(id:203d3d02-xxxx-xxxx-xxxx-76896a3330f4)...SelectanOrg(0to44,orqtoexit):41['203d3d02-xxxx-xxxx-xxxx-76896a3330f4']easily find a Site Id from an org  withmistapi.cli.select_org(apisession)>>>mistapi.cli.select_site(apisession,org_id="203d3d02-xxxx-xxxx-xxxx-76896a3330f4")Availablesites:0)HLAB(id:f5fcbee5-xxxx-xxxx-xxxx-1619ede87879)...SelectaSite(0to6,orqtoexit):0['f5fcbee5-xxxx-xxxx-xxxx-1619ede87879']get the next page or all the pages from a request
For some requests, the Mist Cloud is using pagination to limit the size of the response. The required information the find the next page can either in the HTTP header (headersX-Page-Total,X-Page-LimitandX-Page-Page) or with thenextkey in the json document. To make it easier to request the next page or all the pages, themistapipackage is prossessing the response to extract or generate the URI to retrieve the next page.>>>response=mistapi.api.v1.orgs.clients.searchOrgClientsEvents(apisession,my_org_id,duration="1d")>>>len(response.data["results"])100>>>response.next'/api/v1/orgs/203d3d02-xxxx-xxxx-xxxx-76896a3330f4/clients/events/search?end=1676966894&limit=100&search_after=%5B1676966519626%5D&start=1676880494'To get the next page, use themistapi.get_next()function. The returned response will be the same format as the previous one:>>>response_1=mistapi.api.v1.orgs.clients.searchOrgClientsEvents(apisession,my_org_id,duration="1d")>>>len(response_1.data["results"])100>>>response_1.next'/api/v1/orgs/203d3d02-xxxx-xxxx-xxxx-76896a3330f4/clients/events/search?end=1676966894&limit=100&search_after=%5B1676966519626%5D&start=1676880494'>>>response_2=response.get_next(apisession,response_1)>>>response_2.next'/api/v1/orgs/203d3d02-xxxx-xxxx-xxxx-76896a3330f4/clients/events/search?end=1676966894&limit=100&search_after=%5B1676966204625%5D&start=1676880494'>>>len(response_2.data["results"])100To retrieve all the pages, use themistapi.get_all()function. The returned response will be a list with the concatained data from all the Mist responses:>>>response=mistapi.api.v1.orgs.clients.searchOrgClientsEvents(apisession,my_org_id,duration="1d")>>>len(response.data["results"])100>>>response.next'/api/v1/orgs/203d3d02-xxxx-xxxx-xxxx-76896a3330f4/clients/events/search?end=1676966894&limit=100&search_after=%5B1676966519626%5D&start=1676880494'>>>data=mistapi.get_all(apisession,response)>>>len(data)26027get help on a specific function>>>help(mistapi.api.v1.orgs.stats.getOrgStats)HelponfunctiongetOrgStatsinmodulemistapi.api.v1.orgs.stats:getOrgStats(mist_session:mistapi.__api_session.APISession,org_id:str,page:int=1,limit:int=100,start:int=None,end:int=None,duration:str='1d')->mistapi.__api_response.APIResponseAPIdoc:https://doc.mist-lab.fr/#operation/getOrgStatsPARAMS-----------:paramAPISessionmist_session-mistapisessionincludingauthenticationandMisthostinformationPATHPARAMS-----------:paramstrorg_idQUERYPARAMS------------:paramintpage:paramintlimit:paramintstart:paramintend:paramstrduration(1d,1h,10m)RETURN-----------:returnAPIResponse-responsefromtheAPIcall