Retrieve API data with requests

ClaudeSjDevinHe
Comes here often

Retrieve API data with requests

Hi

I am trying to retrieve switch data via the Meraki API. Instructions and samples for the API's are here:

 

# https://dashboard.meraki.com/api_docs#return-a-switch-port

Sample Request

 

$ curl -L \
-H 'X-Cisco-Meraki-API-Key: <key>' \
-H 'Content-Type: application/json' \
-X GET 'https://dashboard.meraki.com/api/v0/devices/[serial]/switchPorts/[number]'

Sample Response

 

Successful HTTP Status: 200

{
  "number": 1,
  "name": "my port",
  "tags": "dorm-room limited",
  "enabled": true,
  "type": "access",
  "vlan": 10,
  "voiceVlan": 20,
  "poeEnabled": true,
  "isolationEnabled": false,
  "rstpEnabled": true,
  "stpGuard": "disabled",
  "accessPolicyNumber": "asdf1234",
  "linkNegotiation": "Auto negotiate"
}

I am using Python's requests instead of curl. My code is: (NOTE I have altered the serial number and API key just for this post. I use the correct values when I run the code)

 

import requests

headers = {
    'X-Cisco-Meraki-API-Key': '1111111111111111111111111111111111111111',
    'Content-Type': 'application/json',
}

# response = requests.get('https://dashboard.meraki.com/api/v0/devices/[serial]/switchPorts/[number]', headers=headers)
response = requests.get('https://dashboard.meraki.com/api/v0/devices/1111-2222-3333/switchPorts/1', headers=headers)
print(response)


# <Response [200]>

 

I am getting back <Response [200]> instead of the JSON data that the API above shows.

My HTTP Status is correct, however. What am I missing in order to actually get back the JSON data?

4 Replies 4
ww
Kind of a big deal
Kind of a big deal
RaphaelL
Kind of a big deal
Kind of a big deal

Hi ,

 

You simply have to do this : 

import requests

headers = {
    'X-Cisco-Meraki-API-Key': '1111111111111111111111111111111111111111',
    'Content-Type': 'application/json',
}

# response = requests.get('https://dashboard.meraki.com/api/v0/devices/[serial]/switchPorts/[number]', headers=headers)
response = requests.get('https://dashboard.meraki.com/api/v0/devices/1111-2222-3333/switchPorts/1', headers=headers)
print(response.text)

 

Which will print the response text as a string. If you want to use the json , you will have to load it (  switchports = json.loads(response.text) )  🙂 

 

Have fun !

Edgar-VO
Building a reputation

Hi,

 

Just wondering why you don't use the Meraki API set.... This is so much easier in python.

 

Ed

 

FabrizioRollo
Here to help

You could also try to get the responde as JSON

# print json content
print(response.json())

 

 

Look at the Response section of the guide:
https://docs.python-requests.org/en/latest/user/quickstart/

Get notified when there are additional replies to this discussion.