How to connect with Gmail API

Google uses OAuth 2.0 for authentication. In this case, to be able to manipulate Gmail API, you need to connect with OAuth 2.0. Then, you will be able to consume Gmail API. Here is how to connect with Google OAuth 2.0.

To connect with Google OAuth 2.0, you need to create an apps in Google Cloud Console.

Creating Apps

Go to: https://console.cloud.google.com/ and create click Create Project.

Then, click on +ENABLE APIS AND SERVICES.

Then, search for Gmail and click on the first result.

Then click on Enable button.


Creating Credentials

Now, the apps you created have access to Gmail. Next, you need to create credentials which consists of 2 keys:

  1. Client ID
  2. Client Secret

So, you should create credentials.

Choose User data and click Next button.

For scopes, choose all (but in reality, choose only that are related to your project.

For application type, choose Web Application.

Then, you click Done button and get your Client ID and Client Secret.


Getting code to get access token

To get code, you must grant the app to access your account. Navigate to:

https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<Your Redirect URI here>&prompt=consent&response_type=code&client_id=<Your Client ID here>&scope=https://mail.google.com&access_type=offline

Note: You will get error since the app is still under development. Hence, you need to define the test user email.

Then, you will be redirected to the URL you defined after clicking the continue button. Take the code in the URL bar.


Getting access token

To get access token, call API POST to https://oauth2.googleapis.com/token with x-www-form-urlencoded as per screenshot below.

Make sure to set the code, client_id, client_secret and redirect_uri accordingly. Set grant_type as authorization_code. You will get access token and refresh token.


Connect with Gmail API

In this section

Navigate to API Reference to get the list of available APIs or you can directly go to this link.

Now you are able to connect with Gmail API.

Reference:

  1. https://developers.google.com/identity/protocols/oauth2
  2. https://developers.google.com/oauthplayground
  3. https://developers.google.com/identity/protocols/oauth2/web-server
  4. https://developers.google.com/gmail/api/reference/rest/v1/users/getProfile

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *