Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 96 ยท Projects

Project: Typed API Client

Build a type-safe API client in TypeScript - an endpoint map, typed path params, a generic request function, runtime response validation, retries and Result errors.

Calling an HTTP API is where TypeScript's guarantees usually end. fetch returns a Response, response.json() gives you a value of unknown shape, and from then on the code simply hopes the server sent what the documentation promised. Misspell an endpoint, forget a path parameter, or let the backend rename a field, and you find out in production.

In this project you'll build a client that closes those gaps. A single endpoint map describes the API: each endpoint's method and path, its path parameters, its request body and its response. From that map, TypeScript computes the exact arguments and return type of every call. Then you'll add runtime validation, so responses are checked against the same description when they arrive, and finally error handling with Result, including retries and timeouts, so failures become typed values instead of surprise exceptions.

Our editor has no network access, so the "server" is a small in-memory fake with the same signature as fetch, returning real Response objects. The client code never knows the difference: replace fakeFetch with fetch and it talks to a real API.

The plan

Stage What you build Main TypeScript ideas
1 An endpoint map and a generic api() function Template literal types, infer, conditional rest parameters, overloads
2 Schemas that validate every response Type predicates, Infer<typeof schema>, mapped types, satisfies
3 Errors as values, retries and timeouts Discriminated unions, Result<T, E>, exhaustive switch, AbortSignal

Stage 1: an endpoint map

The contract is an interface whose keys are "METHOD /path" strings:

TypeScript
interface Endpoints {
  'GET /users': { response: User[] };
  'GET /users/:userId': { response: User };
  'POST /posts': { body: Omit<Post, 'id'>; response: Post };
  // ...
}

The rest of the types are computed from those keys with template literal types and conditional types:

  • PathOf<'GET /users/:userId'> strips the method and gives '/users/:userId'.
  • ParamNames<'/users/:userId/posts/:postId'> walks the path recursively with infer and collects 'userId' | 'postId'.
  • RequestOptions<K> requires params only if the path has parameters, and body only if the endpoint declares one.
  • OptionsArg<K> turns that into a rest-parameter tuple: [options?: โ€ฆ] when nothing is required, [options: โ€ฆ] otherwise. So api('GET /users') needs no second argument, while api('GET /users/:userId') without params doesn't compile.

The implementation uses an overload: the public signature is precise and generic, and the implementation signature underneath is simple and wide. Callers only ever see the first one.

TypeScript Stage 1: an endpoint map and a typed request function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Every call is checked against the contract, and every result is typed: users.map((user) => user.name) knows user is a User, ada.id is a number, and created.id exists because POST /posts returns a Post. The last call shows a server-side 404 turning into an exception, which stage 3 will improve.

Here's what the contract rejects. The function is only declared in this example (declare function), because the signatures are all the compiler needs. It fails on purpose:

