Search code examples
pythongoogle-apigoogle-drive-apigoogle-sheets-apigoogle-api-python-client

Google Sheets API: Exception vs. Json in response body


I am lost in error handling with Google Sheets API.

The Sheets API reference page does not provide any example of error handling.

This SO question points to a doc page saying:

The Drive API returns two levels of error information:

HTTP error codes and messages in the header.

A JSON object in the response body with additional details that can help you determine how > to handle the error.

Drive apps should catch and handle all errors that might be encountered when using the REST > API. This guide provides instructions on how to resolve specific API errors.

and then lists an example of json response for 404

However when I run with a nonexistent spreadsheet_id the following code (it works fine on a correct spreadsheet_id):

request = service.spreadsheets().get(
            spreadsheetId=spreadsheet_id,
            ranges=ranges,
    )

response = request.execute()

I get an exception raised, rather than an error in json response:

  File ".../lib/python3.8/site-packages/googleapiclient/http.py", line 915, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://sheets.googleapis.com/v4/spreadsheets/1Z2aQvO122lBxHyditlDT6KhSAqkiUeX8zqJ4ysIJHd?alt=json returned "Requested entity was not found.". Details: "Requested entity was not found.">

and it seems I can't even extract an error code without parsing a string.

So, the question is: how to correctly handle sheets api errors? I think I'd prefer to always get a json and catch an exception for truly technical errors such a bad connectivity etc.

Thanks in advance!


Solution

  • I believe your goal and your current situation as follows.

    • When an error occurs with Sheets API, you want to retrieve the error message from Sheets API as JSON data.
    • You want to achieve this using googleapis with python.
    • You have already been able to use Sheets API using googleapis for python.

    In this case, how about using try, except? The sample script is as follows.

    Sample script:

    from googleapiclient.errors import HttpError # <--- In this case, please add this.
    
    try:
    
        # This is your script.
        request = service.spreadsheets().get(
            spreadsheetId=spreadsheet_id,
            ranges=ranges,
        )
    
        response = request.execute()
        print(response)
    
    except HttpError as err:
        e = json.loads(err.content.decode("utf-8"))
        print(e)
    
    • In this sample script, when spreadsheet_id is the valid value, the returned value can be seen with print(response). When spreadsheet_id is the invalid value, the error message can be seen with print(e). The sample value of print(e) is as follows.

        {'error': {'status': 'NOT_FOUND', 'message': 'Requested entity was not found.', 'code': 404, 'errors': [{'domain': 'global', 'message': 'Requested entity was not found.', 'reason': 'notFound'}]}}
      

    Note:

    • In this sample script, it supposes that your service can be used for retrieving the values from Google Spreadsheet using Sheets API. Please be careful this.

    Reference: