You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GettingStarted.md 4.5 KiB

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