Skip to main content
Every request to the HiddenLayer API must be authenticated, and it must go to the correct regional API host. This page explains how the SDKs get your credentials, how they decide where to send requests, and which client options you can change. The three SDKs follow the same rules. The examples show each language in its own tab.

Authentication methods

The SDKs support two ways to authenticate. Configure one of them.

OAuth2 client credentials

OAuth2 client credentials is a standard flow in which an application authenticates as itself by exchanging a client ID and client secret for a short-lived access token. You get a client ID and client secret when you create a client credential in the HiddenLayer Console. See Create a Client Credential. When you provide a client ID and client secret, the SDK handles the token for you:
  1. Before the first API request, the client sends a POST request to {base_url}/oauth2/token with grant_type=client_credentials, your client ID, and your client secret.
  2. The client caches the returned access token and adds it to each request as an Authorization: Bearer <token> header.
  3. The client gets a new token two minutes before the cached one expires, based on the expires_in value in the token response.
Because the token URL is built from the base URL, your credentials must belong to the same region as the base URL. A prod-eu client credential does not work against the prod-us host. If the token request fails, the call you made fails with the token endpoint’s error, such as an UnauthorizedError (HTTP 401) for a wrong client ID or client secret.

Bearer token

The SDK sends a bearer token as Authorization: Bearer <token> and never refreshes it. Use a bearer token for:
  • A HiddenLayer API key. The SDKs send an API key the same way as an access token. See Use an API Key.
  • An access token you obtain yourself. When the token expires, requests fail with HTTP 401 until you supply a new one. In Python and TypeScript, you can pass a function that returns the current token instead of a fixed value. The client calls it before every request. See Pass credentials explicitly.
Client credentials are still recommended, because a leaked access token stops working on its own within a short time.

Which credentials the client uses

If more than one credential is available, the client uses the first of these it finds. Credentials you pass to the client win over the environment, and a token wins over client credentials:
  1. A token passed to the client.
  2. A client ID and client secret passed to the client. If you pass only one of them, the client takes the other from the environment.
  3. The HIDDENLAYER_TOKEN environment variable.
  4. The HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET environment variables.
A blank value counts as not set. If the client finds no credentials at all:
The client is still created, but each request raises an ApiError (from hiddenlayer.core) whose message names the arguments and environment variables to set.

Environment variables

The client reads these environment variables when you create it. Values that you pass to the client take precedence over environment variables. All three SDKs read the same variables.
The SDKs no longer read HIDDENLAYER_LOG or HIDDENLAYER_CUSTOM_HEADERS. Configure logging and extra headers with client options instead. See Client options.

Set environment variables

Set your credentials in the terminal session that runs your code:
Replace the placeholder values with your own. These commands set the variables only for the current terminal session. In production, use your platform’s secret management, such as CI/CD secrets, a container orchestrator’s secrets, or a cloud secret manager, to inject the variables at runtime.
Typing a secret on the command line can save it in your shell history. For local development, a .env file (described next) avoids this.

Optional: use a .env file

A .env file is a plain text file of NAME=value lines that you keep in your project folder. The SDKs do not read .env files on their own.
1

Create a .env file

.env
2

Keep the file out of version control

Add .env to your .gitignore file so that you never commit your secret:
.gitignore
3

Load the file before you create the client

Install python-dotenv with python -m pip install python-dotenv, then load the file:
Call load_dotenv() before you create the client, because the client reads environment variables only when it is constructed.

Choose a region or base URL

The base URL is the root address that the client sends every request to, for example https://api.us.hiddenlayer.ai. HiddenLayer provides two SaaS environments (regions): Select the EU region:
In Python, an unknown region name, such as environment="eu", raises ValueError: Unknown environment: eu. To send requests to another host, such as a self-hosted deployment or a local AI Runtime Security container, set the base URL:

How the client resolves the base URL

The client picks the base URL in this order and uses the first match:
  1. The base URL you pass: base_url in Python, baseUrl in TypeScript, or url(...) in Java.
  2. The region you pass with environment.
  3. The HIDDENLAYER_BASE_URL environment variable, if it is set.
  4. The prod-us environment.
