> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiddenlayer.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Core concepts

> Understand the client, resources, request and response types, pagination, Beta APIs, retries, and the other building blocks the HiddenLayer SDKs for Python, TypeScript, and Java share.

This page explains the ideas you use in every program built on a HiddenLayer SDK. The Python, TypeScript, and Java SDKs share one design: a client, resources grouped by product area, typed requests and responses, and the same authentication, retry, and pagination behavior. Where the languages differ, the examples show each one in its own tab.

Read this page once before you start the workflow guides. Each section links to a page with more detail.

## The client

The **client** is the object that holds your configuration (credentials, region, timeouts, retries) and sends requests to the HiddenLayer API.

| Language | Client | Import | Calls |
| - | - | - | - |
| Python | `HiddenLayer` | `from hiddenlayer import HiddenLayer` | Synchronous |
| Python | `AsyncHiddenLayer` | `from hiddenlayer import AsyncHiddenLayer` | Coroutines you `await` |
| TypeScript | `HiddenLayer` | `import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk"` | Promises you `await` |
| Java | `HiddenLayerClient`, built with `new HiddenLayerClientBuilder()` | `com.hiddenlayer.api.HiddenLayerClient` | Synchronous |
| Java | `AsyncHiddenLayerClient`, built with `new AsyncHiddenLayerClientBuilder()` | `com.hiddenlayer.api.AsyncHiddenLayerClient` | Each method returns a `CompletableFuture` |

In Python and Java, the synchronous and asynchronous clients take the same options and have the same methods. Every method of the TypeScript client is asynchronous.

The following example creates a client from environment credentials and prints the five most recent scans.

> [tab] Python
>
> ```python Sync theme={null}
> from hiddenlayer import HiddenLayer
>
> # Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET from the environment.
> client = HiddenLayer()
>
> page = client.scans.jobs.list(limit=5)
> print(f"{int(page.response.total)} scans in total")
> for scan in page.items or []:
>     print(scan.scan_id, scan.inventory.model_name, scan.status)
> ```
>
> ```python Async theme={null}
> import asyncio
>
> from hiddenlayer import AsyncHiddenLayer
>
>
> async def main() -> None:
>     # Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET from the environment.
>     client = AsyncHiddenLayer()
>
>     page = await client.scans.jobs.list(limit=5)
>     print(f"{int(page.response.total)} scans in total")
>     for scan in page.items or []:
>         print(scan.scan_id, scan.inventory.model_name, scan.status)
>
>
> asyncio.run(main())
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> // Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET from the environment.
> const client = new HiddenLayer();
>
> const page = await client.scans.jobs.list({ limit: 5 });
> console.log(`${page.response.total} scans in total`);
> for (const scan of page.data) {
>     console.log(scan.scan_id, scan.inventory.model_name, scan.status);
> }
> ```

> [tab] Java
>
> ```java Sync theme={null}
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
> import com.hiddenlayer.api.core.pagination.SyncPagingIterable;
> import com.hiddenlayer.api.resources.scans.jobs.requests.ListJobsRequest;
> import com.hiddenlayer.api.resources.scans.jobs.types.ListJobsResponse;
> import com.hiddenlayer.api.types.ScanReportOfRecordV3Summary;
>
> public class CcClientSync {
>     public static void main(String[] args) {
>         // Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET from the environment.
>         try (HiddenLayerClient client = new HiddenLayerClientBuilder().build()) {
>             SyncPagingIterable<ScanReportOfRecordV3Summary> page =
>                     client.scans().jobs().list(ListJobsRequest.builder().limit(5).build());
>             page.<ListJobsResponse>getResponse()
>                     .ifPresent(response -> System.out.println((long) response.getTotal() + " scans in total"));
>             for (ScanReportOfRecordV3Summary scan : page.getItems()) {
>                 System.out.println(scan.getScanId() + " " + scan.getInventory().getModelName() + " " + scan.getStatus());
>             }
>         }
>     }
> }
> ```
>
> ```java Async theme={null}
> import com.hiddenlayer.api.AsyncHiddenLayerClient;
> import com.hiddenlayer.api.AsyncHiddenLayerClientBuilder;
> import com.hiddenlayer.api.resources.scans.jobs.requests.ListJobsRequest;
> import com.hiddenlayer.api.types.ScanReportOfRecordV3Summary;
>
> public class CcClientAsync {
>     public static void main(String[] args) {
>         try (AsyncHiddenLayerClient client = new AsyncHiddenLayerClientBuilder().build()) {
>             client.scans().jobs().list(ListJobsRequest.builder().limit(5).build())
>                     .thenAccept(page -> {
>                         for (ScanReportOfRecordV3Summary scan : page.getItems()) {
>                             System.out.println(scan.getScanId() + " " + scan.getStatus());
>                         }
>                     })
>                     .join();
>         }
>     }
> }
> ```

### Create one client and reuse it

Create the client once (for example at application startup) and share it. Reusing a client matters for two reasons:

* **Connection reuse.** The client keeps HTTP connections open, so later requests are faster.
* **Token caching.** With client ID and client secret authentication, the client requests an access token on its first call, caches it, and requests a new one shortly before it expires. A new client per request would fetch a new token every time.

How you release a client's resources depends on the language:

> [tab] Python
>
> `HiddenLayer` and `AsyncHiddenLayer` are context managers. Use `with HiddenLayer() as client:` or `async with AsyncHiddenLayer() as client:`, or call `client.close()` or `await client.aclose()` when your application shuts down. Closing releases the client's connections, and a closed client can't send requests. An `httpx.Client` (or `httpx.AsyncClient`) that you pass as `httpx_client` stays open, so close that yourself. See [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md#close-the-client).

> [tab] TypeScript
>
> The client has nothing to close. It sends requests with the global `fetch` (or the `fetch` function you pass in the `fetch` option).

> [tab] Java
>
> `HiddenLayerClient` and `AsyncHiddenLayerClient` implement `AutoCloseable`. Each client has its own connection pool, which `close()` releases, so use try-with-resources or call `close()` when your application shuts down. Always close an `AsyncHiddenLayerClient`: its scanners run on threads of their own, which keep the JVM alive until `close()` stops them.

## Resources and methods

The client groups API operations into **resources**. You call an operation on a resource, and some resources are nested. The naming follows each language's conventions:

| | Python | TypeScript | Java |
| - | - | - | - |
| Resource access | `client.scans.results` | `client.scans.results` | `client.scans().results()` |
| Method names | `snake_case`: `retrieve_summary` | `camelCase`: `retrieveSummary` | `camelCase`: `retrieveSummary` |
| Path parameters | Positional arguments: `retrieve_summary(scan_id)` | Fields of the request object: `retrieveSummary({ scan_id })` | Leading `String` arguments: `retrieveSummary(scanId)` |
| Body and query parameters | Keyword arguments | Fields of the request object, with the API's `snake_case` names | A request object built with a builder |

The following table lists the resources the workflow guides use. Resource names are shown in Python form. The SDKs cover every public operation in the HiddenLayer API, so the client also has resources such as `access`, `asset_inventory`, `audit`, `compliance`, `governance`, and `metrics`. See the [API reference](https://docs.hiddenlayer.ai/docs/integrations/sdk/api_reference.md) for every language's names.

| Resource | Product area | Status |
| - | - | - |
| `model_scanner` | AI Supply Chain Security: scan local files and folders, and (Python and TypeScript) models in S3, Azure Blob Storage, and Hugging Face | High-level helper |
| `community_scanner` | AI Supply Chain Security: scan a model at a remote location that HiddenLayer fetches | High-level helper |
| `scans.jobs` | AI Supply Chain Security: list, retrieve, and request scans | Generally available |
| `scans.results` | AI Supply Chain Security: scan summary, paginated file results, SARIF export | Generally available |
| `scans.upload`, `scans.upload.file` | AI Supply Chain Security: multipart upload steps | Generally available |
| `models` | AI Supply Chain Security: retrieve and delete models | Generally available |
| `models.cards` | Model cards listing | **Deprecated** in favor of the asset inventory API |
| `runtime` | AI Runtime Security: the v2 evaluation endpoints for requests, responses, and interactions | Generally available |
| `interactions` | AI Runtime Security: the v1 Interactions endpoint | Generally available. New integrations use `runtime`. |
| `prompt_analyzer` | Prompt Analyzer | Generally available |
| `evaluations.red_team` | AI Attack Simulation: red team workflow endpoints | **Beta** |
| `evaluation_sessions.red_team` | AI Attack Simulation: session helper with polling and callbacks (Python only) | **Beta** (wraps Beta endpoints) |
| `sensors` | Sensors | **Deprecated**: the API says each endpoint "will be removed after April 13, 2026" |

## High-level helpers and API resources

Most resources map one-to-one to a REST endpoint: one method call sends one HTTP request.

A few attributes are **high-level helpers** built on top of those resources. Which helpers exist depends on the language:

| Helper | What it does | Python | TypeScript | Java |
| - | - | - | - | - |
| Model scanner | Uploads model files in parts, starts the scan, polls until it finishes, and collects the file results into one report | `client.model_scanner` | `client.modelScanner` | `client.modelScanner()` |
| Cloud and Hugging Face scans | Downloads a model from S3, Azure Blob Storage, or Hugging Face, then scans it | Yes | Yes | No. Download the model with the provider's SDK, then scan the folder. |
| Community scanner | Asks HiddenLayer to fetch and scan a model from a remote location, then optionally waits for results | `client.community_scanner` | `client.communityScanner` | `client.communityScanner()` |
| Red team session helper | Starts a red team workflow and drives it with polling, iteration, or a callback function | `client.evaluation_sessions.red_team` | No. Call `evaluations.redTeam` directly. | No. Call `evaluations().redTeam()` directly. |

Start with the helpers for common tasks. Use the API resources when you need control the helpers do not offer, such as listing past scans or exporting SARIF. The [API usage examples](https://docs.hiddenlayer.ai/docs/integrations/sdk/api_examples.md) page shows recipes that use them.

## Environments and base URL

An **environment** is the HiddenLayer region your account lives in. The client turns the environment into a **base URL**, the address every request starts with.

| Environment | Python | TypeScript | Java | Base URL |
| - | - | - | - | - |
| US (default) | `"prod-us"` or `HiddenLayerEnvironment.PROD_US` | `"prod-us"` or `HiddenLayerEnvironment.ProdUs` | `Environment.PROD_US` | `https://api.us.hiddenlayer.ai` |
| EU | `"prod-eu"` or `HiddenLayerEnvironment.PROD_EU` | `"prod-eu"` or `HiddenLayerEnvironment.ProdEu` | `Environment.PROD_EU` | `https://api.eu.hiddenlayer.ai` |

The client chooses the base URL in this order:

1. The base URL option: `base_url` (Python), `baseUrl` (TypeScript), or `url(...)` on the builder (Java).
2. The `environment` option.
3. The `HIDDENLAYER_BASE_URL` environment variable, read only when neither option is given.
4. The US region.

Use the base URL option for a self-hosted endpoint, such as a local AI Runtime Security container.

Credentials are region specific, because the token request goes to the same base URL. Use credentials created in the same region you connect to.

## Authentication

The client supports two kinds of credentials:

* **OAuth2 client credentials** (recommended). Your program exchanges a client ID and client secret for a short-lived access token. Set `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET`. The client fetches, caches, and refreshes the token for you.
* **A token.** Set `HIDDENLAYER_TOKEN` to an API key or an access token you obtained elsewhere. The client sends it as a bearer token and does not refresh it.

Options passed to the client win over environment variables, and a token wins over client credentials. See [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md) for the full resolution order and setup steps.

## Request types

Every SDK types its requests, so editors can autocomplete fields and the compiler or type checker can flag mistakes. The shape of a request depends on the language. The following example evaluates a user prompt with the [Runtime Security](https://docs.hiddenlayer.ai/docs/integrations/sdk/runtime_security.md) interaction-evaluations endpoint.

> [tab] Python
>
> Arguments are keyword arguments. Nested objects, such as `metadata` and `interaction`, are Pydantic models you import from `hiddenlayer`. A plain `dict` with the same keys is still sent correctly, but a type checker such as Pyright or mypy reports it.
>
> ```python theme={null}
> from hiddenlayer import (
>     CanonicalInteraction,
>     CanonicalInteractionMessage,
>     ContentPart_Text,
>     HiddenLayer,
>     InteractionEvaluationRequestMetadata,
> )
>
> client = HiddenLayer()
>
> result = client.runtime.evaluate_interaction(
>     metadata=InteractionEvaluationRequestMetadata(
>         model="gpt-4o",
>         provider="openai",
>         requester_id="user-1234",
>     ),
>     interaction=CanonicalInteraction(
>         messages=[
>             CanonicalInteractionMessage(
>                 role="user",
>                 content=[ContentPart_Text(text="What is the capital of France?")],
>             )
>         ]
>     ),
>     hl_project_id="customer-support-bot",
> )
> print(result.outcome.action)
> ```

> [tab] TypeScript
>
> Each method takes one plain object. Its fields keep the API's names, so they are `snake_case`, and headers such as `HL-Project-Id` are quoted keys. Request and response types are in the `HiddenLayerApi` namespace.
>
> ```typescript theme={null}
> import { HiddenLayer, type HiddenLayerApi } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
>
> const request: HiddenLayerApi.InteractionEvaluationRequest = {
>     "HL-Project-Id": "customer-support-bot",
>     metadata: { model: "gpt-4o", provider: "openai", requester_id: "user-1234" },
>     interaction: {
>         messages: [{ role: "user", content: [{ type: "text", text: "What is the capital of France?" }] }],
>     },
> };
>
> const result = await client.runtime.evaluateInteraction(request);
> console.log(result.outcome.action);
> ```

> [tab] Java
>
> Requests are built with **staged builders**: you set each required field, in the order the builder offers them, before the optional fields and `build()`. A missing required field is a compile error. A field that can hold more than one shape, such as `interaction`, takes a union type created with `of(...)`.
>
> ```java theme={null}
> import com.hiddenlayer.api.resources.runtime.requests.InteractionEvaluationRequest;
> import com.hiddenlayer.api.resources.runtime.types.InteractionEvaluationRequestInteraction;
> import com.hiddenlayer.api.types.CanonicalInteraction;
> import com.hiddenlayer.api.types.CanonicalInteractionMessage;
> import com.hiddenlayer.api.types.ContentPart;
> import com.hiddenlayer.api.types.InteractionEvaluationRequestMetadata;
> import com.hiddenlayer.api.types.InteractionEvaluationResponse;
> import com.hiddenlayer.api.types.TextPart;
>
> InteractionEvaluationResponse result = client.runtime().evaluateInteraction(InteractionEvaluationRequest.builder()
>     .metadata(InteractionEvaluationRequestMetadata.builder()
>         .model("gpt-4o")
>         .requesterId("user-1234")
>         .provider("openai")
>         .build())
>     .interaction(InteractionEvaluationRequestInteraction.of(CanonicalInteraction.builder()
>         .addMessages(CanonicalInteractionMessage.builder()
>             .role("user")
>             .addContent(ContentPart.text(TextPart.builder().text("What is the capital of France?").build()))
>             .build())
>         .build()))
>     .hlProjectId("customer-support-bot")
>     .build());
> System.out.println(result.getOutcome().getAction());
> ```

## Response types

Methods return typed objects named after the API specification's schemas, such as `ScanReportSummaryResponseV3` or `InteractionEvaluationResponse`. A field the API adds after your SDK version was released is still readable, and enumerated fields accept values the SDK does not know yet.

> [tab] Python
>
> Responses are Pydantic models. You read fields as attributes, and optional fields are `None` when the response leaves them out. Models are immutable: assigning to a field raises an error. Use `model.dict()` or `model.json()` to get a plain dictionary or a JSON string with the API's field names.
>
> ```python theme={null}
> from hiddenlayer import HiddenLayer
>
> client = HiddenLayer()
>
> summary = client.scans.results.retrieve_summary("YOUR_SCAN_ID")
> print(summary.status)
> print(summary.summary.highest_severity)
> print(summary.json())
>
> if summary.end_time is None:
>     print("The scan has not finished.")
> ```
>
> Every response type is importable from `hiddenlayer` for type hints, for example `from hiddenlayer import ScanReportSummaryResponseV3`. A response that does not match its model raises `hiddenlayer.core.ParsingError`. See [Error handling](https://docs.hiddenlayer.ai/docs/integrations/sdk/error_handling.md).

> [tab] TypeScript
>
> Responses are plain objects typed by interfaces in the `HiddenLayerApi` namespace. Fields keep the API's `snake_case` names, and optional fields are `undefined` when the response leaves them out.
>
> ```typescript theme={null}
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
>
> const summary = await client.scans.results.retrieveSummary({ scan_id: "YOUR_SCAN_ID" });
> console.log(summary.status);
> console.log(summary.summary.highest_severity);
> console.log(JSON.stringify(summary, null, 2));
>
> if (summary.end_time === undefined) {
>     console.log("The scan has not finished.");
> }
> ```

> [tab] Java
>
> Responses are immutable classes with `getX()` getters. An optional field returns an `Optional`, and `toString()` returns the object as JSON. A property the SDK does not model is in `getAdditionalProperties()`.
>
> ```java theme={null}
> import com.hiddenlayer.api.types.ScanReportSummaryResponseV3;
>
> ScanReportSummaryResponseV3 summary = client.scans().results().retrieveSummary("YOUR_SCAN_ID");
> System.out.println(summary.getStatus());
> System.out.println(summary.getSummary().getHighestSeverity().orElse(null));
> System.out.println(summary);
>
> if (!summary.getEndTime().isPresent()) {
>     System.out.println("The scan has not finished.");
> }
> ```

A few endpoints return untyped JSON instead of a typed object: a dictionary (Python), an object (TypeScript), or a `Map<String, Object>` (Java). The SARIF export returns the SARIF log this way, and the request-evaluations and response-evaluations endpoints return the provider payload this way.

## Projects and the `HL-Project-Id` header

In AI Runtime Security, a **project** groups your application's traffic and selects the policy used to evaluate it. The Runtime Security methods and Prompt Analyzer accept an optional project ID or alias, which the SDK sends as the `HL-Project-Id` HTTP header. If you omit it, your tenant's default project and its policy apply.

| Python | TypeScript | Java |
| - | - | - |
| `hl_project_id="customer-support-bot"` argument | `"HL-Project-Id": "customer-support-bot"` field of the request object | `.hlProjectId("customer-support-bot")` on the request builder |

The [Request types](#request-types) example sets the project in each language. The red team `create` method takes the project in the request body instead: `hl_project_id` in Python and TypeScript, and `hlProjectId` in Java. The Python red team session helper names the argument `hiddenlayer_project_id`. See [Runtime security](https://docs.hiddenlayer.ai/docs/integrations/sdk/runtime_security.md) and the [policy documentation](https://docs.hiddenlayer.ai/docs/products/runtime/agentic/policy.md).

## Beta APIs and beta warnings

Some endpoints are **Beta**: they are not generally available and can change without notice, including breaking changes. Beta endpoints are excluded from the SDKs' semantic versioning guarantees. See the [Beta API guidelines](https://dev.hiddenlayer.ai/docs/beta-api-faq).

In the current releases, the Beta endpoints include the AI Attack Simulation red team endpoints (`evaluations.red_team`, and the Python session helper that calls them) and the v2 asset inventory endpoints. The Runtime Security v2 evaluation endpoints are not Beta.

The first time a client calls a Beta endpoint, the SDK warns you. The warning names the endpoint by HTTP method and path:

```text theme={null}
[BETA] POST /evaluations/v1/red-team: This endpoint is not GA or Production ready and is subject to changes at any time. Breaking changes may occur.
```

> [tab] Python
>
> The SDK emits a `hiddenlayer.BetaWarning`, a subclass of `UserWarning`, through Python's `warnings` module, once per endpoint for each client. After you have reviewed the Beta terms, you can silence it:
>
> ```python theme={null}
> import warnings
>
> import hiddenlayer
>
> warnings.filterwarnings("ignore", category=hiddenlayer.BetaWarning)
> ```

> [tab] TypeScript
>
> The SDK logs the warning with `console.warn`, once per endpoint per process. The SDK has no option to turn it off.

> [tab] Java
>
> The SDK logs the warning at `WARNING` level through the `java.util.logging` logger `com.hiddenlayer.api.lib.BetaWarning`, once per endpoint per JVM. After you have reviewed the Beta terms, you can raise that logger's level. Keep a reference to the logger, because `java.util.logging` holds loggers weakly and a collected logger loses its level:
>
> ```java theme={null}
> import java.util.logging.Level;
> import java.util.logging.Logger;
>
> public final class BetaWarnings {
>     private static final Logger BETA_WARNINGS = Logger.getLogger("com.hiddenlayer.api.lib.BetaWarning");
>
>     public static void silence() {
>         BETA_WARNINGS.setLevel(Level.SEVERE);
>     }
> }
> ```

## Pagination

Methods that list many items return a **page** object. Iterating it walks every item across every page: the SDK requests the next page whenever it needs more items.

| | Python | TypeScript | Java |
| - | - | - | - |
| Return type | `SyncPager` (`AsyncPager` on the async client) | `Page` | `SyncPagingIterable` |
| Every item | `for item in page` (async: `async for item in await ...`) | `for await (const item of page)` | `for (T item : page)`, or `page.streamItems()` |
| Current page's items | `page.items` | `page.data` | `page.getItems()` |
| Another page? | `page.has_next` | `page.hasNextPage()` | `page.hasNext()` |
| Next page | `page.next_page()` | `await page.getNextPage()` (updates the page in place) | `page.nextPage()` |
| Response envelope | `page.response` | `page.response` | `page.getResponse()`, an `Optional` |

The following example prints every file result of a scan, 50 results per request.

```python Python theme={null}
from hiddenlayer import HiddenLayer

client = HiddenLayer()

for file_result in client.scans.results.list_files("YOUR_SCAN_ID", page_size=50):
    print(file_result.file_location, file_result.status)
```

```typescript TypeScript theme={null}
import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer();

const files = await client.scans.results.listFiles({ scan_id: "YOUR_SCAN_ID", page_size: 50 });
for await (const fileResult of files) {
    console.log(fileResult.file_location, fileResult.status);
}
```

```java Java theme={null}
import com.hiddenlayer.api.resources.scans.results.requests.ListFilesResultsRequest;
import com.hiddenlayer.api.types.ScanFileResultWithComplianceV3;

for (ScanFileResultWithComplianceV3 fileResult : client.scans().results()
        .listFiles("YOUR_SCAN_ID", ListFilesResultsRequest.builder().pageSize(50).build())) {
    System.out.println(fileResult.getFileLocation() + " " + fileResult.getStatus());
}
```

With Python's `AsyncHiddenLayer`, await the method first, then iterate: `async for file_result in await client.scans.results.list_files(...)`. The Java `AsyncHiddenLayerClient` completes its future with the first page; iterating past it blocks the calling thread for each further page.

> [!WARNING]
>
> Call the next-page method only while the has-next check is true. In Python, `page.next_page()` after the last page sends another request instead of returning `None`, and a list paged by cursor starts again from its first page.

See [API usage examples](https://docs.hiddenlayer.ai/docs/integrations/sdk/api_examples.md#iterate-over-file-results) for page-by-page loops.

## Raw responses

By default, methods return the parsed body only. To read the HTTP status or a response header, request the raw response:

| Python | TypeScript | Java |
| - | - | - |
| `client.<resource>.with_raw_response.<method>(...)` returns an object with `.data`, `.headers`, and `.status_code` | `await client.<resource>.<method>(...).withRawResponse()` returns `{ data, rawResponse }` | `client.<resource>().withRawResponse().<method>(...)` returns an object with `.body()` and `.headers()` |

```python Python theme={null}
from hiddenlayer import HiddenLayer

client = HiddenLayer()

raw = client.scans.results.with_raw_response.retrieve_summary("YOUR_SCAN_ID")
print(raw.status_code, raw.headers.get("content-type"))
summary = raw.data
print(summary.status)
```

```typescript TypeScript theme={null}
import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer();

const { data: summary, rawResponse } = await client.scans.results
    .retrieveSummary({ scan_id: "YOUR_SCAN_ID" })
    .withRawResponse();
console.log(rawResponse.status, rawResponse.headers.get("content-type"));
console.log(summary.status);
```

```java Java theme={null}
import com.hiddenlayer.api.core.BaseHiddenLayerClientHttpResponse;
import com.hiddenlayer.api.types.ScanReportSummaryResponseV3;

BaseHiddenLayerClientHttpResponse<ScanReportSummaryResponseV3> raw =
    client.scans().results().withRawResponse().retrieveSummary("YOUR_SCAN_ID");
raw.headers().forEach((name, values) -> System.out.println(name + ": " + values));
ScanReportSummaryResponseV3 summary = raw.body();
System.out.println(summary.getStatus());
```

The Java raw response has no status code, because a raw method returns only for a 2xx status and throws for any other. Its header names keep the case the server sent them in.

Paginated methods differ. In TypeScript, a paginated method such as `scans.jobs.list` has no `withRawResponse()`; the page it returns has `rawResponse`, the current page's status and headers. In Python, `with_raw_response` on a paginated method returns the same page object as the method, without headers or a status code. In Java, `withRawResponse()` works for paginated methods too.

Use raw responses to read the `hl-runtime-action` header that the Runtime Security request-evaluations and response-evaluations endpoints return. See [Runtime security](https://docs.hiddenlayer.ai/docs/integrations/sdk/runtime_security.md).

## Retries and timeouts

The client retries failed requests automatically so that short outages do not break your program.

| Setting | Default | How to change |
| - | - | - |
| Retries | 2 retries with exponential backoff, starting at 1 second and capped at 60 seconds, with jitter. A `Retry-After` or `X-RateLimit-Reset` response header sets the delay instead. | `max_retries` (Python), `maxRetries` (TypeScript and Java) on the client or for one request. `0` disables retries. |
| Retried responses | HTTP 408, 429, and 5xx in every SDK. Python also retries 409. | Java only: `retryOnStatusCodes(...)` on the builder. |
| Retried failures without a response | Python retries a failed connection. TypeScript and Java do not. No SDK retries a request that timed out. | Not configurable |
| Timeout | 60 seconds per request | `timeout` (Python, seconds), `timeoutInSeconds` (TypeScript), `timeout(int)` in seconds (Java), on the client or for one request |

```python Python theme={null}
from hiddenlayer import HiddenLayer

client = HiddenLayer(max_retries=4, timeout=30.0)

page = client.scans.jobs.list(
    limit=10,
    request_options={"timeout": 120.0, "max_retries": 0},
)
```

```typescript TypeScript theme={null}
import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer({ maxRetries: 4, timeoutInSeconds: 30 });

const page = await client.scans.jobs.list({ limit: 10 }, { timeoutInSeconds: 120, maxRetries: 0 });
console.log(page.data.length);
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.core.RequestOptions;
import com.hiddenlayer.api.resources.scans.jobs.requests.ListJobsRequest;

HiddenLayerClient client = new HiddenLayerClientBuilder().maxRetries(4).timeout(30).build();

client.scans().jobs().list(
    ListJobsRequest.builder().limit(10).build(),
    RequestOptions.builder().timeout(120).maxRetries(0).build());
```

> [!NOTE]
>
> Retries and timeouts apply to each HTTP request. They do not limit how long the model scanner or community scanner wait for a scan to finish. Those helpers poll until the scan reaches a final status, with no overall time limit. See [Model scanning](https://docs.hiddenlayer.ai/docs/integrations/sdk/model_scanning.md).

## Logging

Each SDK can log the requests it sends and the responses it receives. Logging is off by default. To turn it on, pass a logging configuration with a level (`debug`, `info`, `warn`, or `error`) and turn off `silent`:

```python Python theme={null}
from hiddenlayer import HiddenLayer

client = HiddenLayer(logging={"level": "debug", "silent": False})
```

```typescript TypeScript theme={null}
import { HiddenLayer, logging } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer({
    logging: { level: logging.LogLevel.Debug, silent: false },
});
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.core.LogConfig;
import com.hiddenlayer.api.core.LogLevel;

HiddenLayerClient client = new HiddenLayerClientBuilder()
    .logging(LogConfig.builder().level(LogLevel.DEBUG).silent(false).build())
    .build();
```

At the `debug` level, the SDK logs each request and response with its method, URL, status, and headers. The default loggers write to the console:

* **Python** uses the standard `logging` module. Its default console format prints only the message, such as `DEBUG - Making HTTP request`; the method, URL, and headers are passed to the log record as extra fields.
* **TypeScript** uses `console` and prints each message with its fields.
* **Java** uses `java.util.logging` and prints request lines at the `FINE` level, such as `FINE - HTTP Request: GET https://api.us.hiddenlayer.ai/scan/v3/results/...`.

Each SDK also accepts your own logger object with `debug`, `info`, `warn`, and `error` methods, passed as `logger` in the configuration, which receives the same fields. The SDKs no longer read the `HIDDENLAYER_LOG` environment variable.

> [!WARNING]
>
> Debug logging records each request's method, URL, and headers. The SDKs replace the `Authorization` header and other credential headers with `[REDACTED]`, but URLs and other headers can still identify your users or projects. Do not enable debug logging in production or anywhere logs are shared.

## Next steps

* [Model scanning](https://docs.hiddenlayer.ai/docs/integrations/sdk/model_scanning.md)
* [Runtime security](https://docs.hiddenlayer.ai/docs/integrations/sdk/runtime_security.md)
* [Attack simulation](https://docs.hiddenlayer.ai/docs/integrations/sdk/attack_simulation.md)
* [Error handling](https://docs.hiddenlayer.ai/docs/integrations/sdk/error_handling.md)
