Getting started with client libraries
The Google Cloud Libraries for .NET are a mixture of handwritten and autogenerated libraries connecting to Google Cloud services. The handwritten libraries (such as Google.Cloud.Firestore and Google.Cloud.Spanner.Data) are mostly higher level abstractions over the underlying API. See the documentation for those individual libraries for details; the documentation here is primarily aimed at the autogenerated libraries.
If you haven't already found the library for the API you're interested in, please consult the list of .NET libraries which shows both the NuGet package name and the link to the library-specific documentation. In particular, each library has:
- A "getting started" page which lists the client types within that library
- Version history for the library
- API reference documentation
This page demonstrates using the Google.Cloud.Translate.V3 API as a simple example; the steps required for other APIs are very similar.
Prerequisites
All Google Cloud APIs require a Google Cloud project. If you haven't set one up already, please create one. You'll also need to enable your chosen API if it hasn't already been used within that Google Cloud project.
There are no specific tools required to develop using the Google Cloud Libraries for .NET. All development environments should work, but you should check that you're targeting a supported platform.
We recommend installing the gcloud CLI.
Install the library
All Google Cloud Libraries for .NET are available from nuget.org and can be installed using any NuGet package manager. If the version you wish to is install a pre-release version, please ensure you enable pre-release packages (for example, in the Visual Studio NuGet user interface, check the "Include prerelease" box).
The libraries can be installed in any regular project type - for example, console applications, GUI applications such as WinForms and WPF, ASP.NET Core applications, and class libraries.
For the translation example, we'll create a console application using the dotnet
tooling
and install the package.
Note that for simplicity, the sample code below uses synchronous calls - but all methods have asynchronous equivalents, including client construction. Within naturally asynchronous environments such as web applications, we recommend the use of the asynchronous methods.
mkdir TranslationExample
cd TranslationExample
dotnet new console
dotnet add package Google.Cloud.Translate.V3
Dependencies
If you install the library in an interactive environment such as Visual Studio, you may notice a lot of transitive dependencies being installed. This is entirely expected, but you may not recognize some of those dependencies. The list below is not comprehensive, but highlights some of the packages you'll see being installed.
- Google.Protobuf: the library supporting the Protocol Buffers seralization format
- Google.Api.Gax, Google.Api.Gax.Grpc: support libraries specifically tailored for the Google Cloud client libraries
- Google.Apis.Auth, Google.Apis, Google.Apis.Core: authentication support for Google Cloud credentials
- Grpc.Auth, Grpc.Core.Api, Grpc.Net.Client, Grpc.Net.Common: support for the gRPC RPC protocol
- Google.LongRunning: support for long-running operations
Create a client
The first step in making any API calls is to create a client. Some libraries have multiple clients
for operations involving different resources; others have a single client. In the Translation API
we're using, there's just TranslationServiceClient
.
Clients can be configured in a number of ways, but in many cases the defaults are fine. The most common reason to use explicit configuration is to use specific credentials for authentication. For this example, we'll just use Application Default Credentials (ADC). To set up ADC in your local environment, follow the instructions in Local development environment. When you create a client, it automatically detects and uses these credentials.
Each client class has static Create
and CreateAsync
methods to create clients using all the default settings.
So in this case we can just use:
using Google.Cloud.Translate.V3;
var client = TranslationServiceClient.Create();
In applications that use dependency injection via Microsoft.Extensions.DependencyInjection, we recommend using dependency injection for client construction. See the client lifecycle documentation on dependency injection for details.
Make requests
The Google Cloud Libraries use Protocol Buffers to represent requests and responses, with some additional types to make the APIs more convenient to work with.
Most APIs are expressed in terms of a single request returning a single response, although
there are also some streaming APIs involving multiple requests and/or multiple responses.
For our Translation API example, we'll create a simple request for the TranslateText
API.
using Google.Api.Gax.ResourceNames;
...
string projectId = "your-project-id-here";
string locationId = "global";
var request = new TranslateTextRequest
{
Contents = { "It is raining.", "It is sunny." },
TargetLanguageCode = "fr-FR",
ParentAsLocationName = new LocationName(projectId, locationId)
};
var response = client.TranslateText(request);
This example demonstrates a few features:
- Protocol Buffer messages always have parameterless constructors and support object initializers
- The
Contents
property is a read-only property of typeRepeatedField<string>
- the code above doesn't assign a new value to the property; instead it uses a collection initializer to populate the repeated field - The Translate library has added an extra
ParentAsLocationName
property to the message. There's aParent
property which is just of typestring
, but usingParentAsLocationName
allows resource names to be handled in a type-safe manner, and you don't need to concern yourself with the underlying resource name format. For more details, see the resource names documentation.
The Google Cloud Libraries always expose methods accepting an API request directly, but in some cases additional overloads are provided for convenience. In this particular case, we could have used:
var response = client.TranslateText(
new LocationName(projectId, locationId),
"fr-FR",
new[] { "It is raining.", "It is sunny." });
The convenience methods don't always cover all possible aspects of the request.
For example, TranslateTextRequest
has a MimeType
property which can easily be set when
using the code creating a full request, but can't be specified in the convenience method.
The response is also a Protocol Buffers message. Calling ToString()
on any message will return the JSON
representation of the message, which can be useful to see the structure of a response when using a specific
API for the first time. In this case we'll just look at the Translations
property though:
Console.WriteLine($"Translations returned: {response.Translations.Count}");
Console.WriteLine();
foreach (var translation in response.Translations)
{
Console.WriteLine($"Detected language: {translation.DetectedLanguageCode}");
Console.WriteLine($"Translated text: {translation.TranslatedText}");
Console.WriteLine();
}
This produces output of:
Translations returned: 2
Detected language: en
Translated text: Il pleut.
Detected language: en
Translated text: Il fait beau.
The complete code is:
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
var client = TranslationServiceClient.Create();
string projectId = "your-project-id-here";
string locationId = "global";
var request = new TranslateTextRequest
{
Contents = { "It is raining.", "It is sunny." },
TargetLanguageCode = "fr-FR",
ParentAsLocationName = new LocationName(projectId, locationId)
};
var response = client.TranslateText(request);
Console.WriteLine($"Translations returned: {response.Translations.Count}");
Console.WriteLine();
foreach (var translation in response.Translations)
{
Console.WriteLine($"Detected language: {translation.DetectedLanguageCode}");
Console.WriteLine($"Translated text: {translation.TranslatedText}");
Console.WriteLine();
}
This is just a simple example, which hasn't touched on page streaming or specifying call settings for example.
Getting help
If you run into problems with the Google Cloud Libraries for .NET, help is available. Please read the Support guide for more information about the most effective way to ask for help.