

- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
I have seen a number of questions on the best way to authenticate a REST API call on DNA-Center.
The documentation on the DNA-C indicates that /api/system/v1/auth/token is the way to get an authentication token in a cookie.
For those writing python code or using postman, there is a simpler way to get an authentication token.
The API call /api/system/v1/auth/login uses basic authentication and returns a token in a JSON payload.
Here is an simple example in the Python REPL. First we setup the required imports (requests) and the URL for authentication along with the header.
>>> import requests
>>> from requests.auth import HTTPBasicAuth
>>> import json
>>> url = "https://adam-dnac/api/system/v1/auth/token"
>>> headers = {'content-type': 'application/json'}
We can now make a POST API call, using basic authentication and then print out the token.
>>> resp = requests.post(url, auth=HTTPBasicAuth(username='admin', password='password'), headers=headers,verify=False)
>>>
>>> token = resp.json()['Token']
>>> print token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1YTIwMjExY2I2MjZjOTAwOGUzMDc1NjMiLCJhdXRoU291cmNlIjoiaW50ZXJuYWwiLCJ0ZW5hbnROYW1lIjoiVE5UMCIsInJvbGVzIjpbIjVhMjAyMGU2NDQzYmE4OWZiNWQ1ZWQ0MiJdLCJ0ZW5hbnRJZCI6IjVhMjAyMTFiYjYyNmM5MDA4ZTMwNzU2MiIsImV4cCI6MTUyNTIwMzgwOCwidXNlcm5hbWUiOiJhZG1pbiJ9
This token will be required in a header for future API calls. It needs to be used in a header called x-auth-token. I add the token to the header and I can now make authenticated API calls. This token is valid for sixty minutes, then you will need to repeat the step above.
>>> headers['x-auth-token'] = token
>>> network_device_count = requests.get('https://adam-dnac/api/v1/network-device/count', headers=headers, verify=False)
>>> print network_device_count.json()
{u'version': u'1.0', u'response': 74}
Success!! There are 74 network devices on this controller.
For more examples of python code, please see the DevNet DNA-C learning labs https://learninglabs.cisco.com/lab/dnac-basic/step/1
I have posted a range of example in my github repository https://github.com/CiscoDevNet/dnac-samples-aradford
Good luck with the DNA-Center APIs.
Adam
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.