Search code examples
pythonapiresponsedtype

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:

  1. Response is JSON object containing percent_complete - if TRUE, then the percent_complete value is used to add to a progress bar. This apir_response tells me the requested data isn't ready yet and takes percent_complete value to update a progress bar.
  2. Response is JSON object containing meta - if TRUE, then the requested data has been returned as a JSON object, and api_response should be returned, ready to be used in another function.
  3. Response is an .xlsx file (binary??) - if TRUE, then the requested data has been returned in .xlsx format, and api_response should be returned, ready for use in another function.

Any suggestions would be welcome?


Solution

  • 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`."""