> ## Documentation Index
> Fetch the complete documentation index at: https://komga-sdk.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Quick Reference

> Common komga-sdk client, operation, and result patterns

Use these snippets as a reference for the generated Komga API client. All endpoint parameters are flat; the configured client is passed in the optional second argument.

## Client setup

```typescript Basic Auth theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  auth: {
    type: 'basic',
    username: process.env.KOMGA_USER!,
    password: process.env.KOMGA_PASSWORD!,
  },
});
```

```typescript API key theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  auth: { type: 'apiKey', key: process.env.KOMGA_API_KEY! },
});
```

```typescript Browser session or custom headers theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  credentials: 'include',
  headers: { 'X-Request-Source': 'reader-web' },
});
```

`baseUrl` is required. `auth` is optional for an unauthenticated server or an application-owned session. Keep Basic credentials and API keys on a server-side boundary when a browser bundle is public.

## Flat operation calls

```typescript theme={null}
import { getBookById, getBooks, getLibraries } from 'komga-sdk';

const bookResult = await getBookById({ bookId: 'book-123' }, { client });
const librariesResult = await getLibraries({ client });

const booksResult = await getBooks(
  {
    page: 0,
    size: 20,
    sort: ['metadata.title,asc'],
    bookSearch: { fullTextSearch: 'manga' },
  },
  { client },
);
```

The generated signatures used above are:

* `getBookById({ bookId: string }, options?)`
* `getLibraries(options?)`
* `getBooks({ unpaged?, page?, size?, sort?, bookSearch }, options?)`

Operations with no endpoint parameters accept only their options object. Do not use the removed grouped `{ path, query, body }` call shape.

## Nonthrowing results

By default, each call resolves to fields containing `data`, `error`, `request`, and `response`:

```typescript theme={null}
const result = await getBookById({ bookId: 'book-123' }, { client });

if (result.error === undefined) {
  console.log(result.data.metadata.title);
} else {
  console.error(result.response?.status, result.error);
}
```

The success and error branches are discriminated by `error`. `request` and `response` are optional because request construction and network failures may happen before Fetch creates either object. Use `response?.status` for HTTP handling and the generated `error` body for operation-specific details.

## Throwing at an explicit boundary

`unwrap` returns data or throws `KomgaApiError`:

```typescript theme={null}
import { KomgaApiError, getBookById, unwrap } from 'komga-sdk';

try {
  const book = unwrap(await getBookById({ bookId: 'book-123' }, { client }));
  console.log(book.metadata.title);
} catch (error) {
  if (error instanceof KomgaApiError && error.status === 404) {
    console.log('Book not found');
  } else {
    throw error;
  }
}
```

Use the nonthrowing form for local branching and `unwrap` where an exception is the intended application boundary. A successful `204 No Content` operation unwraps to `undefined`.

## Pagination and search

`getBooks` sends `page`, `size`, `sort`, and `unpaged` as query parameters while `bookSearch` is the generated request body:

```typescript theme={null}
import { getBooks } from 'komga-sdk';

const result = await getBooks(
  {
    bookSearch: { fullTextSearch: 'manga' },
    page: 0,
    size: 100,
    sort: ['metadata.releaseDate,desc', 'metadata.title,asc'],
  },
  { client },
);

if (result.error === undefined) {
  console.log(`${result.data.content?.length ?? 0} of ${result.data.totalElements ?? 0}`);
}
```

Use `unpaged: true` only for bounded datasets:

```typescript theme={null}
const result = await getBooks(
  { bookSearch: {}, unpaged: true, sort: ['metadata.title,asc'] },
  { client },
);
```

Collections and read lists use generated query names rather than `BookSearch`:

```typescript theme={null}
import { getCollections, getReadLists } from 'komga-sdk';

const collections = await getCollections(
  { search: 'favorites', library_id: ['library-123'], page: 0, size: 20 },
  { client },
);
const readLists = await getReadLists({ page: 0, size: 20 }, { client });
```

## Common reads and mutations

```typescript theme={null}
import {
  getBookPages,
  getLibraryById,
  getSeriesById,
  libraryScan,
  updateBookMetadata,
} from 'komga-sdk';

const series = await getSeriesById({ seriesId: 'series-123' }, { client });
const library = await getLibraryById({ libraryId: 'library-123' }, { client });
const pages = await getBookPages({ bookId: 'book-123' }, { client });

const update = await updateBookMetadata(
  {
    bookId: 'book-123',
    bookMetadataUpdateDto: { title: 'New title' },
  },
  { client },
);

// Scans require the server role documented for this operation.
const scan = await libraryScan({ libraryId: 'library-123', deep: true }, { client });
```

Mutation responses commonly have `data: undefined` because Komga returns `204 No Content`; check `error` and `response` even when there is no data to print. Operation documentation and generated types are the source of truth for required roles and fields.

## Binary, text, and void responses

Generated Fetch options can select the parser for an endpoint whose response is not JSON:

```typescript theme={null}
import { getBookPageByNumber, getBookPageRawByNumber } from 'komga-sdk';

const image = await getBookPageByNumber(
  { bookId: 'book-123', pageNumber: 1 },
  { client, parseAs: 'blob' },
);

const raw = await getBookPageRawByNumber(
  { bookId: 'book-123', pageNumber: 1 },
  { client, parseAs: 'text' },
);

if (image.error === undefined) {
  const objectUrl = URL.createObjectURL(image.data);
  console.log(objectUrl);
}
```

Use `arrayBuffer`, `blob`, or `text` only when it matches the endpoint's generated response. Always revoke browser object URLs after the image is no longer needed.

## TypeScript types

Generated DTO types are available for annotations. They guide compile-time use and do not validate runtime responses:

```typescript theme={null}
import type { BookDto, BookSearch, PageBookDto } from 'komga-sdk';

const search: BookSearch = { fullTextSearch: 'manga' };

function displayBook(book: BookDto): string {
  return `${book.metadata.title} (${book.number})`;
}

function firstBook(page: PageBookDto): BookDto | undefined {
  return page.content?.[0];
}
```

Use `Awaited<ReturnType<typeof getBookById>>` when a wrapper should follow the generated result contract instead of reproducing it manually.

## Native Fetch customization

Configure headers, credentials, parser options, or a Fetch implementation when creating the client or per operation:

```typescript theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: 'https://komga.example.com',
  headers: { 'X-Request-Source': 'batch-job' },
  fetch: async (input, init) => {
    const started = Date.now();
    try {
      return await fetch(input, init);
    } finally {
      console.log(`Komga request took ${Date.now() - started}ms`);
    }
  },
});
```

The SDK has no built-in retries, caching, timeout policy, or logging. Implement those policies around Fetch or operation calls, and redact auth headers and cookies from logs.

## Environment variables

```typescript theme={null}
import { createKomgaClient } from 'komga-sdk';

const client = createKomgaClient({
  baseUrl: process.env.KOMGA_URL ?? 'http://localhost:25600',
  auth: {
    type: 'apiKey',
    key: process.env.KOMGA_API_KEY!,
  },
});
```

## Next steps

> **[Direct API functions](/direct-api)**
>
> See request mapping, binary results, and mutation examples.

> **[Pagination](/pagination)**
>
> Iterate pages, sort results, and search safely.

> **[Result handling](/errors)**
>
> Handle API, network, and parsing failures.

> **[Request customization](/interceptors)**
>
> Add low-level Fetch lifecycle hooks.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.