Organizing an API
Declarations are ordinary exported values, so structuring them is mostly ordinary module design. This page collects the conventions that hold up as an API grows from five endpoints to a few hundred.
One builder per backend
A builder is the unit that shares an HTTP client and an onError hook. Create it in its own module and import it wherever endpoints are declared.
Putting reporting in onError means individual call sites only handle the failures they can do something about.
One module per resource
Group a resource's schemas and endpoints in one file. They change together, and a reader looking for "everything about users" finds it in one place.
Two things in that file are worth copying:
- Derive, do not restate.
userInputand its.partial()followuserSchemaautomatically. - Share error schemas. An object such as
userNotFoundused by several endpoints keeps their error bodies identical.
Name endpoints by what they do
Use a verb and the resource: getUser, listUsers, createUser, updateUser, deleteUser. The name is what appears at every call site and in every hook, so it matters more than the URL.
Name URL parameters after what they identify. /users/$userId/posts/$postId reads correctly at the call site; /users/$id/posts/$id2 does not.
Export types from declarations
When other code needs a type, derive it from the declaration instead of exporting a second, hand-written one.
For a resource type used on its own, inferring from the schema is equivalent and sometimes clearer: type User = z.output<typeof userSchema>.
Repeated shapes
When several endpoints share a shape, write a function that builds the schema.
Prefer this to a helper that wraps declareEndpoint itself. Wrappers tend to lose type inference, and a declaration that spells out its method, URL and schemas is easier to search for.
Decide where failures are handled
A consistent rule keeps error handling from spreading through the codebase:
- Report everything once, in the builder's
onError. - Declare
errorSchemaonly for statuses you act on. A 409 that becomes a form message deserves a schema. A 500 does not. - Use
.safe()where a failure is an expected outcome, and let the throwing form propagate everywhere else.
Errors has the API for each.
When the server is yours too
If the same team owns the server, move the api/ folder into a package both sides import, and create the builder without a client. Sharing with Navios Server shows the layout.