Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Contacts API nodejs

I've been looking through the Google NodeJS API docs, but I don't see one listed for the Contacts API. Am I missing something or is that not included in the module?

like image 914
Nicholas McMurray Avatar asked Mar 05 '26 18:03

Nicholas McMurray


1 Answers

Google's official API for NodeJS doesn't use Contacts API. They use instead the People API. If you need to access "Other Contacts", you will need Contacts API.

You can still connect with Contacts API using the official googleapis library if you're already using it for other purposes by sending a request to the Contacts API after creating the auth client. If you're not using the googleapis library, it might be an overkill, and it's better to use the other libraries suggested by other answer.

Given that you already have the access token of the user (e.g. if you generated it using Passport, here's the code:

const {google} = require("googleapis");
const authObj = new google.auth.OAuth2({
    access_type: 'offline',
    clientId: process.env.GOOGLE_ID,
    clientSecret: process.env.GOOGLE_SECRET,
});

Refresh access token automatically before it expires

authObj.on('tokens', (tokens) => {
    const access_token = tokens.access_token
    if (tokens.refresh_token){
        this.myTokens.refreshToken = tokens.refresh_token
        // save refresh token in the database if it exists
    }
        this.myTokens.accessToken = tokens.access_token       
        // save new access token (tokens.access_token)
}
authObj.setCredentials({
    access_token:this.myTokens.accessToken,
    refresh_token:this.myTokens.refreshToken,
});

Make the request to Contacts API:

authObj.request({
    headers:{
        "GData-Version":3.0
    },
    params:{
        "alt":"json",
        //"q":"OPTIONAL SEARCH QUERY",
        //"startindex":0
        "orderby":"lastmodified",
        "sortorder":"descending",
    },
    url: "https://www.google.com/m8/feeds/contacts/default/full"
}).then( response => {
    console.log(response); // extracted contacts
});
like image 95
Abdallah Absi Avatar answered Mar 07 '26 09:03

Abdallah Absi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!