paint-brush
How to Implement Cloud APIs: Google Drive API, Dropbox API, and OneDrive APIby@tetianastoyko
2,072 reads
2,072 reads

How to Implement Cloud APIs: Google Drive API, Dropbox API, and OneDrive API

by Tetiana StoykoSeptember 14th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

A cloud API engages with a cloud infrastructure to distribute processing, storing, and system resources for web software and services that have been demanded. Any public cloud operation depends on a cloud API, which is often built on the REST and SOAP approaches, along with cross-platform and vendor-specific APIs. In this article, we performed Google Drive API, Dropbox API, and OneDrive API integration with code fillets and screenshots. For Google Drive API you need to go through a few stages: Getting client keys for Google Drive API, Configuring consent screen,

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - How to Implement Cloud APIs: Google Drive API, Dropbox API, and OneDrive API
Tetiana Stoyko HackerNoon profile picture


A Cloud Application Programming Interface (Cloud API) is a sort of API that allows developers to create applications and services for cloud hardware, software, and platforms deployment. A cloud API is a portal or interface that connects users to cloud infrastructure and software applications, both directly and indirectly. A cloud API engages with a cloud infrastructure to distribute processing, storing, and system resources for web software and services that have been demanded. API integration tools can help you prevent data clutter by pulling information from relevant database systems.


Cloud data storage opens up a world of possibilities, and cloud integration services are expanding to meet those needs, including cloud storage providers with as-a-service capabilities that supply solutions tailored to specific hybrid API integration issues. System administrators are searching for new methods to interact with their cloud model as cloud services consolidate. Companies and developers have the largest hurdle in integrating their system infrastructure with these cloud storage providers or cloud-based services, which are frequently provided by third-party suppliers and enhancing the overall experience that results from that strategic shift. API integration is the actual deal in all of this.


Data management on the cloud is one of the most significant technological breakthroughs in recent years. Not only for huge amounts of data but also for platforms or services for end-users, such as customers or employees of a corporation. Hundreds of tools and capabilities for managing information in the cloud, ranging from office automation to data storage through applications, are the outcome of this work. Any public cloud operation depends on a cloud API, which is often built on the REST and SOAP approaches, along with cross-platform and vendor-specific APIs.


To simplify the API integration for cloud data storage extension and your application’s functionality improvement, we defined a step-by-step description of how to implement the most known and used Cloud APIs: Google Drive API, Dropbox API, and OneDrive API.

Integration with Google Drive

Google Drive API enables you to develop apps that use Google's cloud data storage. Using the Google Drive API, you can design apps that interact with Google Drive as a cloud storage provider that offers extensive functionality, such as: transferring your data model to the VDR once and then trace the VDR to numerous target systems, managing every element of the user interface and user experience, and extendible CE's Elements that require less maintenance.

Getting client keys for Google Drive API

The first thing we should do for API integration is to create client keys.

Navigate to the APIs & Services → Credentials page in the Cloud Console. Then select OAuth client ID in "Create credentials."



If you haven’t configured the consent screen go on with configuring.


Configuring the Consent Screen

On the first step fill in all the required fields and optional if needed.



In the second step, we should specify the scopes we want. Click “Add or remove scopes”. For using Google Drive API we need to have https://www.googleapis.com/auth/drive’ scope. Use the ‘Manually add scopes’ section.



Go to the last step and save the data.

Creating Client Keys

Select the app type and specify the name of it. In our case, the type is a Web application.



Specify the app and redirect URIs. Usually, app URI is our client web application URI, and redirect URI is the server-side route that is going to handle Shopify requests after the OAuth process is completed.



After you get your client id and secret, copy and save them to your project configuration file.

OAuth

To work with google API a good choice is to use the library ‘GoogleAPIs’.

Let us create a service to work with Google Drive API and in it the client with secret keys.


import { google } from 'googleapis';
import { OAuth2Client } from 'google-auth-library';

const { clientId, clientSecret, redirectURL } = cfg.googleDriveAPI;

class GoogleDriveService {
  private gdriveClient: OAuth2Client;

  constructor() {
    this.gdriveClient = new google.auth.OAuth2(
      clientId,
      clientSecret,
      redirectURL,
    );

    google.options({
      auth: this.gdriveClient,
    });
  }
}


To generate an OAuth URL for the web client we can create a special method, specifying access type and scope for Google Drive cloud storage provider.


public getAuthUrl() {
    const authUrl = this.gdriveClient.generateAuthUrl({
      access_type: 'online',
      scope: 'https://www.googleapis.com/auth/drive',
    });

    return authUrl;
  }


Our client application is going to redirect to this URL, and the Google auth form will be presented. After the user logs in successfully, the user will be redirected to the URL you specified.


As we specified our back-end endpoint, let's create one. Firstly we need to add a method to our service


public async getToken(code: string, redirectUri: string) {
    const { tokens } = await this.gdriveClient.getToken({ code, redirect_uri: redirectUri });

    this.gdriveClient.setCredentials(tokens);
    return tokens;
  }


The endpoint should be similar to the implementation below.


router.get('/googledrive-auth', async (req: Request, res: Response) => {
  const { code } = req.query;
  const token = await googleDriveService.getToken(code, cfg.googleDriveAPI.redirectURL);

  // save token to e.g. redis
  // redirect to the FE page
});


Our query params payload will include code, which can be used only once to receive an access token. A good way to save a token to some cache storage and send a redirect as the response.


After you get the token you can use the endpoints of Google drive API. For example, let’s add a method to get a file by its id:


public getFile(
    accessToken,
    fileId,
  ) {
    this.gdriveClient.setCredentials({ access_token: accessToken })

    return drive.files.get(
      { auth: this.gdriveClient, fileId })
  }

Integration with Dropbox

