### Install Google APIs Client Libraries Source: https://github.com/googleapis/google-api-go-client/blob/main/README.md Use 'go get' to install specific API client libraries for your Go project. This example shows how to get the tasks, moderator, and urlshortener v1 libraries. ```shell $ go get google.golang.org/api/tasks/v1 $ go get google.golang.org/api/moderator/v1 $ go get google.golang.org/api/urlshortener/v1 ``` -------------------------------- ### Install Google API Client Library for Go Source: https://github.com/googleapis/google-api-go-client/blob/main/GettingStarted.md Use 'go get' to install a specific version of a Google API client library. This command fetches and installs the library, making it available for use in your Go projects. ```bash $ go get -u google.golang.org/api/urlshortener/v1 ``` -------------------------------- ### Install URL Shortener API v1 Source: https://github.com/googleapis/google-api-go-client/wiki/GettingStarted Use 'go get' to install a specific version of a Google API library. This command fetches and installs the urlshortener v1 API. ```bash $ go get code.google.com/p/google-api-go-client/urlshortener/v1 ``` -------------------------------- ### Impersonate Credentials Example Source: https://github.com/googleapis/google-api-go-client/blob/main/CHANGES.md Demonstrates how to use the new impersonate package for credentials. This is the recommended approach for impersonation, replacing the experimental option.ImpersonateCredentials. ```go import ( "golang.org/x/oauth2/google" "golang.org/x/oauth2/impersonate" ) func main() { // Use the new impersonate package for credentials. // See https://pkg.go.dev/google.golang.org/api/impersonate#example-CredentialsTokenSource-ServiceAccount client, err := impersonate.CredentialsTokenSource(ctx, impersonate.ServiceAccountOptions{ TargetPrincipal: "my-service-account@my-project.iam.gserviceaccount.com", Scopes: []string{cloudresourcemanager.CloudPlatformScope}, }) if err != nil { // handle error } // Use the client to create an authenticated HTTP client. authenticatedClient := google.NewClient(ctx, client) // Use the authenticated client to make API requests. // For example, to list projects: // projectsClient, err := resourcemanager.NewProjectsService(authenticatedClient) // ... } ``` -------------------------------- ### Generate Client from Local Discovery Document Source: https://github.com/googleapis/google-api-go-client/blob/main/google-api-go-generator/README.md Builds the generator and then uses a local discovery document to generate a Go client. The --cache=true flag enables caching of discovery documents, and --install ensures generated packages are installed. ```bash go build -o google-api-go-generator && ./google-api-go-generator -cache=true -install -api_json_file=/path/to/file ``` -------------------------------- ### Clone the google-api-go-client Repository Source: https://github.com/googleapis/google-api-go-client/blob/main/CONTRIBUTING.md Use this command to clone the repository to your local machine. Ensure you have Git installed. ```bash git clone https://github.com/googleapis/google-api-go-client ``` -------------------------------- ### Import URL Shortener API v1 Source: https://github.com/googleapis/google-api-go-client/wiki/GettingStarted Import the installed Google API library into your Go program. The package name is typically the API name without the version. ```go package main import ( "code.google.com/p/google-api-go-client/urlshortener/v1" ) ``` -------------------------------- ### Call URL Shortener Get Method Source: https://github.com/googleapis/google-api-go-client/wiki/GettingStarted Make a call to the 'Get' method of the 'Url' sub-service in the urlshortener API. This retrieves information about a shortened URL. ```go url, err := svc.Url.Get(shortURL).Do() if err != nil { ... } fmt.Printf("The URL %s goes to %s\n", shortURL, url.LongUrl) ``` -------------------------------- ### Conventional Commit Message Example Source: https://github.com/googleapis/google-api-go-client/blob/main/CONTRIBUTING.md Commit messages should follow the Conventional Commit specification. This example shows a commit message for adding a feature. ```git functions: add gophers codelab ``` -------------------------------- ### Instantiate API Service Source: https://github.com/googleapis/google-api-go-client/wiki/GettingStarted Create an API service instance by calling the 'New' function provided by the API library. This function requires an http.Client. ```go svc, err := urlshortener.New(httpClient) ``` -------------------------------- ### Import Google API Client Library in Go Source: https://github.com/googleapis/google-api-go-client/blob/main/GettingStarted.md Import necessary packages for interacting with Google APIs, including context, OAuth2, and the specific API client library. Ensure all required packages are listed for proper functionality. ```go package main import ( "context" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/urlshortener/v1" ) ``` -------------------------------- ### Tagging the Repository for Release Source: https://github.com/googleapis/google-api-go-client/blob/main/RELEASING.md Use this command to tag the repository with the next version during the release process. Ensure no other CLs are submitted before this step. ```bash git tag $NV ``` -------------------------------- ### Implement Wrapper for translate.Service Source: https://github.com/googleapis/google-api-go-client/blob/main/testing.md Implement the TranslateService interface by wrapping a concrete `translate.Service`. This wrapper handles the creation of the service and the translation request, abstracting the details of the Google API client's builder pattern. ```go import ( "context" "fmt" "log" "os" "google.golang.org/api/option" "google.golang.org/api/translate/v3" ) type translateService struct { svc *translate.Service } // NewTranslateService creates a TranslateService. func NewTranslateService(ctx context.Context, opts ...option.ClientOption) TranslateService { svc, err := translate.NewService(ctx, opts...) if err != nil { log.Fatalf("unable to create translate service, shutting down: %v", err) } return &translateService{svc} } func (t *translateService) TranslateText(text, language string) (string, error) { parent := fmt.Sprintf("projects/%s/locations/global", os.Getenv("GOOGLE_CLOUD_PROJECT")) resp, err := t.svc.Projects.Locations.TranslateText(parent, &translate.TranslateTextRequest{ TargetLanguageCode: language, Contents: []string{text}, }).Do() if err != nil { return "", fmt.Errorf("unable to translate text: %v", err) } return resp.Translations[0].TranslatedText, nil } ``` -------------------------------- ### Initialize Sheets Service with Service Account Key File Source: https://github.com/googleapis/google-api-go-client/blob/main/README.md Authorize the Sheets API service client using a service account JSON key file. Use option.WithAuthCredentialsFile and specify the credential type and file path. ```go client, err := sheets.NewService(ctx, option.WithAuthCredentialsFile(option.ServiceAccount, "path/to/keyfile.json")) ``` -------------------------------- ### Configure 3-legged OAuth in Go Source: https://github.com/googleapis/google-api-go-client/blob/main/GettingStarted.md Set up an oauth2.Config for 3-legged OAuth flows. This requires your application's ClientID and ClientSecret, obtained from the Google Cloud Console, and the desired API scopes. ```go var config = &oauth2.Config{ ClientID: "", // from https://console.developers.google.com/project//apiui/credential ClientSecret: "", // from https://console.developers.google.com/project//apiui/credential Endpoint: google.Endpoint, Scopes: []string{urlshortener.UrlshortenerScope}, } ``` -------------------------------- ### Initialize URL Shortener Service Source: https://github.com/googleapis/google-api-go-client/blob/main/README.md Basic Go code to initialize the URL Shortener API service client using the default context. Ensure you handle the error returned by NewService. ```go package main import ( "context" "net/http" "google.golang.org/api/urlshortener/v1" ) func main() { ctx := context.Background() svc, err := urlshortener.NewService(ctx) // ... } ``` -------------------------------- ### Refresh Existing Client Source: https://github.com/googleapis/google-api-go-client/blob/main/google-api-go-generator/README.md Builds the generator and refreshes an existing client. It disables caching (--cache=false) to ensure the latest discovery document is fetched, specifies the API and version to refresh (--api=sevicename:vsomething), and sets the output directory (--gendir=..). ```bash go build -o google-api-go-generator && ./google-api-go-generator -cache=false -install -api=sevicename:vsomething -gendir=.. ``` -------------------------------- ### Generating Go Client Code Source: https://github.com/googleapis/google-api-go-client/blob/main/RELEASING.md This command is used to generate or update the Go client code. It is typically run from the 'internal/version' directory. ```bash go generate ``` -------------------------------- ### Pushing the Release Tag Source: https://github.com/googleapis/google-api-go-client/blob/main/RELEASING.md After tagging the repository, push the tag to the origin to make the release public. This is a crucial step in the release workflow. ```bash git push origin $NV ``` -------------------------------- ### Initialize Sheets Service with Default Credentials Source: https://github.com/googleapis/google-api-go-client/blob/main/README.md Initialize the Google Sheets API service client using the default context and Application Default Credentials for authorization. ```go // import "google.golang.org/api/sheets/v4" client, err := sheets.NewService(ctx) ``` -------------------------------- ### Add a Remote Fork Source: https://github.com/googleapis/google-api-go-client/blob/main/CONTRIBUTING.md After forking the repository, set up your fork as a remote named 'fork'. Replace GITHUB_USERNAME with your GitHub username. ```bash git remote add fork git@github.com:GITHUB_USERNAME/google-api-go-client.git ``` -------------------------------- ### Define Lightweight Mock for TranslateService Source: https://github.com/googleapis/google-api-go-client/blob/main/testing.md Define a lightweight mock implementation of the TranslateService interface for use in tests. This mock returns a predefined string and nil error, simplifying the testing of functions that depend on the TranslateService. ```go import "testing" // mockService fulfills the TranslateService interface. type mockService struct{} func (*mockService) TranslateText(text, language string) (string, error) { return "Hello World", nil } func TestTranslateTextHighLevel(t *testing.T) { svc := &mockService{} text, err := TranslateTextHighLevel(svc, "Hola Mundo", "en-US") if err != nil { t.Fatal(err) } if text != "Hello World" { t.Fatalf("got %q, want Hello World", text) } } ``` -------------------------------- ### Initialize Sheets Service with Token Source Source: https://github.com/googleapis/google-api-go-client/blob/main/README.md Authorize the Sheets API service client by providing an oauth2.TokenSource. This offers more control over the authorization process. ```go tokenSource := ... svc, err := sheets.NewService(ctx, option.WithTokenSource(tokenSource)) ``` -------------------------------- ### Running All Generation Tasks Source: https://github.com/googleapis/google-api-go-client/blob/main/RELEASING.md This command executes all necessary generation tasks for the clients. It is used by the nightly cron job for auto-regeneration. ```bash make all ``` -------------------------------- ### OAuth2 Configuration Source: https://github.com/googleapis/google-api-go-client/wiki/GettingStarted Define the OAuth2 configuration, including Client ID, Client Secret, scopes, and authentication URLs. Obtain Client ID and Secret from the Google API Console. ```go var config = &oauth.Config{ ClientId: "", // from https://code.google.com/apis/console/ ClientSecret: "", // from https://code.google.com/apis/console/ Scope: urlshortener.UrlshortenerScope, AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", } ``` -------------------------------- ### Test Translate Text Function with Fake HTTP Server Source: https://github.com/googleapis/google-api-go-client/blob/main/testing.md Tests the `TranslateText` function by creating a fake HTTP server using `httptest`. This fake server intercepts requests and returns predefined responses, allowing the test to run without making actual network calls. It uses `option.WithoutAuthentication()` and `option.WithEndpoint` to configure the service to use the test server. ```go import ( "context" "encoding/json" "net/http" "net/http/httptest" "testing" "google.golang.org/api/option" "google.golang.org/api/translate/v3" ) func TestTranslateText(t *testing.T) { ctx := context.Background() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { resp := &translate.TranslateTextResponse{ Translations: []*translate.Translation{ {TranslatedText: "Hello World"}, }, } b, err := json.Marshal(resp) if err != nil { http.Error(w, "unable to marshal request: "+err.Error(), http.StatusBadRequest) return } w.Write(b) })) defer ts.Close() svc, err := translate.NewService(ctx, option.WithoutAuthentication(), option.WithEndpoint(ts.URL)) if err != nil { t.Fatalf("unable to create client: %v", err) } text, err := TranslateText(svc, "Hola Mundo", "en-US") if err != nil { t.Fatal(err) } if text != "Hello World" { t.Fatalf("got %q, want Hello World", text) } } ``` -------------------------------- ### Initialize Sheets Service with JSON Credentials Source: https://github.com/googleapis/google-api-go-client/blob/main/README.md Authorize the Sheets API service client directly using JSON credentials provided as a byte slice. Specify the credential type and the JSON key data. ```go // where jsonKey is a []byte containing the JSON key client, err := sheets.NewService(ctx, option.WithAuthCredentialsJSON(option.ServiceAccount, jsonKey)) ``` -------------------------------- ### Use API Key for Google API Authentication in Go Source: https://github.com/googleapis/google-api-go-client/blob/main/GettingStarted.md Authenticate Google API requests using an API key by creating an http.Client with a transport that includes the key. This is suitable for APIs that do not require user authorization. ```go ctx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{ Transport: &transport.APIKey{Key: developerKey}, }) oauthConfig := &oauth2.Config{ .... } var token *oauth2.Token = .... // via cache, or oauthConfig.Exchange httpClient := oauthConfig.Client(ctx, token) svc, err := urlshortener.New(httpClient) ... ``` -------------------------------- ### Create OAuth Transport Client Source: https://github.com/googleapis/google-api-go-client/wiki/GettingStarted Create an http.Client using an oauth.Transport. This client will automatically add OAuth2 authorization headers to requests. ```go transport := &oauth.Transport{ Token: token, Config: config, Transport: http.DefaultTransport, } httpClient := transport.Client() ``` -------------------------------- ### API Key HTTP Client Source: https://github.com/googleapis/google-api-go-client/wiki/GettingStarted Create an http.Client that uses transport.APIKey to add an API key to requests. This is used for APIs that require API key authentication. ```go client := &http.Client{ Transport: &transport.APIKey{Key: developerKey}, } ``` -------------------------------- ### Define High-Level TranslateService Interface Source: https://github.com/googleapis/google-api-go-client/blob/main/testing.md Define a high-level interface for the TranslateText method to abstract the underlying service's complexity. This interface is used by functions that need to translate text, allowing for easy substitution of real services with mocks during testing. ```go // TranslateService is a facade of a `translate.Service`, specifically used to // for translating text. type TranslateService interface { TranslateText(text, language string) (string, error) } // TranslateTextHighLevel translates text to the given language using the // provided service. func TranslateTextHighLevel(service TranslateService, text, language string) (string, error) { return service.TranslateText(text, language) } ``` -------------------------------- ### Handle Google API Errors in Go Source: https://github.com/googleapis/google-api-go-client/blob/main/GettingStarted.md Check for specific Google API errors, such as 'Not Found' (http.StatusNotFound), by performing a type assertion on the returned error. This allows for granular error handling based on the API response. ```go url, err := svc.Url.Get(shortURL).Do() if err != nil { if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound { ... } } ``` -------------------------------- ### Translate Text Function Source: https://github.com/googleapis/google-api-go-client/blob/main/testing.md A function that translates text using the Google Translate API. It requires a `translate.Service` object, the text to translate, and the target language code. Ensure the `GOOGLE_CLOUD_PROJECT` environment variable is set. ```go import ( "fmt" "os" "google.golang.org/api/translate/v3" ) // TranslateText translates text to the given language using the provided // service. func TranslateText(service *translate.Service, text, language string) (string, error) { parent := fmt.Sprintf("projects/%s/locations/global", os.Getenv("GOOGLE_CLOUD_PROJECT")) req := &translate.TranslateTextRequest{ TargetLanguageCode: language, Contents: []string{text}, } resp, err := service.Projects.Locations.TranslateText(parent, req).Do() if err != nil { return "", fmt.Errorf("unable to translate text: %v", err) } return resp.Translations[0].TranslatedText, nil } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.