# @askrjs/fetch

> Published API exports for @askrjs/fetch.

Source: [https://askrjs.com/docs/reference/api/fetch/root](https://askrjs.com/docs/reference/api/fetch/root)

Status: stable. Packages: @askrjs/fetch.

**Published packages are authoritative.** Examples may lag behind a published contract. When guidance differs, verify the exports and TypeScript declarations in your installed package, then file an issue.

## Exports

This entrypoint publishes 47 exports from the declarations shipped by @askrjs/fetch.

### `AdHocCall`

```ts
AdHocCall: any
```

A one-off, untyped request description accepted by {@link createFetch}'s returned function.

- `url`: url: string;

- `method`: method?: string;

- `headers`: headers?: HeadersInit;

- `query`: query?: Record<string, unknown>;

- `querySpec`: querySpec?: ParameterMap;

- `body`: body?: unknown;

- `bodyCodec`: bodyCodec?: Codec;

- `bodyMediaType`: Explicit media type used to encode a request body with a multi-variant `content()` codec.

- `response`: response?: Codec;

- `responses`: responses?: Readonly<Record<number, Codec>>;

- `errors`: errors?: Partial<Record<number | "default", Codec>>;

- `signal`: signal?: AbortSignal;

- `timeout`: timeout?: number;

- `endpoint`: endpoint?: EndpointDescriptor;

- `operationId`: operationId?: string;

### `AnyEndpointDescriptor`

```ts
AnyEndpointDescriptor: EndpointDescriptor<any, any, any, any, any, any>
```

An {@link EndpointDescriptor} with its type parameters erased, for use in generic contexts.

### `ApiClient`

```ts
ApiClient: Readonly<{ [K in keyof A["endpoints"]]: ClientMethod<A["endpoints"][K]>; }>
```

A fully-typed client for an {@link ApiDefinition}, with one method per endpoint.

### `ApiDefinition`

```ts
ApiDefinition: any
```

A named collection of endpoints plus optional API metadata, as produced by {@link defineApi }.

- `endpoints`: readonly endpoints: E;

- `metadata`: readonly metadata?: ApiMetadata;

### `ApiMetadata`

```ts
ApiMetadata: any
```

API-level (rather than per-endpoint) metadata, such as servers and security schemes.

- `servers`: readonly servers?: readonly (string | {
    readonly url: string;
  })[];

- `tags`: readonly tags?: readonly unknown[];

- `securitySchemes`: readonly securitySchemes?: Readonly<Record<string, unknown>>;

### `arrayBuffer`

```ts
arrayBuffer: () => Codec<ArrayBuffer>
```

Creates a codec that decodes any response body as an `ArrayBuffer`.

### `blob`

```ts
blob: () => Codec<Blob>
```

Creates a codec that decodes any response body as a `Blob`.

### `ClientOptions`

```ts
ClientOptions: any
```

Options controlling how a {@link createClient } or {@link createFetch } client makes requests.

- `baseUrl`: baseUrl?: string;

- `fetch`: Custom transport, defaulting to the global `fetch`.

- `headers`: headers?: HeadersInit;

- `credentials`: credentials?: RequestCredentials;

- `timeout`: Request timeout in milliseconds.

- `middleware`: Middleware chain applied to every request, in order.

### `ClientResult`

```ts
ClientResult: Successes<D> | Errors<D> | FailureResult
```

The possible results of calling a typed client method for endpoint descriptor `D`.

### `Codec`

```ts
Codec: any
```

Describes how a request or response body is serialized/deserialized:
which wire format (`kind`), which media types it matches, and optionally
a {@link Validator} to parse/validate the decoded value.

- `kind`: readonly kind: "json" | "text" | "urlEncoded" | "multipart" | "blob" | "arrayBuffer" | "stream" | "empty" | "content";

- `mediaTypes`: readonly mediaTypes: readonly string[];

- `validator`: readonly validator?: Validator<T>;

- `variants`: For `kind: "content"`, the per-media-type codec variants.

### `content`

```ts
content: <T extends Record<string, Codec>>(variants: T) => Codec<{ [K in keyof T]: T[K] extends Codec<infer V> ? V : never; }[keyof T]>
```

Creates a content-negotiated codec that selects among `variants` by the response's
media type, decoding with whichever variant matches.

### `createClient`

```ts
createClient: <A extends ApiDefinition>(api: A, options?: ClientOptions) => ApiClient<A>
```

Builds a typed {@link ApiClient} from an {@link ApiDefinition}. Each endpoint becomes
a method that fills in the path, query, header, and body parameters, executes the
request via {@link createFetch}, and returns a {@link ClientResult}.

### `createFetch`

```ts
createFetch: (options?: ClientOptions) => (call: AdHocCall) => Promise<FetchResult>
```

Creates a low-level fetch function that builds a `Request` from an {@link AdHocCall},
runs it through the configured middleware chain, and decodes the response with the
matching codec. Used internally by {@link createClient}, and usable directly for
requests without a full {@link EndpointDescriptor}.

### `defineApi`

```ts
defineApi: <E extends Record<string, AnyEndpointDescriptor | EndpointBuilder>>(endpoints: E, metadata?: ApiMetadata) => ApiDefinition<Defined<E>>
```

Finalizes a map of {@link EndpointBuilder}s and/or raw {@link EndpointDescriptor}s into
a frozen {@link ApiDefinition}, stamping each endpoint's `operationId` from its key and
deep-freezing its parameters, security, responses, and errors.

```tsx
const api = defineApi({
  getUser: get("/users/{id}").returns(json()),
});
```

### `del`

```ts
del: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>
```

Starts building a DELETE endpoint at the given path.

### `empty`

```ts
empty: () => Codec<undefined>
```

Creates a codec for bodies expected to be empty (e.g. 204 No Content), decoded as `undefined`.

### `EndpointBuilder`

```ts
EndpointBuilder: any
```

Fluent, immutable builder for describing a single endpoint's params, query,
headers, body, responses, errors, and security requirements. Each method
returns a new builder reflecting the added configuration; the accumulated
state is finalized into an {@link EndpointDescriptor} by {@link defineApi}.

- `params`: Declares path parameter types and optional runtime validators. Generic types are erased;
runtime validation occurs only for entries whose specification includes a validator.

- `query`: query<T extends Record<string, unknown>>(spec?: ParameterMap): EndpointBuilder<P, T, H, B, R, E>;

- `headers`: headers<T extends Record<string, unknown>>(spec?: ParameterMap): EndpointBuilder<P, Q, T, B, R, E>;

- `body`: body<C extends Codec>(codec: C): EndpointBuilder<P, Q, H, C extends Codec<infer T> ? T : never, R, E>;

- `returns`: returns<C extends Codec>(codec: C): EndpointBuilder<P, Q, H, B, R & Record<200, C>, E>;

- `returns`: returns<S extends number, C extends Codec>(status: S, codec: C): EndpointBuilder<P, Q, H, B, R & Record<S, C>, E>;

- `errors`: errors<T extends Errors>(spec: T): EndpointBuilder<P, Q, H, B, R, E & T>;

- `security`: security(requirements: readonly Readonly<Record<string, readonly string[]>>[]): EndpointBuilder<P, Q, H, B, R, E>;

### `EndpointDescriptor`

```ts
EndpointDescriptor: any
```

Describes a single API endpoint: its method, path, parameters, body, and possible responses.

- `method`: readonly method: HttpMethod;

- `path`: readonly path: string;

- `params`: readonly params?: ParameterMap;

- `query`: readonly query?: ParameterMap;

- `headers`: readonly headers?: ParameterMap;

- `body`: readonly body?: Codec;

- `responses`: readonly responses: Readonly<R>;

- `errors`: readonly errors: Readonly<E>;

- `security`: readonly security?: readonly Readonly<Record<string, readonly string[]>>[];

- `operationId`: readonly operationId?: string;

- `__input`: readonly __input?: {
    params: P;
    query: Q;
    headers: H;
    body: B;
  };

### `FailureKind`

```ts
FailureKind: "request" | "network" | "timeout" | "abort" | "decode" | "middleware"
```

Categorizes why a fetch could not produce an {@link HttpResult} or {@link SuccessResult}.

### `FailureResult`

```ts
FailureResult: {
  ok: false;
  kind: FailureKind;
  status: number;
  error: unknown;
  headers: Headers;
  url: string;
  response?: Response;
}
```

A fetch outcome that failed before or independently of receiving a decodable HTTP response.

### `FetchError`

```ts
FetchError: typeof FetchError
```

An `Error` thrown by {@link unwrap} that wraps a failed (non-`ok`) {@link FetchResult}.

- `result`: readonly result: Exclude<FetchResult, {
    ok: true;
  }>;

### `FetchResult`

```ts
FetchResult: SuccessResult<T> | HttpResult<T> | FailureResult
```

The outcome of a fetch call: success, an HTTP-level error, or another kind of failure.

### `get`

```ts
get: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>
```

Starts building a GET endpoint at the given path.

### `head`

```ts
head: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>
```

Starts building a HEAD endpoint at the given path.

### `HttpMethod`

```ts
HttpMethod: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"
```

The set of HTTP methods supported by endpoint descriptors.

### `HttpResult`

```ts
HttpResult: {
  ok: false;
  kind: "http";
  status: S;
  error: T;
  mediaType: string | null;
  headers: Headers;
  url: string;
  response: Response;
}
```

A non-2xx fetch outcome where the server responded with a decodable error body.

### `InferCodec`

```ts
InferCodec: C extends Codec<infer T> ? T : never
```

Infers the decoded value type `T` from a {@link Codec}.

### `InferValidator`

```ts
InferValidator: V extends Validator<infer T> ? T : never
```

Infers the parsed output type `T` from a {@link Validator}.

### `json`

```ts
json: { <T = unknown>(): Codec<T>; <V extends Validator>(schema: V): Codec<V extends Validator<infer T> ? T : never>; }
```

Creates a JSON codec, matching `application/json` and `+json` suffixed media types.
Creates a JSON codec that validates/parses the decoded value with the given schema.

### `Middleware`

```ts
Middleware: (context: RequestContext, next: Next) => Promise<FetchResult>
```

A function that can inspect/replace the request context and/or the result of calling `next`.

### `multipart`

```ts
multipart: () => Codec<FormData>
```

Creates a codec for `multipart/form-data` bodies, decoded as `FormData`.

### `Next`

```ts
Next: (context?: RequestContext) => Promise<FetchResult>
```

Invokes the next middleware in the chain, optionally passing a replacement context.

### `options`

```ts
options: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>
```

Starts building an OPTIONS endpoint at the given path.

### `ParameterMap`

```ts
ParameterMap: Readonly<Record<string, Validator<unknown> | ParameterSpec | undefined>>
```

Maps parameter names to either a bare {@link Validator} or a full
{@link ParameterSpec} describing serialization and validation.

### `ParameterSpec`

```ts
ParameterSpec: any
```

Serialization and validation settings for a single path, query, or header parameter.

- `validator`: readonly validator?: Validator<T>;

- `style`: readonly style?: ParameterStyle;

- `explode`: readonly explode?: boolean;

### `ParameterStyle`

```ts
ParameterStyle: "simple" | "label" | "matrix" | "form" | "spaceDelimited" | "pipeDelimited" | "deepObject"
```

OpenAPI-style serialization styles for path, query, and header parameters.

### `patch`

```ts
patch: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>
```

Starts building a PATCH endpoint at the given path.

### `pathNames`

```ts
pathNames: (path: string) => string[]
```

Extracts the ordered list of `{param}` placeholder names from an endpoint path.

### `post`

```ts
post: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>
```

Starts building a POST endpoint at the given path.

### `put`

```ts
put: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>
```

Starts building a PUT endpoint at the given path.

### `RequestContext`

```ts
RequestContext: any
```

The mutable-by-replacement state threaded through the middleware chain for a single request.

- `request`: readonly request: Request;

- `endpoint`: readonly endpoint?: AnyEndpointDescriptor;

- `operationId`: readonly operationId?: string;

- `security`: readonly security?: AnyEndpointDescriptor["security"];

- `attempt`: 1 on the first attempt, incremented by middleware (e.g. {@link retry }) on subsequent attempts.

- `replayableBody`: Whether a body was encoded from a replayable value; streaming bodies set this to `false`.

- `deadline`: Absolute timestamp (ms since epoch) by which the request must complete, if a timeout is set.

### `stream`

```ts
stream: () => Codec<ReadableStream<Uint8Array>>
```

Creates a codec that exposes the raw response body as a `ReadableStream`, without buffering it.

### `SuccessResult`

```ts
SuccessResult: {
  ok: true;
  kind: "success";
  status: S;
  data: T;
  mediaType: string | null;
  headers: Headers;
  url: string;
  response: Response;
}
```

A successful (2xx) fetch outcome, carrying the decoded response data.

### `text`

```ts
text: () => Codec<string>
```

Creates a codec for plain text bodies (`text/*`), decoded as a string.

### `unwrap`

```ts
unwrap: <T>(result: FetchResult<T>) => T
```

Returns the data of a successful {@link FetchResult}, or throws a {@link FetchError}
wrapping the result if it was not `ok`.

### `urlEncoded`

```ts
urlEncoded: () => Codec<URLSearchParams>
```

Creates a codec for `application/x-www-form-urlencoded` bodies, decoded as `URLSearchParams`.

### `Validator`

```ts
Validator: any
```

A minimal schema-validation contract, compatible with libraries such as Zod
that expose a `safeParse` method (e.g. via a thin adapter).

- `safeParse`: safeParse(value: unknown): {
    success: true;
    data: T;
  } | {
    success: false;
    error: unknown;
  };

## Documentation navigation

[Previous](https://askrjs.com/docs/reference/api/charts/styles/index.md) | [Next](https://askrjs.com/docs/reference/api/fetch/middleware/index.md)
