1# Getting Started with the Google APIs for Go 2 3## Getting Started 4 5This is a quick walk-through of how to get started with the Google APIs for Go. 6 7## Background 8 9The first thing to understand is that the Google API libraries are auto-generated for 10each language, including Go, so they may not feel like 100% natural for any language. 11The Go versions are pretty natural, but please forgive any small non-idiomatic things. 12(Suggestions welcome, though!) 13 14## Installing 15 16Pick an API and a version of that API to install. 17You can find the complete list by looking at the 18[directories here](https://github.com/google/google-api-go-client/tree/master/). 19 20For example, let's install the 21[urlshortener's version 1 API](https://godoc.org/google.golang.org/api/urlshortener/v1): 22 23``` 24$ go get -u google.golang.org/api/urlshortener/v1 25``` 26 27Now it's ready for use in your code. 28 29## Using 30 31Once you've installed a library, you import it like this: 32 33```go 34package main 35 36import ( 37 "context" 38 "golang.org/x/oauth2" 39 "golang.org/x/oauth2/google" 40 "google.golang.org/api/urlshortener/v1" 41) 42``` 43 44The package name, if you don't override it on your import line, is the name of the 45API without the version number. In the case above, just `urlshortener`. 46 47## Instantiating 48 49Each API has a `New` function taking an `*http.Client` and returning an API-specific `*Service`. 50 51You create the service like: 52 53```go 54 svc, err := urlshortener.New(httpClient) 55``` 56 57## OAuth HTTP Client 58 59The HTTP client you pass in to the service must be one that automatically adds 60Google-supported Authorization information to the requests. 61 62There are several ways to do authentication. They will all involve the package 63[golang.org/x/oauth2](https://godoc.org/golang.org/x/oauth2) in some way. 64 65### 3-legged OAuth 66 67For 3-legged OAuth (your application redirecting a user through a website to get a 68token giving your application access to that user's resources), you will need to 69create an oauth2.Config, 70 71 72```go 73 var config = &oauth2.Config{ 74 ClientID: "", // from https://console.developers.google.com/project/<your-project-id>/apiui/credential 75 ClientSecret: "", // from https://console.developers.google.com/project/<your-project-id>/apiui/credential 76 Endpoint: google.Endpoint, 77 Scopes: []string{urlshortener.UrlshortenerScope}, 78 } 79``` 80 81... and then use the AuthCodeURL, Exchange, and Client methods on it. 82For an example, see: https://godoc.org/golang.org/x/oauth2#example-Config 83 84For the redirect URL, see 85https://developers.google.com/identity/protocols/OAuth2InstalledApp#choosingredirecturi 86 87### Service Accounts 88 89To use a Google service account, or the GCE metadata service, see 90the [golang.org/x/oauth2/google](https://godoc.org/golang.org/x/oauth2/google) package. 91In particular, see [google.DefaultClient](https://godoc.org/golang.org/x/oauth2/google#DefaultClient). 92 93### Using API Keys 94 95Some APIs require passing API keys from your application. 96To do this, you can use 97[transport.APIKey](https://godoc.org/google.golang.org/api/googleapi/transport#APIKey): 98 99```go 100 ctx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{ 101 Transport: &transport.APIKey{Key: developerKey}, 102 }) 103 oauthConfig := &oauth2.Config{ .... } 104 var token *oauth2.Token = .... // via cache, or oauthConfig.Exchange 105 httpClient := oauthConfig.Client(ctx, token) 106 svc, err := urlshortener.New(httpClient) 107 ... 108``` 109 110## Using the Service 111 112Each service contains zero or more methods and zero or more sub-services. 113The sub-services related to a specific type of "Resource". 114 115Those sub-services then contain their own methods. 116 117For instance, the urlshortener API has just the "Url" sub-service: 118 119```go 120 url, err := svc.Url.Get(shortURL).Do() 121 if err != nil { 122 ... 123 } 124 fmt.Printf("The URL %s goes to %s\n", shortURL, url.LongUrl) 125``` 126 127For a more complete example, see 128[urlshortener.go](https://github.com/google/google-api-go-client/tree/master/examples/urlshortener.go) 129in the [examples directory](https://github.com/google/google-api-go-client/tree/master/examples/). 130(the examples use some functions in `main.go` in the same directory) 131 132## Error Handling 133 134Most errors returned by the `Do` methods of these clients will be of type 135[`googleapi.Error`](https://godoc.org/google.golang.org/api/googleapi#Error). 136Use a type assertion to obtain the HTTP status code and other properties of the 137error: 138 139```go 140 url, err := svc.Url.Get(shortURL).Do() 141 if err != nil { 142 if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound { 143 ... 144 } 145 } 146``` 147