I'm using Google Sheets API v4.
I have tested with some sheets and my code is working but with some it's not. All I'm doing is to swap out the sheets ID.
I use the code found here:
https://developers.google.com/sheets/quickstart/dotnet
All sheets I tested I can read and edit in my browser. The error I'm faced is:
Google.Apis.Requests.RequestError\r\nThe caller does not have permission [403]\r\nErrors [\r\n\tMessage[The caller does not have permission] Location[ - ] Reason[forbidden] Domain[global]\r\n]\r\n
What would be the steps to debug such issue?
Here is the complete source code:
public class Google_Sheets
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
static string ApplicationName = "Google Sheets API Quickstart";
public static void Test()
{
UserCredential credential;
using (var stream =
new FileStream("Google Drive\\client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define request parameters.
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
// working
//String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
//String range = "Class Data!A2:E";
// not working
String spreadsheetId = "1KJtvpd8iROI7cZ-7--fyoTXTLjzdb8ZghmmQOWkKsh4";
String range = "Sheet1!A1:G";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
Console.WriteLine("Name, Major");
foreach (var row in values)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
}
Turns out my problems was that I was logged in two different Google accounts. I suppose that my tool then asked the wrong Google account for a token.
To fix the issue I did:
Not tested, but I assume when the sheet in question is accessible across all Google accounts I would not have any issues.