Search code examples
swiftmacosoauth-2.0google-sheets-apigoogle-oauth

Calling Google Sheets API in Swift with GTMAppAuth


I'm trying to read/write to Google Sheets in Swift on macOS. I'm using the GAppAuth library which in turn makes use of GTMAppAuth.

I managed to get authorized and get back both the access token and the refresh token but I still get an HTTP status code of 403 when I try to make a call to one of the Google Sheets' endpoints.

In applicationDidFinishLaunching(_:) I appended the following authorization scope, as detailed in the documentation:

GAppAuth.shared.appendAuthorizationRealm("https://www.googleapis.com/auth/spreadsheets.readonly")

But still, I get 403. What am I doing wrong? Am I adding the scope properly?

This is the code where I make the API call:

@IBAction func getSpreadsheet(_ sender: NSButton) {
    
    let fetcherService = GTMSessionFetcherService()
    fetcherService.authorizer = authorization
    let spreadsheetInfo = URL(string: "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetID}")
    let fetcher = GTMSessionFetcher(url: spreadsheetInfoEndpoint)
    fetcher.beginFetch { (data, error) in
        //Error code 403
    }
}

Solution

  • I got it working by looking at the cURL request with the Google API Explorer. The access token parameter was missing:

    https://sheets.googleapis.com/v4/spreadsheets/[SPREADSHEETID]/values/[RANGE]?access_token=[access_token]
    

    Also thanks to Jacques-Guzel Heron, in the comment section, who let me know of the official Google Auth Library for Swift. I'll check it out.