cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
606
Views
4
Helpful
2
Replies

Not able to print specifc hostnames from network-device

lagupta
Cisco Employee
Cisco Employee

I'm beginner and trying to write python to understand this more. if I remove the # from print I can see the nice long out put and I want to further code it to get only few items from that output. When I run this code I get error "TypeError: string indices must be integers"

this is my first post on forum so not sure if I can get help on this code or not, but any input to help me to fix the error and provide some education would be great !

import requests

import json

import sys

requests.packages.urllib3.disable_warnings()

url = "https://devnetapi.cisco.com/sandbox/apic_em/api/v1/ticket"

payload = {"username":"devnetuser","password":"Cisco123!"}

header = {"content-type":"application/json"}

output = requests.post(url,data=json.dumps(payload),headers=header,verify=False)

response_json = output.json()

ST = response_json['response']['serviceTicket']

headers = {"X-Auth-Token": ST}

ip = "https://devnetapi.cisco.com/sandbox/apic_em/api/v1/network-device"

response1 = requests.get(ip,headers=headers,verify=False)

network_Devices = response1.json()

#print(json.dumps(network_Devices,indent=4))

devices_list = []

for item in network_Devices:

    devices_list.append([item["hostname"],item["managementIpAddress"],item["type"],item["id"]])

print (devices_list)

2 Replies 2

yawming
Cisco Employee
Cisco Employee

The response JSON from requests.get(ip,headers=headers,verify=False) is


{

    "response": [

        {

            "apManagerInterfaceIp": "",

            "type": "Cisco Catalyst 2960C-8PC-L Switch",

            "upTime": "1 day, 2:20:31.50",

            "locationName": null,

            "memorySize": "59556224",

            "lastUpdateTime": 1467837623914,

We actually just need everything inside "response":[

....

So we use "network_Devices = response1.json()["response"]" instead.

print(json.dumps(response1.json(),indent=4))

network_Devices = response1.json()["response"]

print(json.dumps(network_Devices,indent=4))

devices_list = []

for item in network_Devices:

    devices_list.append([item["hostname"],item["managementIpAddress"],item["type"],item["id"]])

print (devices_list)

To print network device list in pretty format please refer to this learning lab session


Cisco DevNet Learning Labs


Lab 2: Network Device Related APIs

Thank you, Yawchen. It was very helpful.

.:|:.:|:.

CISCO Lalit Gupta | Systems Engineer - Sales| Single # Reach: +1 408 895 8379 | lagupta@cisco.com<mailto:lagupta@cisco.com>