Skip to content

Commit 5531f59

Browse files
Merge pull request #1366 from allmightyspiff/vivification
Updated documentation on how to deal with KeyError
2 parents 6a62dd7 + 1ae2c95 commit 5531f59

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

docs/api/client.rst

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,42 @@ If you ever need to figure out what exact API call the client is making, you can
202202
print(client.transport.print_reproduceable(call))
203203

204204

205+
Dealing with KeyError Exceptions
206+
--------------------------------
207+
208+
One of the pain points in dealing with the SoftLayer API can be handling issues where you expected a property to be returned, but none was.
209+
210+
The hostname property of a `SoftLayer_Billing_Item <https://sldn.softlayer.com/reference/datatypes/SoftLayer_Billing_Item/#hostname>`_ is a good example of this.
211+
212+
For example.
213+
214+
::
215+
216+
# Uses default username and apikey from ~/.softlayer
217+
client = SoftLayer.create_client_from_env()
218+
# iter_call returns a python generator, and only makes another API call when the loop runs out of items.
219+
result = client.iter_call('Account', 'getAllBillingItems', iter=True, mask="mask[id,hostName]")
220+
print("Id, hostname")
221+
for item in result:
222+
# will throw a KeyError: 'hostName' exception on certain billing items that do not have a hostName
223+
print("{}, {}".format(item['id'], item['hostName']))
224+
225+
The Solution
226+
^^^^^^^^^^^^
227+
228+
Using the python dictionary's `.get() <https://docs.python.org/3/library/stdtypes.html#dict.get>`_ is great for non-nested items.
229+
230+
::
231+
print("{}, {}".format(item.get('id'), item.get('hostName')))
232+
233+
Otherwise, this SDK provides a util function to do something similar. Each additional argument passed into `utils.lookup` will go one level deeper into the nested dictionary to find the item requested, returning `None` if a KeyError shows up.
234+
235+
::
236+
itemId = SoftLayer.utils.lookup(item, 'id')
237+
itemHostname = SoftLayer.utils.lookup(item, 'hostName')
238+
print("{}, {}".format(itemId, itemHostname))
239+
240+
205241
API Reference
206242
-------------
207243

0 commit comments

Comments
 (0)