MisterMagister
MisterMagister

Reputation: 71

How to make Google Calendar API Requests using javascript and a service account?

I followed this quickstart tutorial for the Google Calendar API using javascript in my web application. As I need the possibility to show Calendar data on the webpage without user login, I need to implement API calls using a Service Account. Unfortunately I cant't find any good tutorials or explanations for doing so in javascript and since I am fairly new to the subject of API programming I kind of need some guidance.

Ty in advance.

Upvotes: 6

Views: 1764

Answers (1)

Fuad
Fuad

Reputation: 76

Using Service account on client side is not secure. You may want to switch to a server side implementation for that. Assuming you are familiar with javascript I suggest to follow NodeJS implementation from here.

To create Service Account select service account after step 1->a. Refer this image for option.

To use Service Account replace the authorize() logic with this

var email = credentials.client_email;
var key = credentials.private_key;

const jwt = new google.auth.JWT(
  email, null, key, SCOPES
);

jwt.authorize((err, data) => {
  if (err) {
    console.error(err);
    throw err;
  }    
  console.log('You have been successfully authenticated: ', data);

  callback(jwt);
});

As you are using Service Account you also need to create a calendar in your Gmail account to use. Then go to settings and select Add People to share it with client_email from your json, then use your Calendar Id (from Calendar settings) in API Call replacing primary

Upvotes: 3

Related Questions