MarkS
MarkS

Reputation: 1539

Retrieve API data with requests

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?

Upvotes: 0

Views: 3113

Answers (5)

Kumar Pankaj Dubey
Kumar Pankaj Dubey

Reputation: 2297

To access curl using python, you can run this:

import requests

headers = {
'accept': 'text/html',
'Cookie': 'token=5e1a8b55b0249136a60423aa02b9120a845fa4122ac98ce4e771aec5d772d7d7a18ac22f18cd47727d00bddc2ebcc5cddf8a402d7a302ddffdeb7c6e15cb2a7005f857112',
}

response = requests.get("http://link-ui3.enter.com/data/1.0/auth/getUserByToken", headers=headers)

print(response.status_code)

Upvotes: 0

user1004586
user1004586

Reputation: 1

With .content & json.loads you should be able to parse JSON

import requests,json

response = requests.get('https://dashboard.meraki.com/api/v0/devices/1111-2222-3333/switchPorts/1')

json = json.loads(response.content)

print(json.get('name'))

Upvotes: 0

Asif Ahmed
Asif Ahmed

Reputation: 9

print (r.json)
# You will get your json response

Upvotes: -1

Daniel
Daniel

Reputation: 395

Use print(response.content) instead of print(response).

If you want to save the data in a file, you can use:

content=response.content
data=open("name_you_want.json","wb")
data.write(content)
data.close()

Upvotes: 1

elrich bachman
elrich bachman

Reputation: 176

use print (response.text) instead of print(response) because its printing response status code instead of body text and i guess you want to print response body

Upvotes: 1

Related Questions