netbox-community / pynetbox

Python API client library for Netbox.
Apache License 2.0
538 stars 165 forks source link

Get filtering on non existent device_id raises RequestError when it should return None #614

Open pthmas opened 1 month ago

pthmas commented 1 month ago

pynetbox version

v7.3.3

NetBox version

v3.7.8

Python version

3.10

Steps to Reproduce

When trying to get an interface while filtering on device_id, if the device_id doesn't exist a 400 BadRequest response is being raised.

>>> interface = nb.dcim.interfaces.get(name="Ethernet9", device_id=99)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.10/site-packages/pynetbox/core/endpoint.py", line 161, in get
    ret = next(resp, None)
  File "/usr/local/lib/python3.10/site-packages/pynetbox/core/response.py", line 127, in __next__
    next(self.response), self.endpoint.api, self.endpoint
  File "/usr/local/lib/python3.10/site-packages/pynetbox/core/query.py", line 291, in get
    req = self._make_call(add_params=add_params)
  File "/usr/local/lib/python3.10/site-packages/pynetbox/core/query.py", line 258, in _make_call
    raise RequestError(req)
pynetbox.core.query.RequestError: The request failed with code 400 Bad Request: {'device_id': ['Select a valid choice. 99 is not one of the available choices.']}

Expected Behavior

If the device id doesn't exist then None should be returned, as it would for any other get call.

>>> interface = nb.dcim.interfaces.get(name="Ethernet9", device_id=99)
>>> interface == None
True

Observed Behavior

Seems that device_id is being used as a choice when it should not be.

markkuleinio commented 1 month ago

Works here:

>>> pynetbox.__version__
'7.3.3'
>>> netbox.status()["netbox-version"]
'3.7.3'
>>> interface = netbox.dcim.interfaces.get(name="Loopback", device_id=1222)
>>> interface
Loopback
>>>
pthmas commented 1 month ago

It does work for me when the device_id exist but not when it doesn't. Does it also work for you if the device_id doesn't exist?

markkuleinio commented 1 month ago

Oh, sorry, I misread your issue.

When you test the API you see that pynetbox just returns what NetBox returns:

$  curl -i -H "Content-Type: application/json" -H "Authorization: Token xxxxxxxxxxx" \
https://netbox.example.com/api/dcim/interfaces/?device_id=99
HTTP/2 400
api-version: 3.7
...

{"device_id":["Select a valid choice. 99 is not one of the available choices."]}
$

So if you feel this is an error, then raise an issue in the NetBox repository.

pthmas commented 1 month ago

Thanks for your input. I only raised this issue because we have a test in our stack using the exact query I used in the example, this query used to return None and now returns BadRequestError. This change happened when I both upgraded, pynetbox and Netbox. I'll consider opening an issue on the Netbox repo then!