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_complete
value is used to add to a progress bar. Thisapir_response
tells me the requested data isn't ready yet and takespercent_complete
value 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_response
should be returned, ready to be used in another function. - Response is an
.xlsx
file (binary??) - if TRUE, then the requested data has been returned in.xlsx
format, andapi_response
should be returned, ready for use in another function.
Any suggestions would be welcome?
CodePudding user response:
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`."""