Skip to content

Instantly share code, notes, and snippets.

Created February 15, 2021 09:15
Show Gist options
  • Save NWMichl/aed4b582f3f922b5e515751d6fa6d6c1 to your computer and use it in GitHub Desktop.
Save NWMichl/aed4b582f3f922b5e515751d6fa6d6c1 to your computer and use it in GitHub Desktop.
Query the Cisco ACI APIC API using Python & requests
import requests, json
apic_url = ''
apic_username = 'admin'
apic_password = 'ciscopsdt'
def apic_login(apic: str, username: str, password: str) -> dict:
""" APIC login and return session cookie """
apic_cookie = {}
credentials = {'aaaUser': {'attributes': {'name': apic_username, 'pwd': apic_password }}}
json_credentials = json.dumps(credentials)
base_url = 'https://' + apic + '/api/aaaLogin.json'
login_response =, data=json_credentials)
login_response_json = json.loads(login_response.text)
token = login_response_json['imdata'][0]['aaaLogin']['attributes']['token']
apic_cookie['APIC-Cookie'] = token
return apic_cookie
def apic_query(apic: str, path: str, cookie: dict) -> dict:
""" APIC 'GET' query and return response """
base_url = 'https://' + apic + path
get_response = requests.get(base_url, cookies=cookie)
return get_response
def apic_logout(apic: str, cookie:dict) -> dict:
""" APIC logout and return response """
base_url = 'https://' + apic + '/api/aaaLogout.json'
post_response =, cookies=cookie)
return post_response
apic_cookie = apic_login(apic=apic_url, username=apic_username, password=apic_password)
response = apic_query(apic=apic_url, path='/api/class/fabricHealthTotal.json', cookie=apic_cookie)
logout_response = apic_logout(apic=apic_url, cookie=apic_cookie)
response_json = json.loads(response.text)
fab_health_total = response_json['imdata'][0]['fabricHealthTotal']['attributes']['cur']
Copy link

nnelluri928 commented Sep 14, 2021


I see below error while executing the script, I am not sure whether password is correct or Not 'ciscopsdt'.
could you please check and let me know, Appreciate your effort for creating the script.
I am not able Login to sandbox with mentions username/password.

pyATS35] [nnelluri@sjc-xdm-041 ~]$ python3
Traceback (most recent call last):
File "", line 38, in
apic_cookie = apic_login(apic=apic_url, username=apic_username, password=apic_password)
File "", line 18, in apic_login
token = login_response_json['imdata'][0]['aaaLogin']['attributes']['token']
KeyError: 'aaaLogin'
[pyATS35] [nnelluri@sjc-xdm-041 ~]$

Copy link

The output you've presented informs you about the wrong username or password or both
There is no IP address validation and wrong credentials are not handled in the code posted, therefore you are expected to provide the correct credentials to get the result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment