Skip to main content
Version: v10.5.0

SDK

Read the API Reference »

An SDK describes a whole API as one TypeScript type and gives you its requests by dot notation, such as sdk.users.$userId.$get. createSdk(client) builds each request on access with a proxy, so nothing is created up front. Use it for APIs with many endpoints, or generate the schema from OpenAPI with the CLI.

Purpose
  1. One schema for the whole API, with response, payload, query params and endpoint per leaf.
  2. Typed dot notation: paths are keys, $param keys are URL params, $get and friends are methods.
  3. Central defaults per endpoint with $configure, checked against the schema.
api/sdk.ts
import { createClient, createSdk, type RequestModel } from "@hyper-fetch/core";

type User = { id: string; name: string };

type ApiSchema = {
users: {
$get: RequestModel<{
response: User[];
queryParams?: { page?: number } | null;
endpoint: "/users";
}>;
$userId: {
$get: RequestModel<{ response: User; endpoint: "/users/:userId" }>;
$delete: RequestModel<{ response: User; endpoint: "/users/:userId" }>;
};
};
};

export const client = createClient({ url: "https://api.example.com" });
export const sdk = createSdk<typeof client, ApiSchema>(client);

// GET /users/123
const { data } = await sdk.users.$userId.$get.send({
params: { userId: "123" },
});

Every leaf is a regular request: send(), setParams, useFetch and useSubmit all work with it.


Write the schema​

  • Path keys become URL segments. camelCase keys turn into kebab-case: userProfiles is /user-profiles.
  • $name keys below a path are URL params: $userId is /:userId.
  • $get, $post, $put, $patch, $delete are the methods, upper-cased by methodTransform.
  • Leaves are RequestModel<{ response, payload, queryParams, error, endpoint }>. You do not pass the client: createSdk adds it, with its adapter and global error type.

Nested keys must not be named like a request property (send, cache, method, params and so on), because the request property wins. The types mark such a key with SdkReservedKeyError, so rename it in the schema.


RequestModel or RequestInstance​

Both describe requests at the type level, for opposite jobs.

RequestModel<{...}>RequestInstance<{...}>
DescribesThis one endpointAny request matching a partial shape
Use forSDK schema leaves, single-endpoint typesGeneric constraints of helpers and components
Omitted fields default toStrict types such as unknown, Error and falseany, so any concrete request satisfies it
api/types.ts
// This endpoint: no payload, no query params
type GetUsers = RequestModel<{ response: User[]; endpoint: "/users" }>;

// Any request that returns User[], whatever its payload or query params
function countCachedUsers<T extends RequestInstance<{ response: User[] }>>(
request: T,
) {
return request.read()?.data?.length ?? 0;
}

See extend Request for the helper pattern.


Configure endpoints with $configure​

$configure sets request defaults per endpoint and returns a new SDK. Values are an object of options, or a function that receives the request and returns a changed one, with access to every setter.

api/sdk.ts
export const api = sdk.$configure({
"*": { retry: 2 }, // every request
"/users/*": { staleTime: 60_000 }, // /users/:userId and deeper
// one SDK leaf
"users.$userId.$delete": (request) => request.setCancelable(true),
});
Key patternMatchesApplied
"*"Every requestFirst
"/users"Every method of that exact endpointSecond
"/users/*"Endpoints below /usersSecond
"users.$userId.$get"One SDK leafLast

Later matches override earlier ones. Dot-path keys are checked against the schema, so a typo fails to compile. Object values accept headers, auth, cache, cacheTime, staleTime, retry, retryTime, cancelable, queued, offline, deduplicate, deduplicateTime and structuralSharing.

Split a large configuration by domain with createConfiguration, then chain the $configure calls:

api/users.configure.ts
import { createConfiguration } from "@hyper-fetch/core";

export const usersConfig = createConfiguration<ApiSchema>()({
"users.$get": { staleTime: 30_000 },
});

// api/sdk.ts
export const configuredSdk = sdk.$configure(usersConfig);

Options​

OptionDefaultDescription
camelCaseToKebabCasetrueTurn camelCase keys into kebab-case segments (userProfiles → user-profiles)
pathSegmentsnoneURL segment of a key when it differs, such as { findByStatus: "findByStatus" }
methodTransform(method) => method.toUpperCase()Turn a $ key into the request method
defaultsnoneThe same map as $configure

Prefer $configure over defaults: its keys are type-checked against the schema.


Keep a reference to a leaf​

Every property access creates a new request. When you attach a mock or $hooks, store the request first and use that variable:

api/users.ts
const getUsers = sdk.users.$get;

getUsers.setMock(() => ({ data: [], status: 200 }));
await getUsers.send();

Summary
  • Describe the API as a schema of RequestModel leaves and call createSdk<typeof client, Schema>(client).
  • Paths are keys, $param keys are URL params, $get, $post and the others are methods.
  • Set defaults per endpoint with $configure or createConfiguration. Keep leaves in variables before mocking them.

Next steps​

Runnable examples: Typed SDK and OpenAPI codegen.

Generate the SDK
Write the schema from an OpenAPI or Swagger document with the CLI.
Socket SDK
The same pattern for realtime listeners and emitters.
createSdk API reference
Signature and options of createSdk.