|
| 1 | +# api-contracts |
| 2 | + |
| 3 | +API contracts are shared definitions that live in a shared package and are consumed by both the client and the backend. The contract describes a route — its path, HTTP method, and request/response schemas — and serves as the single source of truth for both sides. |
| 4 | + |
| 5 | +The backend implements the route against the contract. The client uses the same contract to make type-safe requests without duplicating configuration. This eliminates assumptions across the boundary and keeps documentation, validation, and types in sync. |
| 6 | + |
| 7 | +## Defining contracts |
| 8 | + |
| 9 | +### REST routes |
| 10 | + |
| 11 | +```ts |
| 12 | +import { defineApiContract, ContractNoBody } from '@lokalise/api-contracts' |
| 13 | +import { z } from 'zod/v4' |
| 14 | + |
| 15 | +// GET with path params |
| 16 | +const getUser = defineApiContract({ |
| 17 | + method: 'get', |
| 18 | + requestPathParamsSchema: z.object({ userId: z.uuid() }), |
| 19 | + pathResolver: ({ userId }) => `/users/${userId}`, |
| 20 | + responseSchemasByStatusCode: { |
| 21 | + 200: z.object({ id: z.string(), name: z.string() }), |
| 22 | + }, |
| 23 | +}) |
| 24 | + |
| 25 | +// POST |
| 26 | +const createUser = defineApiContract({ |
| 27 | + method: 'post', |
| 28 | + pathResolver: () => '/users', |
| 29 | + requestBodySchema: z.object({ name: z.string() }), |
| 30 | + responseSchemasByStatusCode: { |
| 31 | + 201: z.object({ id: z.string(), name: z.string() }), |
| 32 | + }, |
| 33 | +}) |
| 34 | + |
| 35 | +// DELETE with no response body |
| 36 | +const deleteUser = defineApiContract({ |
| 37 | + method: 'delete', |
| 38 | + requestPathParamsSchema: z.object({ userId: z.uuid() }), |
| 39 | + pathResolver: ({ userId }) => `/users/${userId}`, |
| 40 | + responseSchemasByStatusCode: { |
| 41 | + 204: ContractNoBody, |
| 42 | + }, |
| 43 | +}) |
| 44 | +``` |
| 45 | + |
| 46 | +### Non-JSON responses |
| 47 | + |
| 48 | +Use `textResponse` for plain-text or CSV responses, and `blobResponse` for binary responses (images, PDFs, etc.). Both carry the content type. |
| 49 | + |
| 50 | +```ts |
| 51 | +import { defineApiContract, textResponse, blobResponse } from '@lokalise/api-contracts' |
| 52 | + |
| 53 | +const exportCsv = defineApiContract({ |
| 54 | + method: 'get', |
| 55 | + pathResolver: () => '/export.csv', |
| 56 | + responseSchemasByStatusCode: { |
| 57 | + 200: textResponse('text/csv'), |
| 58 | + }, |
| 59 | +}) |
| 60 | + |
| 61 | +const downloadPhoto = defineApiContract({ |
| 62 | + method: 'get', |
| 63 | + pathResolver: () => '/photo.png', |
| 64 | + responseSchemasByStatusCode: { |
| 65 | + 200: blobResponse('image/png'), |
| 66 | + }, |
| 67 | +}) |
| 68 | +``` |
| 69 | + |
| 70 | +### SSE and dual-mode routes |
| 71 | + |
| 72 | +Use `sseResponse()` inside `responseSchemasByStatusCode` to define SSE event schemas. For endpoints that can respond with either JSON or an SSE stream depending on the `Accept` header, use `anyOfResponses()` to declare both options on the same status code. |
| 73 | + |
| 74 | +```ts |
| 75 | +import { defineApiContract, sseResponse, anyOfResponses } from '@lokalise/api-contracts' |
| 76 | +import { z } from 'zod/v4' |
| 77 | + |
| 78 | +// SSE-only |
| 79 | +const notifications = defineApiContract({ |
| 80 | + method: 'get', |
| 81 | + pathResolver: () => '/notifications/stream', |
| 82 | + responseSchemasByStatusCode: { |
| 83 | + 200: sseResponse({ |
| 84 | + notification: z.object({ id: z.string(), message: z.string() }), |
| 85 | + }), |
| 86 | + }, |
| 87 | +}) |
| 88 | + |
| 89 | +// Dual-mode: JSON response or SSE stream depending on Accept header |
| 90 | +const chatCompletion = defineApiContract({ |
| 91 | + method: 'post', |
| 92 | + pathResolver: () => '/chat/completions', |
| 93 | + requestBodySchema: z.object({ message: z.string() }), |
| 94 | + responseSchemasByStatusCode: { |
| 95 | + 200: anyOfResponses([ |
| 96 | + sseResponse({ |
| 97 | + chunk: z.object({ delta: z.string() }), |
| 98 | + done: z.object({ finish_reason: z.string() }), |
| 99 | + }), |
| 100 | + z.object({ text: z.string() }), |
| 101 | + ]), |
| 102 | + }, |
| 103 | +}) |
| 104 | +``` |
| 105 | + |
| 106 | +`getSseSchemaByEventName(contract)` extracts SSE event schemas from a contract: |
| 107 | + |
| 108 | +```ts |
| 109 | +import { getSseSchemaByEventName } from '@lokalise/api-contracts' |
| 110 | + |
| 111 | +getSseSchemaByEventName(notifications) |
| 112 | +// { notification: ZodObject<...> } |
| 113 | + |
| 114 | +getSseSchemaByEventName(chatCompletion) |
| 115 | +// { chunk: ZodObject<...>, done: ZodObject<...> } |
| 116 | +``` |
| 117 | + |
| 118 | +### All fields |
| 119 | + |
| 120 | +```ts |
| 121 | +defineApiContract({ |
| 122 | + // Required |
| 123 | + method: 'get' | 'post' | 'put' | 'patch' | 'delete', |
| 124 | + pathResolver: (pathParams) => string, |
| 125 | + responseSchemasByStatusCode: { |
| 126 | + [statusCode]: z.ZodType | ContractNoBody | TypedTextResponse | TypedBlobResponse | TypedSseResponse | AnyOfResponses |
| 127 | + }, |
| 128 | + |
| 129 | + // Path params — links pathResolver parameter type to the schema |
| 130 | + requestPathParamsSchema: z.ZodType, |
| 131 | + |
| 132 | + // Request |
| 133 | + requestBodySchema: z.ZodType | ContractNoBody, // POST / PUT / PATCH only |
| 134 | + requestQuerySchema: z.ZodType, |
| 135 | + requestHeaderSchema: z.ZodType, |
| 136 | + |
| 137 | + // Response |
| 138 | + responseHeaderSchema: z.ZodType, |
| 139 | + |
| 140 | + // Documentation |
| 141 | + summary: string, |
| 142 | + description: string, |
| 143 | + tags: readonly string[], |
| 144 | + metadata: Record<string, unknown>, |
| 145 | +}) |
| 146 | +``` |
| 147 | + |
| 148 | +### Header schemas |
| 149 | + |
| 150 | +```ts |
| 151 | +const contract = defineApiContract({ |
| 152 | + method: 'get', |
| 153 | + pathResolver: () => '/api/data', |
| 154 | + requestHeaderSchema: z.object({ |
| 155 | + authorization: z.string(), |
| 156 | + 'x-api-key': z.string(), |
| 157 | + }), |
| 158 | + responseHeaderSchema: z.object({ |
| 159 | + 'x-ratelimit-remaining': z.string(), |
| 160 | + 'cache-control': z.string(), |
| 161 | + }), |
| 162 | + responseSchemasByStatusCode: { |
| 163 | + 200: dataSchema, |
| 164 | + }, |
| 165 | +}) |
| 166 | +``` |
| 167 | + |
| 168 | +### Type utilities |
| 169 | + |
| 170 | +**`InferNonSseSuccessResponses<T>`** — TypeScript output type of all non-SSE 2xx responses. JSON schemas → `z.output<T>`, `textResponse` → `string`, `blobResponse` → `Blob`, `ContractNoBody` → `undefined`, `sseResponse` → `never` (excluded). `anyOfResponses` entries are unpacked before mapping. |
| 171 | + |
| 172 | +```ts |
| 173 | +import type { InferNonSseSuccessResponses } from '@lokalise/api-contracts' |
| 174 | + |
| 175 | +type UserResponse = InferNonSseSuccessResponses<typeof getUser['responseSchemasByStatusCode']> |
| 176 | +// { id: string; name: string } |
| 177 | + |
| 178 | +type CsvResponse = InferNonSseSuccessResponses<typeof exportCsv['responseSchemasByStatusCode']> |
| 179 | +// string |
| 180 | +``` |
| 181 | +
|
| 182 | +**`InferJsonSuccessResponses<T>`** — union of Zod schema types for all JSON 2xx entries. Text, Blob, SSE, and `ContractNoBody` entries are excluded. |
| 183 | +
|
| 184 | +**`InferSseSuccessResponses<T>`** — extracts the SSE event schema map type from a `responseSchemasByStatusCode` map. Returns `never` when no SSE schemas are present. |
| 185 | +
|
| 186 | +**`HasAnySseSuccessResponse<T>`** — `true` if any 2xx entry is a `TypedSseResponse` or an `AnyOfResponses` containing one. |
| 187 | +
|
| 188 | +**`HasAnyJsonSuccessResponse<T>`** — `true` if any 2xx entry is a JSON Zod schema or an `AnyOfResponses` containing one. |
| 189 | +
|
| 190 | +**`IsNoBodySuccessResponse<T>`** — `true` when all 2xx entries are `ContractNoBody` or no 2xx status codes are defined. |
| 191 | +
|
| 192 | +### Utility functions |
| 193 | +
|
| 194 | +**`mapApiContractToPath`** — Express/Fastify-style path pattern. |
| 195 | +
|
| 196 | +```ts |
| 197 | +import { mapApiContractToPath } from '@lokalise/api-contracts' |
| 198 | + |
| 199 | +mapApiContractToPath(getUser) // "/users/:userId" |
| 200 | +``` |
| 201 | + |
| 202 | +**`describeApiContract`** — human-readable `"METHOD /path"` string. |
| 203 | + |
| 204 | +```ts |
| 205 | +import { describeApiContract } from '@lokalise/api-contracts' |
| 206 | + |
| 207 | +describeApiContract(getUser) // "GET /users/:userId" |
| 208 | +``` |
| 209 | + |
| 210 | +**`getSuccessResponseSchema`** — merged Zod schema from all 2xx JSON entries. `ContractNoBody` and non-JSON entries are excluded. Returns `null` when no schema is present. |
| 211 | + |
| 212 | +```ts |
| 213 | +import { getSuccessResponseSchema } from '@lokalise/api-contracts' |
| 214 | + |
| 215 | +getSuccessResponseSchema(getUser) // ZodObject |
| 216 | +getSuccessResponseSchema(deleteUser) // null |
| 217 | +``` |
| 218 | + |
| 219 | +**`getIsEmptyResponseExpected`** — `true` when no Zod schema exists among 2xx entries. |
| 220 | + |
| 221 | +```ts |
| 222 | +import { getIsEmptyResponseExpected } from '@lokalise/api-contracts' |
| 223 | + |
| 224 | +getIsEmptyResponseExpected(deleteUser) // true |
| 225 | +getIsEmptyResponseExpected(getUser) // false |
| 226 | +``` |
| 227 | + |
| 228 | +**`getSseSchemaByEventName`** — extracts SSE event schemas from a contract. Returns `null` when no SSE schemas are present. |
| 229 | + |
| 230 | +```ts |
| 231 | +import { getSseSchemaByEventName } from '@lokalise/api-contracts' |
| 232 | + |
| 233 | +getSseSchemaByEventName(notifications) // { notification: ZodObject<...> } |
| 234 | +getSseSchemaByEventName(getUser) // null |
| 235 | +``` |
| 236 | + |
0 commit comments