• Stars
    star
    384
  • Rank 107,802 (Top 3 %)
  • Language
    Dart
  • License
    BSD 3-Clause "New...
  • Created over 9 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Repository for building the googleapis packages
Package source Description Published Version
_discoveryapis_commons Library for use by client APIs generated from Discovery Documents. pub package
discoveryapis_generator Create API Client libraries based on the Discovery API Service. pub package
googleapis Auto-generated client libraries for accessing Google APIs described through the API discovery service. pub package
googleapis_beta Auto-generated client libraries for accessing Google APIs described through the API discovery service. pub package
googleapis_auth Obtain Access credentials for Google services using OAuth 2.0 pub package

Google API Client Libraries with Dart

Google provides a large set of APIs that your applications can use to interact with Google products such as Google Drive, Gmail, Cloud Datastore, and Cloud Storage. These APIs are accessible via REST-like interfaces. The Dart team provides the googleapis and googleapis_beta packages, which provide generated Dart libraries for these APIs. Using the APIs, which are available for both web apps and cloud apps, is more convenient and less error-prone than using the raw REST protocol.

To use any of these APIs, you need a Cloud Project. In addition, based on the API being used, you need either an API key or a Client ID. And finally, depending on what kind of application is being used, you might need a Service Account. All these items are available through Google Developers Console when you create a project. Below are a few scenarios:

  • APIs require a Client ID specific to the kind of application when it accesses data that is owned by a user on behalf of that user (with consent): for example a browser application or a console application.

  • A server application can access data owned by the application itself by using a Service Account. Example: a server application accessing data in Datastore or Google Cloud Storage.

  • APIs that can be used to get public data require only an API key (for quota and billing purposes).

To set up authentication and authorization for your app, you need to create a project, create the authentication credentials, and activate the API you want to use, all of which you do at Google Developers Console.

Support for Google APIs is in two packagesโ€”googleapis and googleapis_beta. The googleapis package contains the APIs for all the APIs that are available in a stable version. The googleapis_beta package contains the APIs that are currently in beta and possibly only available through a Limited Preview program.

A third package, googleapis_auth, provides a way to obtain OAuth 2.0 credentials and an authenticated HTTP client required to use these APIs.

The rest of this document describes the following:

Some of the APIs you can use

Here are just a few of the APIs your Dart programs can use.

Google Drive
Google Drive is a Cloud Storage service that allows you to store your documents, photos, videos, and more online. The Google Drive client library lets you access Google Drive services, such as reading and writing files.
Gmail
The Gmail API gives you flexible, RESTful access to the user's inbox, with a natural interface to threads, messages, labels, drafts, and history.
Cloud Datastore
Using Cloud Datastore client libraries you have access to a fully managed, schemaless database for storing non-relational data. Cloud Datastore provides high availability of reads and writes, strong consistency for reads and ancestor queries, and eventual consistency for all other queries.
Google Cloud Storage
Google Cloud Storage provides a fast, scalable, highly available object store that scales as your needs grow. You can access your data with an HTTP API, a web-based interface, or a commmand-line tool.

You can see the full list of APIs at googleapis and googleapis_beta.

OAuth 2.0

Applications sometimes require OAuth 2.0 for authentication and authorization. Whether an application needs OAuth 2.0 depends on the API being used and the kind of data being accessed. For example, an application needs OAuth 2.0 if it needs user consent. An application sometimes needs OAuth 2.0 depending on the following properties:

  • Using public API (no credentials needed)
  • Using API that can be accessed using an API Key (no concrete user)
  • Using API that provides access to user data (user consent)
  • Using API that provides access to application data (service account)

The OAuth 2.0 protocol provides different flows for different types of applications, including web server, installed, and client-side applications. For example, the following diagram illustrates the flow of communication for client-side applications:

Token flow in client-only (JavaScript) application

Using OAuth 2.0 to Access Google APIs gives a detailed overview of the OAuth 2.0 authorization scenarios that Google supports.

What do you need?

To write a program that interacts with a Google product, you need several tools and packages.