HIDDENLAYER_BASE_URL applies only when your code chooses neither a region nor a base URL, so passing environment overrides the variable. In Java, environment(...) and url(...) set the same value, so call only one of them.

Pass credentials explicitly

By default, the client reads credentials from environment variables. You can also pass them to the client, for example when your application loads secrets from a secret manager under different names. Read the values from your secret store or the environment. Never write them as literals in code.
To use a bearer token, such as an API key, instead, pass it as the token. In this example your application reads the key from its own HIDDENLAYER_API_KEY variable; the SDK reads a token from the environment only from HIDDENLAYER_TOKEN.
If your tokens rotate, pass a function that returns the current token. The client calls it before every request:
AsyncHiddenLayer also takes async_token, an async function. See Async client.
Do not hard-code client secrets or tokens in source files, notebooks, or container images. Anyone with access to the code can use them, and secrets committed to version control remain in the history. If a secret is exposed, regenerate the client secret in the Console.

Client options

Each SDK exposes the same settings under names that follow its language’s conventions. Python takes keyword arguments, TypeScript takes an options object, and Java uses builder methods. Failed requests are retried with exponential backoff when the response is HTTP 408, 429, or 5xx. Python also retries HTTP 409 and failed connections. Set retries to 0 to disable them. Java also has maxConcurrentRequests(int), addInterceptor(Interceptor), and settings that fine-tune retries, such as retryOnStatusCodes and initialRetryDelayMillis. For every option, see the SDK’s method reference, listed in Method reference and migration guides. Example with a custom timeout, retries, and a header:
For details on retry behavior and timeout errors, see Error handling.

Use a proxy

If your network requires an HTTP proxy, give the client an HTTP client that uses it.
Pass an httpx.Client configured with your proxy:
When you pass your own httpx.Client, the SDK uses that client’s timeout and redirect settings, so set them as shown. The proxy argument requires httpx 0.26 or later. The client also sends its token requests through the httpx.Client you pass.httpx reads the HTTPS_PROXY environment variable by default, so if it is set where your code runs, a client created without httpx_client already sends its requests through that proxy.

Override options for a single request

Every method takes request options as its last argument. Use them when one call needs different settings, such as a longer timeout for a large request. The client’s own settings are not changed.
Request options can also add headers and query parameters to one call: additional_headers and additional_query_parameters in Python, headers and queryParams in TypeScript, and addHeader and addQueryParameter in Java.

Close the client

Create one client when your application starts and reuse it for all requests. A client keeps HTTP connections open so that it can reuse them, and it caches its access token.
HiddenLayer is a context manager. Use a with block, or call close() when you are finished, to close the client’s connections:
A closed client can’t send requests. If you pass your own httpx.Client as httpx_client, the SDK never closes it, so close it yourself.For AsyncHiddenLayer, see Async client.

Async client

AsyncHiddenLayer accepts the same arguments and reads the same environment variables as HiddenLayer. Await each method call.
If the aiohttp extra is installed (python -m pip install "hiddenlayer-sdk[aiohttp]"), AsyncHiddenLayer sends its requests with aiohttp automatically.To close the client’s connections when you are done, use async with, or call await client.aclose(). With the aiohttp extra installed, this also avoids aiohttp’s Unclosed connector warning when your program exits.
If you pass your own httpx.AsyncClient as httpx_client, the SDK never closes it, so close it yourself. To send requests with aiohttp through a client of your own, pass an HttpxAiohttpClient from the httpx_aiohttp package, which the extra installs.To supply a rotating token without blocking the event loop, pass async_token, an async function that returns the current token:

Method reference and migration guides

Each SDK’s repository has a reference.md that lists every resource, method, and parameter, and a breaking-changes guide for the move from Python 3.x, TypeScript 3.x, or Java 2.x. If you are upgrading from one of those versions, read the guide first: client options, error types, and type names changed. For the changes in later releases, see Version compatibility and upgrades.

Next step

Quickstart

Make your first authenticated API call.