TypeScript Calls the contract rejects (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(38,11): error TS2345: Argument of type '"GET /user/:userId"' is not assignable to parameter of type 'keyof Endpoints'.
main.ts(39,7): error TS2554: Expected 2 arguments, but got 1.
main.ts(40,45): error TS2353: Object literal may only specify known properties, and 'id' does not exist in type 'Record<"userId", string | number>'.
main.ts(41,28): error TS2741: Property 'userId' is missing in type '{ title: string; }' but required in type 'Omit<Post, "id">'.
main.ts(43,22): error TS2339: Property 'nmae' does not exist on type 'User'.

A misspelled endpoint, missing path parameters, a parameter with the wrong name, an incomplete request body and a typo in a response field: five classic API bugs, all caught before a single request is sent. And because the endpoint names are a union of literals, editors autocomplete them.

Stage 1 has one big hole: return response.json() trusts the server completely. The types say GET /users returns User[], but nothing checks it. If the backend changes id to a string, the compiler can't know, and the client happily hands the wrong data to the rest of your program. Types describe what you expect; only runtime checks tell you what you got.

Stage 2: validating responses with schemas

To check responses at runtime you need the contract as values, not just types. This stage builds a tiny schema library in about 50 lines, the same idea as Zod and Valibot (see Typing APIs and JSON Data):

  • A Schema<T> is an object with one method, is(value, path, issues), whose return type is the type predicate value is T (Custom Type Guards). It records every problem it finds, with a path like response[2].email.
  • string(), number() and boolean() check primitives; array(item) and object(shape) combine schemas.
  • Infer<S> uses infer to read the type back out of a schema. object()'s return type is a mapped type over the shape, so Infer<typeof UserSchema> is { id: number; name: string; email: string }.

That last point changes the design: the schemas become the single source of truth, and the TypeScript types are derived from them. The User interface from stage 1 disappears; type User = Infer<typeof UserSchema> replaces it, and the two can never drift apart.

The endpoint map becomes a constant object of schemas, checked with satisfies so that every entry has a response schema while keeping each entry's precise type. The pretend server now has a broken record (user 3 has a string id and a null email) and a buggy delete endpoint.

TypeScript Stage 2: schemas that validate responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The good responses come back exactly as before, but now they are proven to match their types: ada.email.toUpperCase() is safe because the email was checked to be a string. The bad ones are stopped at the boundary with a precise list of every problem, so { id: '3', email: null } never reaches the rest of your program, and neither does a deleted flag of 'yes'.

Look at parse: after if (schema.is(value, label, issues)), TypeScript has narrowed value from unknown to T, so return value needs no assertion. The only assertion in the schema library is in object(), where an already checked non-null object is viewed as Record<string, unknown> so its properties can be read by name.

Validation also runs on the way out: api('POST /posts', โ€ฆ) checks the request body against NewPostSchema before sending. The compiler already checks bodies you write in code, but bodies built from form input or other untyped data can still be wrong at runtime, and this catches them before the server does.

Stage 3: errors as values

Stage 2 still reports problems by throwing, and a thrown error is invisible in a function's type: Promise<User> says nothing about 404s, timeouts or broken responses. Callers forget to catch, and catch (error) gives them unknown (Error Handling).

This stage makes failure part of the return type. api() now returns Promise<Result<T, ApiError>>, where ApiError is a discriminated union of everything that can go wrong:

TypeScript
type ApiError =
  | { kind: 'network'; message: string }
  | { kind: 'timeout'; ms: number }
  | { kind: 'http'; status: number; message: string }
  | { kind: 'validation'; issues: readonly string[] };

To read the data, callers must check result.ok, and to report an error, they can switch on error.kind, with the compiler making sure every kind is handled. The client also gets smarter about failures:

  • Timeouts use AbortSignal.timeout(ms), which aborts the request with a TimeoutError.
  • Retries happen only for errors worth retrying (network errors, timeouts and 5xx responses), with exponential backoff: 10 ms, then 20 ms. A 404 or a validation error is never retried, because asking again won't change the answer.

The pretend server now has realistic problems: the posts endpoint drops the connection twice before it works, the user list is too slow, and deletes fail with 503 because the database is in maintenance.

TypeScript Stage 3: Result types, retries and timeouts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the output as a story. The posts request fails twice with a network error, is retried with growing delays, and succeeds on the third attempt, so the caller only sees the posts. A missing user is an http error, and the broken user 3 is a validation error; neither is retried. The slow user list times out three times and gives up, and the delete fails three times with 503 before the client reports it.

The types guarantee the important properties:

  • api() never throws for expected failures. Its return type lists them, so posts.value is only reachable after if (posts.ok).
  • describeError is exhaustive without a default branch. Add a fifth kind, such as { kind: 'offline' }, and the function stops compiling (it could return undefined) until you describe the new case.
  • ok() and err() return Result<T, never> and Result<never, E>. Because never is assignable to everything, either one fits any Result<T, E> return type without annotations.
  • isRetryable reads like the policy it implements, thanks to narrowing: error.status is only accessed after error.kind === 'http' is checked.

Should every function return Result instead of throwing? Usually not. A good rule: use Result for failures a caller is expected to handle (network problems, invalid input, "not found"), and keep exceptions for bugs and truly unexpected situations. An API client sits exactly on that boundary, which is why it's the classic place for Result types.

Using the client in a real project

On a real computer, the client works with the real fetch as is:

TypeScript
// before
const response = await fakeFetch(url, { method, body, signal: AbortSignal.timeout(config.timeoutMs) });
// after
const response = await fetch(url, { method, body, headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(config.timeoutMs) });

For production you would probably replace the hand-written schemas with a schema library, generate the endpoint map from an OpenAPI description instead of writing it by hand (Typing APIs and JSON Data shows both), and add authentication headers in one place inside attempt.

Ideas for extending the client

  • Add query parameters to the endpoint map (query: { page: number; limit?: number }) and build the URL with URLSearchParams.
  • Group endpoints into a resource-style client with mapped types, so you can write client.users.get({ userId: 1 }).
  • Cache GET responses for a few seconds in a Map keyed by the URL, and invalidate it after POST or DELETE.
  • Add optional(), literal() and union() schemas, and use them to validate a response like { status: 'active' | 'banned' }.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is ParamNames<'/users/:userId/posts/:postId'>?

    The recursive conditional type matches the first parameter and the rest of the path, then recurses on the rest, collecting every name into a union.
  2. 2. Why does api('GET /users/:userId') (no second argument) fail to compile?

    {} is not assignable to { params: ... }, so OptionsArg chooses the required tuple [options: RequestOptions<K>], and a missing argument is error TS2554.
  3. 3. In stage 1, what happens if the server returns users whose id is a string?

    Types are erased at runtime. Without validation, response.json() is trusted blindly, which is exactly the gap stage 2 closes.
  4. 4. Given const UserSchema = object({ id: number(), name: string() }), what is Infer<typeof UserSchema>?

    object() returns Schema<ObjectOf<S>>, a mapped type that infers each property's type from its schema, and Infer extracts T from Schema<T>.
  5. 5. Which failures does the stage 3 client retry?

    isRetryable returns true for errors that may succeed on a second attempt. A 404 or an invalid response would fail the same way again.

Summary

  • Describe the API once in an endpoint map keyed by "METHOD /path"; template literal and conditional types derive path parameters, bodies and responses from it.
  • A conditional rest-parameter tuple makes the options argument optional or required per endpoint; an overload keeps the public signature precise and the implementation simple.
  • Types are erased, so validate responses at runtime. Schemas with type-predicate is methods narrow unknown to T without assertions, and Infer<typeof schema> derives the types from the schemas.
  • satisfies checks the endpoint map's shape while keeping every entry's precise type.
  • Return Result<T, ApiError> for expected failures; a discriminated ApiError union with an exhaustive switch makes every failure explicit.
  • Retry only what can succeed later (network, timeout, 5xx), with backoff, and use AbortSignal.timeout for time limits.

Next: Project: Type-Safe DOM Widgets.