I have this script to make an API call using the meraki python module to query a Meraki device.
I'm trying to add some error handling in the code so that if the API call comes back with an error code, it will do something else. I cannot seem to figure out what to do.
Here is my simple code to just query a device:
import meraki
import requests
API_KEY = 'API_KEY'
dashboard = meraki.DashboardAPI(API_KEY)
serial = input("What is the serial number?")
print(f"{serial}")
response = (dashboard.devices.getDevice(serial))
When I run the script it will return either a "200 OK" or "404 Not Found"
Terminal window response:
C:\Scripts\Meraki\dev> python .\getdevice.py
What is the serial number? XXXX-XXXX-XXXX
2023-04-26 18:32:52 meraki: INFO > GET https://api.meraki.com/api/v1/devices/XXXX-XXXX-XXXX
2023-04-26 18:32:53 meraki: INFO > devices, getDevice - 200 OK
or
2023-04-26 18:41:09 meraki: INFO > GET https://api.meraki.com/api/v1/devices/XXXX-XXXX-XXXX
2023-04-26 18:41:10 meraki: ERROR > devices, getDevice - 404 Not Found, b''
The purpose of this script is to check to see if the serial number has already been assigned to a user / network. If it is available, I'll get a "404 Not Found" and if it has already been assigned to someone, I'll get a "404 Not Found".
How can I detect and handle the 404 case?
I'm assuming you are using the meraki
package with the source code at https://github.com/meraki/dashboard-api-python/tree/main/meraki.
According to that, if a 404 response occurs, getDevice
should raise an APIError
exception. It contains details about the error in the status
, reason
, and message
attributes (see https://github.com/meraki/dashboard-api-python/blob/main/meraki/exceptions.py) – your log output shows the result of APIError.__repr__
which includes these attributes.
You can handle it by using a try
/except
statement:
from meraki import APIError
# ...
try:
response = dashboard.devices.getDevice(serial)
except APIError as e:
print(e.status)
print(e.reason)
print(e.message)
If you need to handle the 404 case specifically, you can use an if
statement:
if e.status == 404:
# ...