A Google account
If you don't already have a Google account, you can create one at Create your Google Account.
A project in Google Developers Console
Every application that uses the client libraries needs a project in Google Developers Console. A project is a collection of settings, credentials, and metadata about the application. Google Developers Console is where you manage aspects of your project, such as authenticating and authorizing you application, activating APIs, and managing team and billing information associated with your project. You must have a project to get OAuth2 service accounts and client IDs.
The googleapis_auth package
Access to Google APIs uses the HTTP protocol. The googleapis_auth package provides different means for creating an HTTP client that can handle the authorization. This HTTP client is then passed to the API objects and takes care of augmenting the communication with the required authorization information. The Dart googleapis_auth client library is available at pub.dev/packages/googleapis_auth. There you can find a detailed README file with code examples and explanatory text.
The googleapis or googleapis_beta package
These packages are publicly available at pub.dev/packages/googleapis and pub.dev/packages/googleapis_beta. Later, you'll see an example of how to use them in your Dart program.
Dart
Get Dart from the download page.

A web application example

Let's look at a web application example that uses the googleapis Google Drive API to retrieve documents from a user's Google Drive. The following screenshot shows the app after it has retrieved a list of spreadsheets from a user's Google Drive and displayed them on the page.

A list of spreadsheets retrieved from Google Drive using client library APIs

You can find the source code for this example, drive_search_web, and others, at googleapis_examples on GitHub.

The section Example explained describes the code in the drive_search_web example related to googleapis and googleapis_auth. But first let's look at how to run the example.

Running the example

To run this example, you need to create a project, activate an API, and create a Client ID in Google Developers Console. This section provides instructions about how to do these for this particular example. For complete information and detailed explanations, refer to Google Developers Console Help.

Create project

  • Go to Google Developers Console.

  • Click the Create Project button.

  • Provide a name for your project.

  • Click the Create button.

Activate the Drive API

  • On left of the project page, click APIs & auth, click APIs.

  • Turn on the authentication for Drive API. It might take a couple of minutes to propagate.

Create a client ID

  • On the left of the project page, under APIs & Auth, then click Credentials.

  • Click Create new Client ID.

  • In the popup window, click Web application, then fill in the form. Use http://localhost:8080 for Authorized JavaScript origins. Because this example is a client-side-only application, don't put a value in Authorized redirect URIs. This example runs on the local computer and uses port 8080. Ensure nothing else is using port 8080. If you later run this example from a different origin, you'll need a new Client ID.

  • Click Create Client ID.

Run the example

  • In the index.dart file, change to the client ID generated in the previous step. The client ID ends in apps.googeusercontent.com.

  • In the top directory of the application, run pub serve.

  • Visit http://localhost:8080 in a browser window. After a little while, you'll see a built version of the app.

  • Click Authorize and accept the authorization on the page that appears.

  • Select a document type from the drop-down menu and click List. The program displays the list of files from the Google Drive of the user who is currently logged in. (Later the user can revoke access if desired.) Refer to Security - Account Settings for details.

This example, drive_search_web, uses the Google Drive API and the OAuth 2.0 API to access the user's files on Google Drive. Let's look at the relevant parts of the example.

  • To use the googleapi packages, you need to declare dependencies in the pubspec.yaml file.
dependencies:
  googleapis_auth: '>=0.1.0 < 0.2.0'
  googleapis: '>=0.1.1 < 0.2.0'
  • In addition to declaring dependencies, you need to import the libraries from the packages into your Dart file. This example has only one Dart file, index.dart, which imports the libraries like this:
import 'package:googleapis_auth/auth_browser.dart' as auth;
import 'package:googleapis/drive/v2.dart' as drive;
  • At the top level, the program gets an identifier for the client with its ID created in Google Developers Console. In addition, the code defines the scope of the APIs it intends to use. The scope controls the set of APIs or parts of APIs that can access token permits. During the access-token request, your application sends one or more values in the scope parameter.
final identifier = new auth.ClientId(
     "<custom-app-id>.apps.googleusercontent.com",
     null);

final scopes = [drive.DriveApi.DriveScope];
  • The main() method authorizes the client with a call to authorizedClient(), passing the identifier and scopes in as parameters.
authorizedClient(loginButton, identifier, scopes).then((client) {
  ...
}

Let's take a look at authorizedClient().

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);
  });
}

First the code initializes the browser flow as illustrated in the OAuth 2.0 diagram above. Then the program attempts to proceed without user consent using flow.clientViaUserConsent() with false as a parameter value. If the user previously gave consent, this will succeed. Otherwise, the program sets up the authorization button in the UI. When the user presses the button, the program brings up a popup window where the user can provide consent. To ask the user for consent, the code call flow.clientViaUserConsent() again using true for the parameter value.

  • In the main() function, the code gets access to the Drive API by creating a new DriveApi object and passing in the HTTP client.
