---
title: "Build a TypeScript Client"
description: "Generate Y2 API types and add a small server-side fetch transport"
canonical: https://y2.dev/docs/sdks/typescript/
---

# Build a TypeScript Client

Generate Y2 API types and add a small server-side fetch transport

Use generated OpenAPI types with native `fetch`. This guide uses Bun to run TypeScript examples. The transport also works in runtimes that support `fetch` and `AbortSignal.timeout`.

Before you begin, [create a key](https://y2.dev/docs/api/create-key) with `news:read`. Set `Y2_API_KEY` in your environment.

Keep the API key server-side

Run API calls on your server or local runtime. Keep `Y2_API_KEY` out of browser bundles.

## Generate declarations

Install the same generator used by the Y2 platform repository:

**Bun**

```
bun add --dev openapi-typescript@^7.13.0
bunx openapi-typescript https://y2.dev/api/openapi.yaml \
  --immutable \
  --alphabetize \
  --output src/y2-api.d.ts
```

**npm**

```
npm install --save-dev openapi-typescript@^7.13.0
npx openapi-typescript https://y2.dev/api/openapi.yaml \
  --immutable \
  --alphabetize \
  --output src/y2-api.d.ts
```

Commit the generated declarations or pin the input specification. Review changes when you regenerate them.

Add a repeatable script:

package.json

```
{
  "scripts": {
    "generate:y2-types": "openapi-typescript https://y2.dev/api/openapi.yaml --immutable --alphabetize --output src/y2-api.d.ts"
  }
}
```

## Make a first request

Save this complete example as `src/first-request.ts`:

src/first-request.ts

```
import type { paths } from "./y2-api";

type NewsPage =
  paths["/news"]["get"]["responses"][200]["content"]["application/json"];

const apiKey = process.env.Y2_API_KEY;
if (!apiKey) throw new Error("Set Y2_API_KEY");

const response = await fetch("https://api.y2.dev/api/v1/news?limit=1", {
  headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
  signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error(`Y2 returned HTTP ${response.status}`);

const page: NewsPage = await response.json();
console.log(response.status);
for (const item of page.data) {
  console.log(item.title, item.links.canonical);
}
```

Run `bun src/first-request.ts` with `Y2_API_KEY` set. Expect `200`, followed by up to one title and source URL. An empty collection prints only `200`. For other statuses, see [API errors](https://y2.dev/docs/api/responses#errors).

## Create a reusable JSON transport

Set the credential in the runtime environment:

```
export Y2_API_KEY="y2_..."
```

Then create a transport that preserves Y2 Problem Details and rate-limit context:

src/y2-client.ts

```
import type { components } from "./y2-api";

const API_ORIGIN = "https://api.y2.dev";
const API_V1 = `${API_ORIGIN}/api/v1`;

export type Y2Problem = components["schemas"]["ErrorResponse"];

export class Y2ApiError extends Error {
  constructor(
    readonly status: number,
    readonly problem: Y2Problem | null,
    readonly retryAfter: string | null,
    readonly requestId: string | null,
  ) {
    super(problem?.detail ?? `Y2 request failed with HTTP ${status}`);
  }
}

function isProblem(value: unknown): value is Y2Problem {
  return (
    typeof value === "object" &&
    value !== null &&
    "status" in value &&
    "code" in value &&
    "detail" in value
  );
}

function resolveUrl(pathOrUrl: string): string {
  if (pathOrUrl.startsWith("https://")) return pathOrUrl;
  if (pathOrUrl.startsWith("/api/")) return `${API_ORIGIN}${pathOrUrl}`;
  return `${API_V1}${pathOrUrl}`;
}

export async function y2Json<T>(
  pathOrUrl: string,
  init: RequestInit = {},
): Promise<T> {
  const apiKey = process.env.Y2_API_KEY;
  if (!apiKey) throw new Error("Y2_API_KEY is required");

  const headers = new Headers(init.headers);
  headers.set("Authorization", `Bearer ${apiKey}`);
  if (!headers.has("Accept")) headers.set("Accept", "application/json");
  if (init.body && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const response = await fetch(resolveUrl(pathOrUrl), {
    ...init,
    headers,
    signal: init.signal ?? AbortSignal.timeout(30_000),
  });

  const text = await response.text();
  let payload: unknown = null;
  if (text) {
    try {
      payload = JSON.parse(text);
    } catch {
      payload = text;
    }
  }

  if (!response.ok) {
    throw new Y2ApiError(
      response.status,
      isProblem(payload) ? payload : null,
      response.headers.get("Retry-After"),
      response.headers.get("X-Request-Id"),
    );
  }

  return payload as T;
}
```

`y2Json` handles JSON only. Use separate readers for text, streams, and audio redirects.

## Type a read operation

Extract parameter and response types from the path entry:

src/news.ts

```
import type { paths } from "./y2-api";
import { y2Json } from "./y2-client";

type ListNewsQuery = Pick<
  NonNullable<paths["/news"]["get"]["parameters"]["query"]>,
  "topics" | "limit" | "cursor"
>;
type ListNewsResponse =
  paths["/news"]["get"]["responses"][200]["content"]["application/json"];

export async function listNews(query: ListNewsQuery): Promise<ListNewsResponse> {
  const params = new URLSearchParams();
  if (query.topics) params.set("topics", query.topics);
  if (query.limit !== undefined) params.set("limit", String(query.limit));
  if (query.cursor) params.set("cursor", query.cursor);

  return y2Json<ListNewsResponse>(`/news?${params}`);
}

const page = await listNews({ topics: "markets,macro", limit: 10 });
for (const item of page.data) {
  console.log(item.title, item.links.canonical);
}
```

Use `GET /news/feeds` to discover topics. Items contain `title`, `summary`, and a nested `sentiment` object. Read `sentiment.label` and `sentiment.value`.

## Type a mutation

Profile creation returns a `PublicProfile` in `data`. Read its ID from `data.id`. Use `GET /profiles` to find the associated `sub_...` subscription ID. This request needs `profiles:write`.

src/profiles.ts

```
import type { paths } from "./y2-api";
import { y2Json } from "./y2-client";

type CreateProfileBody =
  paths["/profiles"]["post"]["requestBody"]["content"]["application/json"];
type CreateProfileResponse =
  paths["/profiles"]["post"]["responses"][201]["content"]["application/json"];

export async function createProfile(
  body: CreateProfileBody,
  idempotencyKey: string,
): Promise<CreateProfileResponse> {
  return y2Json<CreateProfileResponse>("/profiles", {
    method: "POST",
    headers: { "Idempotency-Key": idempotencyKey },
    body: JSON.stringify(body),
  });
}

const created = await createProfile(
  {
    name: "Critical Supplier Risk",
    topic: "Monitor disruption affecting strategic semiconductor suppliers.",
    frequency: "daily",
    scheduleTimeOfDay: "08:00",
    isCommunity: false,
  },
  "supplier-risk-2026-07-21",
);

console.log(created.data.id); // prf_...
```

Use `PATCH /profiles/{profileId}` for partial changes. Use `PUT` for full replacement. Extend this helper to retain `ETag` headers if you need `If-Match` concurrency protection.

## Paginate reports

Use a key with `reports:read`. Replace the example profile ID with an accessible profile ID. Follow each response link unchanged:

src/reports.ts

```
import type { paths } from "./y2-api";
import { y2Json } from "./y2-client";

type ReportsPage =
  paths["/reports"]["get"]["responses"][200]["content"]["application/json"];

export async function* reportsForProfile(profileId: string) {
  let next: string | null = `/reports?profileId=${encodeURIComponent(profileId)}&limit=20`;

  while (next) {
    const page: ReportsPage = await y2Json<ReportsPage>(next);
    yield* page.data;
    next = page.links.next;
  }
}

for await (const report of reportsForProfile("prf_0123456789abcdef01234567")) {
  console.log(report.id, report.summary);
}
```

The list and default detail response are compact. Request `include=content,sources` or `Accept: text/markdown` only when the consumer needs those representations.

## Call Intel v2 correctly

Intel paths include `/api/v2` and use `https://api.y2.dev` as the server. Use a key with an accepted Intel scope:

```
import type { paths } from "./y2-api";
import { y2Json } from "./y2-client";

type IncidentList =
  paths["/api/v2/incidents"]["get"]["responses"][200]["content"]["application/json"];

const incidents = await y2Json<IncidentList>(
  "https://api.y2.dev/api/v2/incidents?limit=20",
);
```

Do not compose Intel URLs by adding `/api/v1` to the path.

## Handle special representations

| Format   | Handling                                                                                         |
| -------- | ------------------------------------------------------------------------------------------------ |
| NDJSON   | Read `response.body` as a stream. Parse complete lines. Keep `X-Y2-Next-Cursor`                  |
| Markdown | Send `Accept: text/markdown` on a supported report request. Read the body with `response.text()` |
| SSE      | Use an SSE parser for Agent Y2. Keep `X-Thread-Id`                                               |

Do not pass these responses through `y2Json`.

## Production checklist

- Pin or review generated declaration changes.
- Give the key only the required scopes.
- Use idempotency keys on supported create operations.
- Follow `Retry-After` on `429` and retry only safe or idempotent requests.
- Log `X-Request-Id` without logging credentials or full payment payloads.
- Treat `404` as non-disclosing for tenant-owned resources.
- Test special media types separately from JSON.

[OpenAPI contract](https://y2.dev/docs/api/openapi)

[Authentication](https://y2.dev/docs/api/authentication)

[Profiles API](https://y2.dev/docs/api/profiles)

[Reports API](https://y2.dev/docs/api/reports)
