Initializing Your Java Client

August 30, 2022 ยท View on GitHub

The first step to using your generated client in code is to import and initialize your client. Our SDKs are modelled such that the client is the main point of access to the generated code.

Importing Your Client

You include the generated client through Maven. In your application's pom.xml add a dependency with groupId, artifactId, and version specified in the generated client's pom.xml file. For the sake for this example, let's say the groupId is the same as the package name specified when generating (under flag --namespace), the artifactId is azure-pets, and the version is 1.0.0-beta.1.

<dependencies>
  <dependency>
    <groupId>com.azure.pets</groupId>
    <artifactId>azure-pets</artifactId>
    <version>1.0.0-beta.1</version>
  </dependency>
</dependencies>

Once this is included in your pom, you are free to use your client without specific imports!

Initializing and Authenticating Your Client

Your client's name is detailed in the swagger, (TODO link to swagger docs), and let's say ours is called PetsClient. We use builders to build our client, with each builder being the service client's name + suffix Builder(). The builder takes in any number of parameters, and ultimately calls buildClient(), which ultimately what returns the built client.

package com.azure.pets;

public static void main(String args[])
{
    PetsClient client = new PetsClientBuilder().buildClient();
}

You can also install your client with a credential, using the flag --credential-types. If you generate with --credential-types=TokenCredential, your client will take in an Azure Active Directory (AAD) token credential. We always recommend using a credential type obtained from the com.azure.identity package for AAD authentication. For this example, we use the most common DefaultAzureCredential.

As an installation note, the com.azure.identity is not listed as a dependency in the pom we generate (see --regenerate-pom in our flag index for more information), so you would need to install this library separately.

package com.azure.pets;

import com.azure.identity.DefaultAzureCredentialBuilder;

public static void main(String args[])
{
    PetsClient client = new PetsClientBuilder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();
}

You can also have your generated client take in an AzureKeyCredential instead. To do so, generate with flag --credential-types=AzureKeyCredential, and for more information on this flag, see our flag index

package com.azure.pets;

import com.azure.core.credential.AzureKeyCredential;

public static void main(String args[])
{
    PetsClient client = new PetsClientBuilder()
        .credential(new AzureKeyCredential("{key}"))
        .buildClient();
}

Currently, we only support generating credentials of type TokenCredential and / or AzureKeyCredential.