Set user agent

Set a custom user agent on a BigQuery client.

Code sample

Java

Before trying this sample, follow the Java setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Java API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;

public class SetUserAgent {

  private static final String USER_AGENT_HEADER = "user-agent";

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String customUserAgentValue = "my-custom-user-agent-value";
    setUserAgent(projectId, customUserAgentValue);
  }

  public static void setUserAgent(String projectId, String customUserAgentValue)
      throws IOException {
    // Setup the credentials
    GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();

    // Initialize the HeaderProvider object with custom user agent value
    HeaderProvider headerProvider =
        FixedHeaderProvider.create(ImmutableMap.of(USER_AGENT_HEADER, customUserAgentValue));

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    BigQuery bigQuery =
        BigQueryOptions.newBuilder()
            .setProjectId(projectId)
            .setCredentials(googleCredentials)
            .setHeaderProvider(headerProvider)
            .build()
            .getService();

    System.out.println(bigQuery.getOptions().getUserAgent());
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Node.js API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
// Create a client and set the user agent
const bigquery = new BigQuery({userAgent: 'my-user-agent'});

console.log('User agent:');
console.log(bigquery.providedUserAgent);

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.