var api = new drive.DriveApi(client);
  • The code uses the API provided by the DriveApi object to search the user's documents:
Future<List<drive.File>> 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);
}

Using a service account for a Cloud API

For APIs such as Cloud Datastore and Cloud Storage you need a Google service account, which is an account that represents your application instead of an individual end user. You can create one when creating a new Client ID: just click Service account instead of Web application.

The example cloudstorage_upload_download_service_account needs a service account because it uses the Google Cloud Storage API.

Let's take a quick look at the relevant code.

The following code creates account credentials from the service account specified in the details of the given JSON string. After you create the service account, you can download the JSON from the Cloud Console. Then enter the appropriate information to replace the placeholders.

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"
}
''');

The program selects the scopes it will use and gets the StorageAPI, just like the previous example retrieved the Drive API.

final scopes = [storage.StorageApi.DevstorageFullControlScope];
...
var api = new storage.StorageApi(client);

Using the credentials and scopes parameters, a call to clientViaServiceAccount gets an authenticated client that can use the Storage APIs.

auth.clientViaServiceAccount(accountCredentials, scopes).then((client) {
  ...
  var regexp = new RegExp(r'^gs://([^/]+)/(.+)$');
  switch (args.first) {
    case 'upload':
  ...
}

Note that the code shown above creates accountCredentials, which identifies this application. The code specified by then() processes the command-line arguments and uploads or downloads a file as indicated.

The following line of code uses the Storage API to upload a media file to Google Cloud Storage.

return api.objects.insert(null, bucket, name: object, uploadMedia: media);

Resource links

Here's a convenient list of the resources you might need:

Contribute

The following notes for those who are contributing to this package. If you are only using this package, you can skip this section.

If you are only making changes to googleapis_auth, then you only need to run tests for that package and can skip the remainder of this section. Specifically, before submitting a pull request:

$ pushd googleapis_auth
$ pub get
$ pub run test
$ dart format . --fix
$ popd

Otherwise...

  • Clone this package and run pub upgrade from the generator directory.

    $ cd generator
    $ rm -rf .dart_tool
    $ pub upgrade
  • Download and generate the APIs using the config.yaml configuration (avoid doing this on corp network, use cloudshell instead).

    $ dart generator/bin/generate.dart run_config download

Note: You may need to reset some of the downloaded discovery documents, such as drive, or prediction.

  • Generate the APIs.

    $ dart generator/bin/generate.dart run_config generate
  • Create a diff with the previous APIs to determine whether a minor or a major update to the version number is required.

  • Update the appropriate CHANGELOG.md file under resources/.

  • Update config.yaml with a new version number and generate again.

    $ dart generator/bin/generate.dart run_config generate
  • Run the tests.

    $ pushd generated/googleapis
    $ pub get
    $ pub run test
    $ cd ../googleapis_beta
    $ pub get
    $ pub run test
    $ popd
  • Commit the downloaded discovery documents and generated packages.

Overrides

If you ever need to ignore a specific API method or make a manual change to anything inside discovery/, you should add the relevant diff to the overrides/ directory.

  • Make changes to the overrides/<desired-api>.json file.
  • Run git diff overrides/<desired-api>.json > overrides/<name>.diff to create a diff file.

Note: The name of the diff file is not important, but if possible, it is advised to associate the name with the relevant GitHub issue. For example, if your manual change is related to issue #123, then the diff file should be named i123.diff.

What next?

  • Read the README and the code for the packages on pub.dev: googleapis_auth.

  • Check out additional APIs that are currently in beta and possibly only available through a Limited Preview program: googleapis_beta.

  • Play with some examples.

  • Read the reference documentation. These APIs are common to many languages including Python, Java, and others. You can refer to the general reference documentation at the developers' products page. Find the product you're interested in on that page and follow the link. Be sure to look the API reference docs for Dart as some of the Dart APIs have quirks.

More Repositories

1

material-design-icons

Material Design icons by Google (Material Symbols)
49,776
star
2

guava

Google core libraries for Java
Java
48,313
star
3

zx

A tool for writing better scripts
JavaScript
37,928
star
4

styleguide

Style guides for Google-originated open-source projects
HTML
36,576
star
5

leveldb

LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values.
C++
33,564
star
6

material-design-lite

Material Design Components in HTML/CSS/JS
HTML
32,279
star
7

googletest

GoogleTest - Google Testing and Mocking Framework
C++
32,215
star
8

jax

Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more
Python
27,992
star
9

python-fire

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.
Python
26,112
star
10

comprehensive-rust

This is the Rust course used by the Android team at Google. It provides you the material to quickly teach Rust.
Rust
26,107
star
11

mediapipe

Cross-platform, customizable ML solutions for live and streaming media.
C++
25,513
star
12

gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Java
22,945
star
13

flatbuffers

FlatBuffers: Memory Efficient Serialization Library
C++
22,064
star
14

iosched

The Google I/O Android App
Kotlin
21,790
star
15

ExoPlayer

An extensible media player for Android
Java
21,465
star
16

eng-practices

Google's Engineering Practices documentation
19,741
star
17

web-starter-kit

Web Starter Kit - a workflow for multi-device websites
HTML
18,434
star
18

flexbox-layout

Flexbox for Android
Kotlin
18,141
star
19

fonts

Font files available from Google Fonts, and a public issue tracker for all things Google Fonts
HTML
17,588
star
20

filament

Filament is a real-time physically based rendering engine for Android, iOS, Windows, Linux, macOS, and WebGL2
C++
16,946
star
21

cadvisor

Analyzes resource usage and performance characteristics of running containers.
Go
16,335
star
22

libphonenumber

Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
C++
15,728
star
23

gvisor

Application Kernel for Containers
Go
15,105
star
24

WebFundamentals

Former git repo for WebFundamentals on developers.google.com
JavaScript
13,842
star
25

yapf

A formatter for Python files
Python
13,648
star
26

tink

Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.
Java
13,318
star
27

deepdream

13,212
star
28

brotli

Brotli compression format
TypeScript
12,921
star
29

guetzli

Perceptual JPEG encoder
C++
12,863
star
30

guice

Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 11 and above, brought to you by Google.
Java
12,342
star
31

wire

Compile-time Dependency Injection for Go
Go
12,222
star
32

blockly

The web-based visual programming editor.
TypeScript
12,067
star
33

sanitizers

AddressSanitizer, ThreadSanitizer, MemorySanitizer
C
10,754
star
34

grumpy

Grumpy is a Python to Go source code transcompiler and runtime.
Go
10,464
star
35

or-tools

Google's Operations Research tools:
C++
10,405
star
36

dopamine

Dopamine is a research framework for fast prototyping of reinforcement learning algorithms.
Jupyter Notebook
10,367
star
37

auto

A collection of source code generators for Java.
Java
10,234
star
38

go-github

Go library for accessing the GitHub v3 API
Go
9,941
star
39

oss-fuzz

OSS-Fuzz - continuous fuzzing for open source software.
Shell
9,859
star
40

go-cloud

The Go Cloud Development Kit (Go CDK): A library and tools for open cloud development in Go.
Go
9,389
star
41

sentencepiece

Unsupervised text tokenizer for Neural Network-based text generation.
C++
8,657
star
42

re2

RE2 is a fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python. It is a C++ library.
C++
8,190
star
43

traceur-compiler

Traceur is a JavaScript.next-to-JavaScript-of-today compiler
JavaScript
8,182
star
44

tsunami-security-scanner

Tsunami is a general purpose network security scanner with an extensible plugin system for detecting high severity vulnerabilities with high confidence.
Java
8,118
star
45

trax

Trax โ€” Deep Learning with Clear Code and Speed
Python
7,943
star
46

skia

Skia is a complete 2D graphic library for drawing Text, Geometries, and Images.
C++
7,874
star
47

benchmark

A microbenchmark support library
C++
7,812
star
48

android-classyshark

Android and Java bytecode viewer
Java
7,468
star
49

pprof

pprof is a tool for visualization and analysis of profiling data
Go
7,408
star
50

closure-compiler

A JavaScript checker and optimizer.
Java
7,253
star
51

agera

Reactive Programming for Android
Java
7,227
star
52

accompanist

A collection of extension libraries for Jetpack Compose
Kotlin
7,221
star
53

magika

Detect file content types with deep learning
Python
7,171
star
54

flutter-desktop-embedding

Experimental plugins for Flutter for Desktop
C++
7,109
star
55

latexify_py

A library to generate LaTeX expression from Python code.
Python
6,953
star
56

diff-match-patch

Diff Match Patch is a high-performance library in multiple languages that manipulates plain text.
Python
6,918
star
57

lovefield

Lovefield is a relational database for web apps. Written in JavaScript, works cross-browser. Provides SQL-like APIs that are fast, safe, and easy to use.
JavaScript
6,847
star
58

glog

C++ implementation of the Google logging module
C++
6,797
star
59

jsonnet

Jsonnet - The data templating language
Jsonnet
6,742
star
60

error-prone

Catch common Java mistakes as compile-time errors
Java
6,690
star
61

model-viewer

Easily display interactive 3D models on the web and in AR!
TypeScript
6,473
star
62

gops

A tool to list and diagnose Go processes currently running on your system
Go
6,375
star
63

draco

Draco is a library for compressing and decompressing 3D geometric meshes and point clouds. It is intended to improve the storage and transmission of 3D graphics.
C++
6,188
star
64

automl

Google Brain AutoML
Jupyter Notebook
6,154
star
65

gopacket

Provides packet processing capabilities for Go
Go
6,082
star
66

physical-web

The Physical Web: walk up and use anything
Java
6,017
star
67

grafika

Grafika test app
Java
6,002
star
68

j2objc

A Java to iOS Objective-C translation tool and runtime.
Java
5,976
star
69

snappy

A fast compressor/decompressor
C++
5,940
star
70

ios-webkit-debug-proxy

A DevTools proxy (Chrome Remote Debugging Protocol) for iOS devices (Safari Remote Web Inspector).
C
5,848
star
71

osv-scanner

Vulnerability scanner written in Go which uses the data provided by https://osv.dev
Go
5,832
star
72

seesaw

Seesaw v2 is a Linux Virtual Server (LVS) based load balancing platform.
Go
5,599
star
73

EarlGrey

๐Ÿต iOS UI Automation Test Framework
Objective-C
5,580
star
74

seq2seq

A general-purpose encoder-decoder framework for Tensorflow
Python
5,577
star
75

flax

Flax is a neural network library for JAX that is designed for flexibility.
Python
5,523
star
76

gemma.cpp

lightweight, standalone C++ inference engine for Google's Gemma models.
C++
5,518
star
77

google-java-format

Reformats Java source code to comply with Google Java Style.
Java
5,366
star
78

wireit

Wireit upgrades your npm/pnpm/yarn scripts to make them smarter and more efficient.
TypeScript
5,280
star
79

battery-historian

Battery Historian is a tool to analyze battery consumers using Android "bugreport" files.
Go
5,249
star
80

clusterfuzz

Scalable fuzzing infrastructure.
Python
5,202
star
81

bbr

5,156
star
82

gumbo-parser

An HTML5 parsing library in pure C99
HTML
5,141
star
83

syzkaller

syzkaller is an unsupervised coverage-guided kernel fuzzer
Go
5,111
star
84

git-appraise

Distributed code review system for Git repos
Go
5,090
star
85

google-authenticator

Open source version of Google Authenticator (except the Android app)
Java
5,077
star
86

uuid

Go package for UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.
Go
4,994
star
87

gts

โ˜‚๏ธ TypeScript style guide, formatter, and linter.
TypeScript
4,930
star
88

gemma_pytorch

The official PyTorch implementation of Google's Gemma models
Python
4,920
star
89

closure-library

Google's common JavaScript library
JavaScript
4,837
star
90

cameraview

[DEPRECATED] Easily integrate Camera features into your Android app
Java
4,734
star
91

grr

GRR Rapid Response: remote live forensics for incident response
Python
4,641
star
92

liquidfun

2D physics engine for games
C++
4,559
star
93

pytype

A static type analyzer for Python code
Python
4,528
star
94

gxui

An experimental Go cross platform UI library.
Go
4,450
star
95

bloaty

Bloaty: a size profiler for binaries
C++
4,386
star
96

clasp

๐Ÿ”— Command Line Apps Script Projects
TypeScript
4,336
star
97

ko

Build and deploy Go applications on Kubernetes
Go
4,329
star
98

santa

A binary authorization and monitoring system for macOS
Objective-C
4,288
star
99

google-ctf

Google CTF
Go
4,246
star
100

tamperchrome

Tamper Dev is an extension that allows you to intercept and edit HTTP/HTTPS requests and responses as they happen without the need of a proxy. Works across all operating systems (including Chrome OS).
TypeScript
4,148
star