Google API Client Libraries for Dart

repository·master·Indexed 19 days ago

https://github.com/google/googleapis.dart

Auto-generated Dart client libraries for accessing Google APIs (such as Drive, Gmail, and Cloud Storage) via RESTful interfaces. The project includes the googleapis and googleapis_beta packages for API access, googleapis_auth for OAuth 2.0 credentials and authenticated HTTP clients, and discoveryapis_generator for creating API packages from Discovery documents.

Tokens
6.7K
Snippets
17
Records
29
Agent score
62%

What's inside googleapis.dart

  1. Overview of Google API Client Libraries for Dart

    master

    This repository provides Dart client libraries to interact with Google APIs (such as Google Drive, Gmail, Cloud Datastore, and Cloud Storage) via REST-like interfaces. Instead of using raw REST protocols, you can use these generated libraries for a more convenient and less error-prone experience.

    The ecosystem is split into several key packages:

    • googleapis: Contains stable, auto-generated client libraries for accessing Google APIs.
    • googleapis_beta: Contains APIs that are currently in beta or part of a Limited Preview program.
    • googleapis_auth: Provides tools to obtain OAuth 2.0 credentials and an authenticated HTTP client required to use the googleapis packages.
    • _discoveryapis_commons: A library used by client APIs generated from Discovery Documents.
    • discoveryapis_generator: A tool to create API Client libraries based on the Discovery API Service.
  2. Explore Google API Client Libraries for Dart

    master

    To use Google APIs in Dart, you can utilize the following packages:

    • googleapis_auth: The core package for authentication and OAuth 2.0 flows.
    • googleapis_beta: Contains APIs that are currently in beta or part of a Limited Preview program.

    You can also find practical implementations in the googleapis_examples repository.

  3. Determine the required credentials for Google APIs

    master

    The type of credentials you need depends on the nature of your application and the data it accesses. You manage all credentials through the Google Developers Console.

    Credential Scenarios:

    • Client ID: Required for applications that access data owned by a user on their behalf (with user consent), such as browser-based or console applications.
    • Service Account: Used by server-side applications to access data owned by the application itself (e.g., a server accessing Cloud Storage or Datastore).
    • API Key: Used for accessing public data that does not require user-specific authorization (used primarily for quota and billing purposes).
  4. Understand OAuth 2.0 flows for Google APIs

    master

    OAuth 2.0 is used when an application requires authentication or authorization, specifically when user consent is involved. The protocol provides different flows depending on the application type (web server, installed, or client-side).

    Common authorization properties include:

    • Public API: No credentials needed.
    • API Key access: Accesses data without a specific user.
    • User Data access: Requires user consent (OAuth 2.0).
    • Application Data access: Uses a Service Account.
  5. Use a Service Account for Autonomous Applications

    master

    Service accounts allow applications to act autonomously without user intervention. Create a 'Service account' in the Google Developers Console to download a JSON key file containing a private RSA key.

    Use ServiceAccountCredentials.fromJson to load the credentials and clientViaServiceAccount to obtain an auto-refreshing AuthClient.

    Impersonation: To support APIs like Google Apps that require user impersonation, use the impersonatedUser argument in the ServiceAccountCredentials constructor.

    import 'package:googleapis_auth/auth_io.dart';
    import 'package:http/http.dart' as http;
    
    // Use service account credentials to get an authenticated and auto refreshing client.
    Future<AuthClient> obtainAuthenticatedClient() async {
      final accountCredentials = ServiceAccountCredentials.fromJson({
        'private_key_id': '<please fill in>',
        'private_key': '<please fill in>',
        'client_email': '<please fill in>@developer.gserviceaccount.com',
        'client_id': '<please fill in>.apps.googleusercontent.com',
        'type': 'service_account'
      });
      final scopes = ['scope1'];
    
      final AuthClient client = await clientViaServiceAccount(accountCredentials, scopes);
    
      return client; // Remember to close the client when you are finished with it.
    }
  6. Use service accounts for Cloud APIs

    master
    The documentation provides guidance on using service accounts to authenticate and access Google Cloud APIs. For specific implementation details, refer to the 'Using a service account for a Cloud API' section in the full README.
  7. Use a Service Account for Cloud APIs

    master

    For server-side applications accessing Cloud APIs (like Cloud Storage or Datastore), use a Service Account instead of user-based OAuth 2.0.

    1. Create Service Account: In the Google Developers Console, create a new credential of type Service account.
    2. Download JSON Key: Download the service account credentials in JSON format.
    3. Initialize in Dart: Use auth.ServiceAccountCredentials.fromJson() to load the credentials and auth.clientViaServiceAccount() to generate the authenticated HTTP client.
    import 'package:googleapis_auth/auth.dart' as auth;
    import 'package:googleapis/storage/v1.dart' as storage;
    
    // 1. Load credentials from the downloaded JSON
    final accountCredentials = new auth.ServiceAccountCredentials.fromJson(r'''
    {
      "private_key_id": "<please fill in>",
      "private_key": "<please fill in>",
      "client_email": "<please fill in>@developer.gserviceaccount.com",
      "client_id": "<please fill in>.apps.googleusercontent.com",
      "type": "service_account"
    }''');
    
    // 2. Define scopes
    final scopes = [storage.StorageApi.DevstorageFullControlScope];
    
    // 3. Create the authenticated client
    auth.clientViaServiceAccount(accountCredentials, scopes).then((client) {
      // 4. Initialize the API
      var api = new storage.StorageApi(client);
      
      // Example: Upload a file
      // return api.objects.insert(null, bucket, name: object, uploadMedia: media);
    });
  8. Authenticate a web application using OAuth 2.0

    master

    For client-side web applications, use googleapis_auth to handle the OAuth 2.0 flow.

    1. Import libraries: Use auth_browser.dart for browser-based authentication and the specific API library (e.g., drive/v2.dart).
    2. Define Client ID and Scopes: Create an auth.ClientId using your generated ID and define an array of scopes (e.g., drive.DriveApi.DriveScope).
    3. Initialize Browser Flow: Use auth.createImplicitBrowserFlow to manage the user consent process.
    4. Get Authenticated Client: Use flow.clientViaUserConsent() to prompt the user for permission. If the user has already consented, this can be called with forceUserConsent: false to provide a seamless experience.
    import 'package:googleapis_auth/auth_browser.dart' as auth;
    import 'package:googleapis/drive/v2.dart' as drive;
    
    // 1. Define credentials
    final identifier = new auth.ClientId("<custom-app-id>.apps.googleusercontent.com", null);
    final scopes = [drive.DriveApi.DriveScope];
    
    // 2. Perform authentication flow
    Future authorizedClient(ButtonElement loginButton, auth.ClientId id, scopes) {
      return auth.createImplicitBrowserFlow(id, scopes)
          .then((auth.BrowserOAuth2Flow flow) {
            return flow.clientViaUserConsent(forceUserConsent: false).catchError((_) {
              // Handle case where user needs to manually click a button to consent
              loginButton.text = '';
              return loginButton.onClick.first.then((_) {
                return flow.clientViaUserConsent(forceUserConsent: true);
              });
            }, test: (error) => error is auth.UserConsentException);
          });
    }
    
    // 3. Use the client to access the API
    // ... inside an async block after getting the client
    var api = new drive.DriveApi(client);
  9. Prerequisites for using Google API Client Libraries

    master

    To build and run a program that interacts with Google products using these libraries, ensure you have the following:

    1. A Google Account: To manage your development resources.
    2. A Google Developers Console Project: Every application requires a project to manage settings, credentials (OAuth2 service accounts, Client IDs), API activation, and billing.
    3. The googleapis_auth package: Essential for creating an authenticated HTTP client that handles authorization automatically when passed to API objects.
    4. The googleapis or googleapis_beta package: The specific client library for the API you wish to consume.
    5. Dart SDK: Installed on your development machine.
  10. Obtain OAuth2 credentials for Client-side Web Applications

    master

    For client-side only web applications, create a 'Web application' type Client ID in the Google Developers Console. Set the Javascript Origins to the URLs where your app is served (e.g., http://localhost:8080).

    You can use requestAccessCredentials to get credentials or authenticatedClient to get an HTTP client that automatically handles authentication.

    Note: Use package:googleapis_auth/auth_browser.dart for this flow.

    import 'package:googleapis_auth/auth_browser.dart';
    import 'package:http/http.dart' as http;
    
    // Obtain access credentials
    Future<AccessCredentials> obtainCredentials() => requestAccessCredentials(
          clientId: '....apps.googleusercontent.com',
          scopes: ['scope1', 'scope2'],
        );
    
    // Obtain an authenticated HTTP client
    Future<AuthClient> obtainClient() async {
      final credentials = await requestAccessCredentials(
        clientId: '....apps.googleusercontent.com',
        scopes: ['scope1', 'scope2'],
      );
    
      return authenticatedClient(http.Client(), credentials);
    }