Developers may use the Dropbox API to interact with Dropbox files, including sophisticated features like full-text search, thumbnails, and sharing. Dropbox API also includes regular authentication procedures to eliminate endpoint subtlety, as well as standardized methods and calls among all APIs, webhooks, and monitoring.

Getting Client Keys for the Dropbox API

Firstly we should create an application using your Dropbox console.



After you created the application we need to add the OAuth redirect URI in the app settings.



Your app key and secret information are available in settings.



Now when we have keys we can start creating a service to work with Dropbox API. We are using library Dropbox SDK.


import { Dropbox } from 'dropbox';

export class DropboxService {
  protected dbxOauth: Dropbox

  constructor(config: Record<'clientId' | 'clientSecret', string> = cfg.dropboxAPI) {
    const { clientId, clientSecret } = config;

    this.dbxOauth = new Dropbox({ clientId });
    this.dbxOauth.setClientSecret(clientSecret);
  }
}

OAuth

To start the OAuth process we should form the URL which should be opened in the browser(usually by the client-side of the application). It should include the base URL of the Dropbox OAuth page and query parameters, including client ID(from settings of the app), redirect URI (one of configured in settings), and response type(we are using code-based OAuth flow.

This will open the Dropbox OAuth window.



After you log in and allow your app to access the data on your account you will be redirected to the URI you specified with code in the query params.


Let’s create a handler for it. Firstly we need to add a method to our service to exchange codes and get access tokens.


public async getToken(code: string, redirectUri: string) {
    const token = await this.dbxOauth.getAccessTokenFromCode(redirectUri, code);

    return token;
  }

The endpoint should be similar to the implementation below.

router.get('/dropbox-auth, async (req: Request, res: Response) => {
  const { code } = req.query;
  const token = await dropboxService.getToken(code, cfg.dropboxAPI.redirectURL);

  // save token to e.g. redis
  // redirect to the FE page
});

Using API

Now when we have a token, let’s create a helper to get an authorized client for the Dropbox API.


protected async getClient(accessToken: string) {
    const dbxClient = new Dropbox({ accessToken });

    return await dbxClient;
  }


Now we can use the API. For example, getting current users should look like below.


public async getCurrentUser(accessToken: string) {
    const dropboxClient = await this.getClient(accessToken);
    const user = await dropboxClient.usersGetCurrentAccount();

    return user;
  }

Integration with One Drive

With the OneDrive API, it is possible to work with files in a number of settings, including Microsoft Teams, Groups, SharePoint, and more. Users may view these files from anywhere, exchange links to files, and copy or transfer data to team drives using OneDrive. Customers can trust the sophisticated encryption, compliance, and security capabilities in OneDrive API to keep their data safe.

Getting Client Keys for the OneDrive API

Create an application within your Microsoft Azure platform. We are using SPA type to redirect URI.



After you create your client ID, it is available on the overview page.



After that, we have to create the client secret on the Certificates & Secrets page




After you have created it you can save the value of it to configuration files.




Now we should update our API permissions. Go to the OneDrive API permissions tab and add Files.ReadWrite(for accessing Onedrive files) and User.Read(for authorization).



OAuth

The OAuth URI should contain clientID, scopes, and response type, which in our case represents this URL.




After you log in to the OneDrive API, cloud data storage and allow your app to access the data on your account you will be redirected to the URI you specified with code in the query params. Let’s create a service and auth handler for it.

We are using simple-oauth2 library:


import * as simpleOauth2 from 'simple-oauth2';

const { clientId, clientSecret } = cfg.oneDriveAPI;

class OneDriveService {
  private oneDriveOauth = simpleOauth2.create({
    client: {
      id: clientId,
      secret: clientSecret,
    },
    auth: {
      tokenHost: 'https://login.microsoftonline.com/common',
      authorizePath: '/oauth2/v2.0/authorize',
      tokenPath: '/oauth2/v2.0/token',
    },
  })

  public async getToken(code: string, redirectUri: string) {
    const rawTokenData = await this.oneDriveOauth.authorizationCode.getToken({
      code,
      redirect_uri: redirectUri,
    });

    return this.oneDriveOauth.accessToken.create(rawTokenData);
  }
}


The endpoint should be similar to the implementation below.


router.get('/onedrive, async (req: Request, res: Response) => {
  const { code } = req.query;
  const token = await onedriveService.getToken(code, cfg.oneDriveAPI.redirectURL);

  // save token to e.g. redis
  // redirect to the FE page
});

Using the API

Now when we have a token, let’s create a helper to get an authorized client for the API integration.

private getClient(token: string) {
    return MicrosoftGraph.Client.init({
      authProvider: (done) => {
        done(null, token); //first parameter takes an error if you can't get an access token
      }
    });
  }


Now we can use the OneDrive API. For example, getting current users should look like below.


 public async getCurrentUser(accessToken: string) {
    const client = this.getClient(accessToken);

    return client.api('/me')
      .select(['id', 'displayName', 'userPrincipalName'])
      .get();
  }

Last comments

Cloud API is a set of automation tools that assist link software applications and API integration tools independent of their deployment environment. Furthermore, API integration of cloud data storage provides a single dashboard for managing, governing, and integrating cloud-based applications, utilizing tools that link cloud applications and services and regulate integration flow.


The integration of cloud storage providers breaks down the process, improves visibility, and simplifies corporate operations by bringing diverse information solutions together. It's critical to thoroughly comprehend what cloud data storage does and can accomplish before learning how to take advantage of the potential it offers. Since there are a variety of Cloud API Integration tools available, you should ensure that the one you implement - fulfills all of your demanded functionalities.


Also posted on: https://incorainc.com/cloud-api-use-cases-for-google-drive-dropbox-onedrive-api/