nasonov
nasonov

Reputation: 125

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
    }
}

Upvotes: 0

Views: 354

Answers (1)

nasonov
nasonov

Reputation: 125

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.

Upvotes: 1

Related Questions