# StitchAPI > API stitching: turn any API into a typed, resilient function. Declare an endpoint once — its types, auth, and resilience — and call it like a local function, from your code, the CLI, or an AI agent over MCP, without ever touching a credential. fetch/axios are pluggable adapters underneath; a stitch sits above them, it does not replace them. ## What an agent needs to know - API stitching, not an HTTP client: a **stitch** takes one endpoint (HTTP, GraphQL, SSE, an LLM, even a shell command) and hands back a callable. Keep the fetch/axios you already have — it is the adapter underneath. - Capability, not credential: an agent invokes a stitch and gets structured, validated, traceable data; the secret stays behind the boundary. - One context-frugal **code-mode** tool (run_stitch + list_stitches + describe_stitch), not one tool per endpoint — adding APIs never floods the context window. - No server, no codegen, no config files — a URL and one example response is enough; only explicit composition (no ambient/global config a stitch silently inherits). - Zero-dependency core, ~18–22 kB min+gzip, validator-agnostic (bring your own Standard Schema / Zod), and it runs in the browser. - Composes with your data layer: a stitch is the queryFn for TanStack Query / SWR — it owns the call's resilience; your query layer owns view state. ## Quickstart ```ts import { stitch } from 'stitchapi'; const getUser = stitch('https://api.example.com/users/{id}'); const user = await getUser({ params: { id: 1 } }); // typed, validated, traced ``` > API stitching: turn any API into a typed, resilient function — declare an endpoint once and call it like a local function from your code, the CLI, or an agent, without ever touching a credential. - Getting started - [Introduction](/docs/getting-started): What a stitch is, the integration pain it removes, and how this documentation is organized. - [Installation](/docs/getting-started/installation): Install stitchapi and set up the zero-dependency runtime in Node or the browser. - [Quickstart](/docs/getting-started/quickstart): Declare your first stitch from one endpoint and call it as a typed function in five minutes. - [Migration notes](/docs/getting-started/migration-notes): Three spec-correct behaviors — lowercase header names, %20 query spaces, and template-narrowed stitch types — that differ from a naive baseline and surprise migrators. - Recipes - [Recipes](/docs/recipes): Working examples of common tasks — each one the whole thing in a single block, with links down to the guides for depth. - [Send JSON and get a typed result back](/docs/recipes/typed-json-round-trip): POST a validated body and read a typed, runtime-validated result — input checked before the request, output checked after. - [Define an entity once, derive every request shape](/docs/recipes/define-an-entity-once): Declare a resource schema once and derive the create body, update body, and query filter with your validator’s own .omit()/.partial()/.pick() — no StitchAPI-specific schema layer. - [Loop a cursor API into one array](/docs/recipes/paginate-into-one-array): Follow nextCursor across every page and aggregate the items — no manual while-loop, cursor bookkeeping, or concat. - [Make a flaky call succeed on its own](/docs/recipes/make-a-flaky-call-succeed): Add retry with backoff so transient 429s and 5xxs recover without your code noticing. - [Keep a failing dependency from taking you down](/docs/recipes/survive-a-flaky-dependency): Compose timeout, retry, and a circuit breaker so a degraded upstream fails fast instead of hanging every caller. - [Retry a write without double-charging](/docs/recipes/idempotent-writes): Attach an idempotency key so a retried POST settles once, not twice. - [Catch a breaking API change before your users do](/docs/recipes/catch-a-breaking-api-change): Wrap output with drift to compare every response against a committed snapshot and flag dropped fields, type flips, and new keys by severity. - [Catch a silent selector rename in scraped HTML](/docs/recipes/catch-a-selector-rename): Scrape an HTML page into a structured object with transform, then drift the structured shape so a markup or selector rename becomes a loud contract error instead of a silently missing field. - [Watch retries and throttling as they happen](/docs/recipes/watch-a-call-as-it-happens): Iterate a stitch's event stream instead of awaiting it, and observe every retry, pause, and drift in real time. - [Mirror a paginated API to NDJSON](/docs/recipes/mirror-a-paginated-api): Pull every page of a cursor-paginated, OAuth2-protected endpoint — with retry and throttle on each page — and write the rows as newline-delimited JSON. - [Share one rate limit across every worker](/docs/recipes/one-rate-limit-across-workers): Point the throttle at a shared store so a whole fleet draws from a single rate budget instead of N× the limit. - [Authenticate without the token touching your code](/docs/recipes/auth-as-a-capability): Declare auth on the stitch so callers get a capability, not a credential — the secret is read per call and never returned. - [Let an agent call your API without handing it the key](/docs/recipes/expose-a-stitch-to-an-agent): Expose your stitches over MCP through one run_stitch tool — the agent invokes a capability and never sees the credential. - [Call one stitch as a function, a CLI command, and an agent tool](/docs/recipes/one-stitch-every-surface): One definition, four front doors — in-process, shell, HTTP, and MCP — with nothing about the stitch changing. - Concepts - [The stitch primitive](/docs/concepts/the-stitch): A typed, declarative, composable unit that turns input into validated output with auth, resilience, and observability built in. - [The event stream](/docs/concepts/event-stream): Why a stitch returns an async iterable of typed events — start, progress, drift, result, done — instead of Promise. - [Capability, not credential](/docs/concepts/capability-not-credential): How a stitch holds the secret and hands the caller a capability, so an agent invoking it never sees the token. - [Principles](/docs/concepts/principles): Progressive disclosure, atomic stitches, composition over configuration, and the other ideas that shape the API. - Guides - Authoring & composition - [stitch()](/docs/guides/authoring/stitch): Declare an endpoint and get back a typed, callable function — the core authoring move. - [extends](/docs/guides/authoring/extends): Layer fragments — strings, objects, or other stitches — with deep-merge to compose configuration. - [.with() partial application](/docs/guides/authoring/with): Pre-bind part of a call and reuse the same runtime so cookies, throttle, and sessions persist. - [Hooks](/docs/guides/authoring/hooks): Observe a call as it runs — onRequest, onResponse, onError, onRetry — and where each fires relative to auth, retry, throttle, and timeout. - Auth - [bearer](/docs/guides/auth/bearer): Attach a bearer token resolved at call time from an env var or a secrets file. - [apiKey](/docs/guides/auth/api-key): Send an API key as a header or query parameter, resolved at call time. - [basic](/docs/guides/auth/basic): HTTP Basic authentication with credentials resolved from a secret resolver. - [cookieSession](/docs/guides/auth/cookie-session): Log in once, capture and replay cookies, and refresh the session on a status code or a soft 200 wall. - [oauth2](/docs/guides/auth/oauth2): OAuth2 client_credentials: fetch, cache, and auto-refresh a token behind the capability boundary. - [Secret resolvers](/docs/guides/auth/secret-resolvers): Resolve secrets lazily at call time with env() and secretsFile() instead of hard-coding them. - Resilience - [Retry & backoff](/docs/guides/resilience/retry): Retry on configurable status codes with expo/jitter/fixed backoff and respect for Retry-After. - [Accept status](/docs/guides/resilience/accept-status): Declare statuses that are a normal result, not an error — an accepted non-2xx flows through transform/unwrap/validate instead of throwing. - [Throttle](/docs/guides/resilience/throttle): Space requests by rate and cap concurrency, scoped per stitch or per host. - [Timeouts](/docs/guides/resilience/timeout): Enforce total and per-attempt timeouts with a real AbortSignal. - [Circuit breaker](/docs/guides/resilience/circuit-breaker): Stop hammering a failing dependency by opening a circuit after repeated failures. - [Delegate backoff](/docs/guides/resilience/delegate-backoff): Surface rate-limit outcomes as a RateLimitError so an outer gate owns the backoff, instead of retrying and throttling them internally. - [Idempotency keys](/docs/guides/resilience/idempotency): Attach idempotency keys to writes so safe retries don't duplicate side effects. - Data shaping - [unwrap](/docs/guides/data/unwrap): Pull just the part of the response you want by dot-path. - [transform](/docs/guides/data/transform): Reshape a response before unwrap and validation — for example, scrape HTML into structured data. - [Pagination](/docs/guides/data/pagination): Auto-loop pages and aggregate items, with auth, retry, and throttle applied to every page. - [Body encoding](/docs/guides/data/body-encoding): Send request bodies as json, form, or multipart. - [URL shaping](/docs/guides/data/url-shaping): RFC 6570 path templates and qs-style nested query serialization — how params and query become the URL. - [GraphQL](/docs/guides/data/graphql): Call a GraphQL endpoint with variables, unwrap data, and treat a 200 carrying errors as a failure. - Validation & drift - [Validation](/docs/guides/validation/validation): Validate params, query, body, headers, and the response, failing fast before the request when input is wrong. - [Leveled drift](/docs/guides/validation/drift): Detect silent contract changes as leveled findings (error/warn/info) against a committed snapshot. - [Standard Schema](/docs/guides/validation/standard-schema): Bring any Standard Schema validator — Zod, Valibot, ArkType — for validation and inferred types. - Observability - [Trace sinks](/docs/guides/observability/trace-sinks): Tracing is off by default — opt in with trace: console, a fileSink, env vars, or your own TraceSink. - [OTLP export](/docs/guides/observability/otlp): Export traces as OpenTelemetry spans for your existing observability stack. - State & stores - [The pluggable store](/docs/guides/state/pluggable-store): Swap the in-memory store for a shared one to back throttle and sessions with get/set/incr + TTL. - [Distributed throttle](/docs/guides/state/distributed-throttle): Share one rate budget across workers by pointing the throttle at a shared store. - [Shared sessions](/docs/guides/state/shared-sessions): Persist and share a login across stitches and workers via a session key and a shared store. - Testing - [Testing](/docs/guides/testing/mocking): Mock the transport to test a stitch definition, or swap in a fake stitch to test code that calls one — from stitchapi/testing. - Surfaces - [In-process function](/docs/surfaces/function): Call a stitch directly as a typed async function, awaited or streamed. - [CLI](/docs/surfaces/cli): Run, trace, diagram, and export stitches from the shell — no app boot. - [HTTP serve](/docs/surfaces/http-serve): Expose a stitch over HTTP for callers that aren't in-process. - [MCP](/docs/surfaces/mcp): Expose a single code-mode run_stitch tool to agents instead of one tool per endpoint. - Integrations - [Integrations](/docs/integrations): First-party companion packages that bridge a stitch to the framework, frontend, logger, and store you already run — each a thin layer over a stable seam, never a re-implementation. - **Server frameworks** - [Elysia](/docs/integrations/elysia): An Elysia plugin for StitchAPI — a principal-bound seam on the request context, an SSE bridge with streamStitchSse returning a Response, and stitch errors mapped to HTTP via the plugin's onError. - [Express](/docs/integrations/express): Express 4/5 middleware for StitchAPI — a principal-bound seam on req.stitch, an SSE bridge with streamStitchSse, and stitch errors mapped to JSON by a 4-arg error handler. - [Fastify](/docs/integrations/fastify): Register stitchPlugin and your Fastify app gets a shared seam, a request-scoped principal, and bridges into Fastify's Pino logger, SSE streaming, and error handling. - [Hono](/docs/integrations/hono): Edge-ready Hono middleware for StitchAPI — a principal-bound seam on c.var.stitch, an SSE bridge with streamStitchSse, and stitch errors mapped to HTTPException. - [NestJS](/docs/integrations/nestjs): Wire stitches into a NestJS app with StitchModule — injectable stitches, a Logger trace bridge, ConfigService-backed secrets, and request-scoped multi-tenancy. - [Next.js](/docs/integrations/next): Web-standard helpers for Next App Router route handlers — sseResponse streams a stitch as text/event-stream, and stitchErrorResponse maps a StitchError to a Response. - **Client & UI bindings** - [Angular](/docs/integrations/angular): injectStitch and injectStitchStream expose a stitch's lifecycle as both Angular signals and an RxJS observable over the framework-agnostic @stitchapi/query-core store — plus an optional TanStack Query adapter. - [Expo](/docs/integrations/expo): expoFetchAdapter streams over expo/fetch with no polyfills, and expoSecureStore keeps auth tokens encrypted — over the same hooks, AsyncStorage store, and lifecycle helpers as @stitchapi/react-native. - [React](/docs/integrations/react): Tearing-free useStitch and useStitchStream hooks built on useSyncExternalStore, over the framework-agnostic @stitchapi/query-core store — plus an optional TanStack Query adapter. - [React Native](/docs/integrations/react-native): A streaming XHR adapter (the streaming fetch bare RN lacks), an AsyncStorage-backed StitchStore for persistent sessions, and AppState/NetInfo refetch helpers — plus the re-exported useStitch / useStitchStream hooks. - [Solid](/docs/integrations/solid): createStitch and createStitchStream primitives that reconcile a Solid store from a stitch call, over the framework-agnostic @stitchapi/query-core store — plus an optional TanStack Query adapter. - [Svelte](/docs/integrations/svelte): stitchStore and stitchStreamStore — real Svelte stores wrapping a stitch call, over the framework-agnostic @stitchapi/query-core store. Works on Svelte 4 and 5, plus an optional TanStack Query adapter. - [Vue](/docs/integrations/vue): Reactive useStitch and useStitchStream composables backed by Vue 3 reactivity, over the framework-agnostic @stitchapi/query-core store — plus an optional TanStack Query adapter. - **Data-fetching libraries** - [RTK Query](/docs/integrations/rtk-query): stitchQueryFn turns a stitch into an RTK Query endpoint, and stitchStreamUpdater folds a streaming stitch into the cache — RTK Query keeps the cache, tags, and generated hooks. - [SWR](/docs/integrations/swr): useStitchSWR runs a stitch as an SWR fetcher, so SWR owns caching and revalidation while the stitch stays typed, validated, and traced. - [TanStack Query](/docs/integrations/tanstack-query): A stitch is the queryFn. StitchAPI owns the call’s resilience; TanStack Query (or SWR) owns view state — they compose, they do not compete. - **State stores** - [Distributed stores](/docs/integrations/stores): Attach a Redis, Cloudflare Workers KV, or Deno KV StitchStore so a stitch's throttle, sessions, and cache become fleet-wide — same call site, no backend in core. Includes the atomic-incr trade-off that decides which store fits. - **Auth** - [AWS SigV4](/docs/integrations/aws-sigv4): awsSigV4 signs each request with AWS Signature Version 4 — the request-signing AuthStrategy that core's built-in bearer/apiKey/basic/oauth2 don't cover. Edge-safe Web Crypto, no dependencies. - **AI** - [Vercel AI SDK](/docs/integrations/vercel-ai): stitchTool exposes a stitch as a Vercel AI SDK tool() the model can call — the stitch runs as the tool's execute, so the model gets typed, validated data and never the credential. - **Observability** - [Pino](/docs/integrations/pino): Forward a stitch's event stream to a Pino logger with pinoSink — structured, leveled logs at every call site, metadata-only and safe on a secret-bearing seam. - [Sentry](/docs/integrations/sentry): A Sentry TraceSink that maps the stitch event stream to breadcrumbs and captures error events with the call's context — metadata-only, safe on a secret-bearing seam. - For agents - [Use from an agent](/docs/agents): How an agent invokes, authors, and reasons over stitches — the agent entry point. - [run_stitch & code-mode](/docs/agents/run-stitch-tool): Drive stitches from a sandbox with one context-frugal tool instead of flooding the model with per-endpoint tools. - [Author from one example](/docs/agents/author-from-one-example): Have an agent emit a stitch declaration from a single curl, HAR, or doc snippet. - [Adopt in your project](/docs/agents/adopt-in-your-project): Drop a rule into your repo so any agent reaches for a typed stitch instead of a hand-rolled fetch — by hand, or with npx stitch init. - [Point an agent at llms.txt](/docs/agents/llms-txt): Feed the auto-generated llms.txt and per-page llms.mdx to an agent for context-frugal docs. - Reference - [stitch()](/docs/reference/stitch): Signatures for stitch() and graphql(). - [Auth strategies](/docs/reference/auth-strategies): bearer, apiKey, basic, cookieSession, oauth2, and the env(), optionalEnv(), secretsFile(), and secretFrom() resolvers. - [Config types](/docs/reference/config-types): StitchConfig and the retry, throttle, timeout, auth, validation, and drift option shapes. - [Request surfaces](/docs/reference/surfaces): http, graphql, sse, stream, and download — the request styles a stitch can speak, each a subpath import riding one engine. - [Helpers](/docs/reference/helpers): fetchAdapter, axiosAdapter, xhrAdapter, consoleSink, fileSink, createTrace, multiplex, loggerSink, the OTLP exporters, memoryStore, and toValidator. - [Conformance kits](/docs/reference/conformance-kits): Prove a custom adapter, store, or trace sink implements its seam — from stitchapi/testing, in your own CI. - [Event types](/docs/reference/events): The StitchEvent union and the shape of each event in the stream. - Errors & pitfalls - [Errors & pitfalls](/docs/errors): How StitchAPI errors work, the code-to-docs contract, and an index of every coded failure. - [STITCH_VALIDATION](/docs/errors/stitch-validation): Input or response failed schema validation. - [STITCH_DRIFT](/docs/errors/stitch-drift): An error-level drift finding broke the response contract. - [STITCH_AUTH_WALL](/docs/errors/stitch-auth-wall): Authentication failed, or a soft 200 login wall was hit and could not be refreshed. - [STITCH_TIMEOUT](/docs/errors/stitch-timeout): A total or per-attempt timeout aborted the call. - [STITCH_CIRCUIT_OPEN](/docs/errors/stitch-circuit-open): The circuit breaker is open after repeated failures and short-circuited the call. - [STITCH_GRAPHQL](/docs/errors/stitch-graphql): A GraphQL 200 response carried an errors array and failed the call. - [RateLimitError](/docs/errors/rate-limit): The delegate-backoff error: a rate-limit response surfaced for an outer gate to back off on, instead of being retried internally.