### Import Google API Libraries in Dart Source: https://github.com/google/googleapis.dart/blob/master/README.md Import the authentication and Drive API libraries into your Dart file. This example uses 'auth_browser' for browser-based authentication and 'drive/v2' for the Drive API. ```dart import 'package:googleapis_auth/auth_browser.dart' as auth; import 'package:googleapis/drive/v2.dart' as drive; ``` -------------------------------- ### Obtain Authenticated Client via Metadata Server Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Get an authenticated and auto-refreshing HTTP client using the metadata service. Remember to close the client when finished. ```dart import 'package:googleapis_auth/auth_io.dart'; // Use the metadata service to get an authenticated and auto refreshing client. Future obtainAuthenticatedClient() async { final AuthClient client = await clientViaMetadataServer(); return client; // Remember to close the client when you are finished with it. } ``` -------------------------------- ### Implement Browser OAuth 2.0 Flow Source: https://github.com/google/googleapis.dart/blob/master/README.md This function manages the implicit browser flow for OAuth 2.0. It first attempts to get a client without forcing user consent. If consent is required or denied, it prompts the user via a button click. ```dart Future authorizedClient(ButtonElement loginButton, auth.ClientId id, scopes) { return auth.createImplicitBrowserFlow(id, scopes) .then((auth.BrowserOAuth2Flow flow) { return flow.clientViaUserConsent(forceUserConsent: false).catchError((_) { loginButton.text = ''; return loginButton.onClick.first.then((_) { return flow.clientViaUserConsent(forceUserConsent: true); }); }, test: (error) => error is auth.UserConsentException); }); } ``` -------------------------------- ### Obtain Authenticated Client via Service Account Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Get an authenticated and auto-refreshing HTTP client using service account credentials. This client is suitable for autonomous applications accessing Google Cloud Project data. Remember to close the client when finished. ```dart import 'package:googleapis_auth/auth_io.dart'; // Use service account credentials to get an authenticated and auto refreshing // client. Future obtainAuthenticatedClient() async { final accountCredentials = ServiceAccountCredentials.fromJson({ 'private_key_id': '', 'private_key': '', 'client_email': '@developer.gserviceaccount.com', 'client_id': '.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. } ``` -------------------------------- ### Display Help for Discovery Generator Source: https://github.com/google/googleapis.dart/blob/master/discoveryapis_generator/README.md Run the generator with the -h flag to see all available commands and options. ```bash dart bin/generate.dart -h ``` -------------------------------- ### Rungoogleapis_auth Package Tests Source: https://github.com/google/googleapis.dart/blob/master/README.md Execute tests for the `googleapis_auth` package. This includes fetching dependencies, running tests, and formatting the code. ```console $ pushd googleapis_auth $ pub get $ pub run test $ dart format . --fix $ popd ``` -------------------------------- ### Generate APIs Source: https://github.com/google/googleapis.dart/blob/master/README.md Generate API client libraries using the `generate.dart` script with the `run_config generate` command. This step should be performed after downloading discovery documents. ```console $ dart generator/bin/generate.dart run_config generate ``` -------------------------------- ### Download APIs using config.yaml Source: https://github.com/google/googleapis.dart/blob/master/README.md Download API discovery documents using the `generate.dart` script with the `run_config download` command. It's recommended to use Cloud Shell for this operation, especially on corporate networks. ```console $ dart generator/bin/generate.dart run_config download ``` -------------------------------- ### Run Generatedgoogleapis Tests Source: https://github.com/google/googleapis.dart/blob/master/README.md Execute tests for the generated Google APIs packages (`googleapis` and `googleapis_beta`). This involves navigating to the respective directories, fetching dependencies, and running the tests. ```console $ pushd generated/googleapis $ pub get $ pub run test $ cd ../googleapis_beta $ pub get $ pub run test $ popd ``` -------------------------------- ### Generate API Package from Discovery Documents Source: https://github.com/google/googleapis.dart/blob/master/discoveryapis_generator/README.md Use the 'package' subcommand to create a new Dart API client library package. Specify input and output directories, along with package metadata. ```bash dart bin/generate.dart package -i -o --package-name --package-version --package-description --package-author --package-repository ``` -------------------------------- ### Initialize Storage API Client Source: https://github.com/google/googleapis.dart/blob/master/README.md Define the necessary scopes for your API operations and obtain an authenticated HTTP client using your service account credentials. This client is then used to instantiate the Storage API. ```dart final scopes = [storage.StorageApi.DevstorageFullControlScope]; ... var api = new storage.StorageApi(client); ``` -------------------------------- ### Create Service Account Credentials from JSON Source: https://github.com/google/googleapis.dart/blob/master/README.md Instantiate service account credentials using a JSON string. Ensure you replace the placeholder values with your actual service account details obtained from the Cloud Console. ```dart final accountCredentials = new auth.ServiceAccountCredentials.fromJson(r''' { "private_key_id": "", "private_key": "", "client_email": "@developer.gserviceaccount.com", "client_id": ".apps.googleusercontent.com", "type": "service_account" }'''); ``` -------------------------------- ### Obtain Credentials via Metadata Server Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Use the metadata service to obtain OAuth credentials on a Compute Engine VM. Ensure the http client is closed after use. ```dart import 'package:googleapis_auth/auth_io.dart'; import 'package:http/http.dart' as http; // Use the metadata service to obtain oauth credentials. Future obtainCredentials() async { final client = http.Client(); final credentials = await obtainAccessCredentialsViaMetadataServer(client); client.close(); return credentials; } ``` -------------------------------- ### Create Drive API Instance Source: https://github.com/google/googleapis.dart/blob/master/README.md Instantiate the DriveApi object by passing the authenticated HTTP client. This object provides methods to interact with the Google Drive API. ```dart var api = new drive.DriveApi(client); ``` -------------------------------- ### Declare Dependencies in pubspec.yaml Source: https://github.com/google/googleapis.dart/blob/master/README.md Declare the necessary googleapis_auth and googleapis packages in your pubspec.yaml file to use the Google Drive API and OAuth 2.0. ```yaml dependencies: googleapis_auth: '>=0.1.0 < 0.2.0' googleapis: '>=0.1.1 < 0.2.0' ``` -------------------------------- ### Upload Media to Google Cloud Storage Source: https://github.com/google/googleapis.dart/blob/master/README.md Use the Storage API to upload a media file to a Google Cloud Storage bucket. This involves calling the `insert` method on the `objects` resource of the Storage API. ```dart return api.objects.insert(null, bucket, name: object, uploadMedia: media); ``` -------------------------------- ### Generate API Files into Existing Package Source: https://github.com/google/googleapis.dart/blob/master/discoveryapis_generator/README.md Use the 'files' subcommand to generate API files directly into an existing Dart package. This command can also update the pubspec.yaml file. ```bash dart bin/generate.dart files -i -o -u --core-prefixes ``` -------------------------------- ### Authenticate Client with Service Account Source: https://github.com/google/googleapis.dart/blob/master/README.md Obtain an authenticated HTTP client by providing the service account credentials and the desired scopes to the `clientViaServiceAccount` function. This client can then be used to interact with Google Cloud APIs. ```dart auth.clientViaServiceAccount(accountCredentials, scopes).then((client) { ... var regexp = new RegExp(r'^gs://([^/]+)/(.+)$'); switch (args.first) { case 'upload': ... } ``` -------------------------------- ### Obtain Credentials for Client-Side Web App Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Use this for client-side web applications to request access credentials. Requires a Client ID and specified scopes. ```dart import 'package:googleapis_auth/auth_browser.dart'; // Initialize the browser oauth2 flow functionality then use it to obtain // credentials. Future obtainCredentials() => requestAccessCredentials( clientId: '....apps.googleusercontent.com', scopes: ['scope1', 'scope2'], ); ``` -------------------------------- ### Obtain Authenticated HTTP Client for Client-Side Web App Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Obtain an authenticated HTTP client for client-side web applications. This client will automatically use the obtained credentials for requests. Remember to close the client when finished. ```dart import 'package:googleapis_auth/auth_browser.dart'; import 'package:http/http.dart' as http; Future obtainClient() async { final credentials = await requestAccessCredentials( clientId: '....apps.googleusercontent.com', scopes: ['scope1', 'scope2'], ); return authenticatedClient(http.Client(), credentials); } ``` -------------------------------- ### Initiate Authorized Client Flow Source: https://github.com/google/googleapis.dart/blob/master/README.md Call authorizedClient() in your main function to obtain an authenticated HTTP client. This function handles the OAuth 2.0 authorization process, requesting user consent if necessary. ```dart authorizedClient(loginButton, identifier, scopes).then((client) { ... }) ``` -------------------------------- ### Access Public Data with API Key Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Obtain an HTTP client that uses an API key for making requests to Google APIs. The API key is used for quota and billing and should not be disclosed. ```dart import 'package:googleapis_auth/auth_io.dart'; var client = clientViaApiKey(''); // [client] can now be used to make REST calls to Google APIs. ... client.close(); ``` -------------------------------- ### Obtain Credentials with Custom Endpoints Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Use custom AuthEndpoints to obtain access credentials via user consent for a non-Google OAuth provider. ```dart final clientId = ClientId('my-client-id', 'my-client-secret'); final credentials = await obtainAccessCredentialsViaUserConsent( clientId, ['scope1', 'scope2'], client, (url) { print('Please go to the following URL and grant access:'); print(' => $url'); print(''); }, authEndpoints: MicrosoftAuthEndpoints(), ); ``` -------------------------------- ### Upgrade Dependencies in Generator Directory Source: https://github.com/google/googleapis.dart/blob/master/README.md Update project dependencies within the `generator` directory. This involves removing the existing Dart tool cache and running `pub upgrade`. ```console $ cd generator $ rm -rf .dart_tool $ pub upgrade ``` -------------------------------- ### Configure Client ID and Scopes Source: https://github.com/google/googleapis.dart/blob/master/README.md Define the client ID obtained from the Google Developers Console and the API scopes required for your application. The scope determines the level of access granted to the user's data. ```dart final identifier = new auth.ClientId( ".apps.googleusercontent.com", null); final scopes = [drive.DriveApi.DriveScope]; ``` -------------------------------- ### Search Documents with Google Drive API Source: https://github.com/google/googleapis.dart/blob/master/README.md Implement a function to search for documents in Google Drive using the Drive API. This function supports pagination to retrieve all results if the total number exceeds the maximum results per page. ```dart Future> searchTextDocuments(drive.DriveApi api, int max, String query) { var docs = []; Future next(String token) { // The API call returns only a subset of the results. It is possible // to query through the whole result set via "paging". return api.files.list(q: query, pageToken: token, maxResults: max) .then((results) { docs.addAll(results.items); // If we would like to have more documents, we iterate. if (docs.length < max && results.nextPageToken != null) { return next(results.nextPageToken); } return docs; }); } return next(null); } ``` -------------------------------- ### Obtain Credentials via Service Account Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Use service account credentials to obtain OAuth credentials for autonomous applications. Requires a JSON key file and specified scopes. Ensure the http client is closed after use. ```dart import 'package:googleapis_auth/auth_io.dart'; import 'package:http/http.dart' as http; // Use service account credentials to obtain oauth credentials. Future obtainCredentials() async { final accountCredentials = ServiceAccountCredentials.fromJson({ 'private_key_id': '', 'private_key': '', 'client_email': '@developer.gserviceaccount.com', 'client_id': '.apps.googleusercontent.com', 'type': 'service_account' }); final scopes = ['scope1', 'scope2']; final client = http.Client(); final credentials = await obtainAccessCredentialsViaServiceAccount( accountCredentials, scopes, client); client.close(); return credentials; } ``` -------------------------------- ### Define Custom Authentication Endpoints Source: https://github.com/google/googleapis.dart/blob/master/googleapis_auth/README.md Subclass AuthEndpoints to provide custom authorization and token URIs for non-Google OAuth providers. ```dart import 'package:googleapis_auth/auth_io.dart'; class MicrosoftAuthEndpoints extends AuthEndpoints { @override Uri get authorizationEndpoint => Uri.https('login.microsoftonline.com', 'common/oauth2/v2.0/authorize'); @override Uri get tokenEndpoint => Uri.https('login.microsoftonline.com', 'common/oauth2/v2.0/token'); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.