Abhishek Ranjan
Abhishek Ranjan

Reputation: 497

How to call Google Tasks API from javascript?

I amtrying to call Google Tasks API for a app I'm building.When I make the call using Google's client libraries, it succeeds and return what is expected.

function getAllTasks() {
gapi.client.tasks.tasks.list({
    tasklist: 'MDIxODc1MzEwNzc4MzMxNDU2MTU6MDow'
}).then(function (response) {
    console.log(response);
    var arr = response.result.items;
    console.log(arr);
    for(var j=0;j<arr.length;j++){
        console.log(arr[j].title);
    }
})
}

But when I do the same using jQuery, I get 404 with the text "Login Requied" in the response body.

function getAllTasksJquery() {
$.get("https://content.googleapis.com/tasks/v1/lists/MDIxODc1MzEwNzc4MzMxNDU2MTU6MDow/tasks",function (data,status) {
    console.log(data,status);
    var arr = data.result.items;
    console.log(arr);
    for(var j=0;j<arr.length;j++) {
        console.log(arr[j].title);
    }
});

}

Can someone tell me what am I doing wrong ?

Upvotes: 0

Views: 1094

Answers (1)

Abhishek Ranjan
Abhishek Ranjan

Reputation: 497

So after hours of search, I finally figured this out. Since I was using the Google's JS Client libraries, I almost ignored the fact that I have to pass my oauth2 access_token with each API call. Only then will the API know the account to access. More specifically, pass the access_token in the header while making API requests. Here is a jQuery snippet for the same :

$.get(`https://www.googleapis.com/tasks/v1/users/@me/lists`,{access_token: AccessToken}, function (data,status) {
    console.log(status,data);
});

Hope it helps the others...

Upvotes: 1

Related Questions