'Handling varying API response Dtype
Given a basic API call -
response = requests.post(url, auth=HTTPBasicAuth(key, secret), headers=headers, data=d)
return(response.json())
How would you handle the response if the Dtype varied? E.g., sometimes json, sometimes .xlsx [binary]?
Context: I want to create a function that tests 3x criteria:
- Response is JSON object containing
percent_complete- if TRUE, then thepercent_completevalue is used to add to a progress bar. Thisapir_responsetells me the requested data isn't ready yet and takespercent_completevalue to update a progress bar. - Response is JSON object containing
meta- if TRUE, then the requested data has been returned as a JSON object, andapi_responseshould be returned, ready to be used in another function. - Response is an
.xlsxfile (binary??) - if TRUE, then the requested data has been returned in.xlsxformat, andapi_responseshould be returned, ready for use in another function.
Any suggestions would be welcome?
Solution 1:[1]
You could use try and except for that:
response = requests.post(url, auth=HTTPBasicAuth(key, secret), headers=headers, data=d)
try:
data = response.json()
# No exceptions here means that we get and parse valid json
if 'percent_complete' in data:
"""Handle option 1 here."""
elif 'meta' in data:
"""Handle option 2 here."""
else:
# Unknown format, so return None
return None
except:
# Data is non json, as exception occured
"""Try handling option 3 here by accessing `response.content`."""
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Kosh |
