### Install and Run Fastify Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/examples/with-fastify/README.md Commands to install dependencies, build the project, and start the Fastify development server for the with-fastify example. ```bash pnpm install pnpm run build pnpm run dev -w with-fastify ``` -------------------------------- ### Install and Run Next.js Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/examples/with-nextjs/README.md Commands to install dependencies, build the project, and start the development server for the Next.js example. ```bash pnpm install pnpm run build pnpm run dev -w with-nextjs ``` -------------------------------- ### Install and Run NuxtJS Project Source: https://github.com/mcampa/trpc-to-openapi/blob/master/examples/with-nuxtjs/README.md Install project dependencies, build the project, and start the NuxtJS development server. ```bash pnpm install pnpm run build pnpm run dev -w with-nuxtjs ``` -------------------------------- ### Install and Run Express Development Server Source: https://github.com/mcampa/trpc-to-openapi/blob/master/examples/with-express/README.md Install dependencies, build the project, and start the development server for the Express integration. ```bash pnpm install pnpm run build pnpm run dev -w with-express ``` -------------------------------- ### GET Request Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/README.md Demonstrates a GET request procedure with path and optional query parameters, showing the request and expected response. ```typescript // Procedure .meta({ openapi: { method: 'GET', path: '/users/{id}' } }) .input(z.object({ id: z.string(), active: z.boolean().optional() })) .output(userSchema) .query(({ input }) => {...}) // Request GET /api/users/123?active=true // Extracted input { id: '123', active: true } // Response 200 OK { "id": "123", "name": "John", "email": "john@example.com" } ``` -------------------------------- ### HTTP Request/Response Examples Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/INDEX.md Illustrates common HTTP request and response patterns for GET, POST, and DELETE operations, including parameter extraction and return types. ```text GET /users/{id}?active=true → Extracts: { id: string, active: boolean } ← Returns: 200 OK { id, name, email, ... } POST /users Content-Type: application/json { "name": "John", "email": "..." } → Extracts: { name: string, email: string } ← Returns: 200 OK { id, name, email, ... } DELETE /users/{id} → Extracts: { id: string } ← Returns: 200 OK { success: boolean } ``` -------------------------------- ### Get Users Procedure with Query Parameters Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of configuring a GET request with optional query parameters for filtering and pagination. ```APIDOC ## GET /users ### Description Retrieves a list of users with optional filtering and pagination. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of users to return. - **offset** (number) - Optional - The number of users to skip. - **search** (string) - Optional - A search term to filter users. ``` -------------------------------- ### Get User Posts Procedure Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example demonstrating path parameters for a GET request to retrieve a user's posts, specifying both userId and postId. ```APIDOC ## GET /users/{userId}/posts/{postId} ### Description Retrieves a specific post for a given user. ### Method GET ### Endpoint /users/{userId}/posts/{postId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user. - **postId** (string) - Required - The ID of the post. ``` -------------------------------- ### Install trpc-to-openapi Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/README.md Install the trpc-to-openapi library using npm. ```bash npm install trpc-to-openapi ``` -------------------------------- ### Basic Node.js HTTP Server Setup Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/adapters.md Sets up a basic Node.js HTTP server using the `createOpenApiHttpHandler`. ```typescript import http from 'http'; import { createOpenApiHttpHandler } from 'trpc-to-openapi'; import { appRouter } from './router'; const server = http.createServer( createOpenApiHttpHandler({ router: appRouter }) ); server.listen(3000); ``` -------------------------------- ### Basic OpenAPI Endpoint Configuration Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/types.md Example of configuring a tRPC procedure with minimal OpenAPI metadata, including HTTP method and path. Ensure the path starts with a '/'. ```typescript const t = initTRPC.meta().create(); export const appRouter = t.router({ getUser: t.procedure .meta({ openapi: { method: 'GET', path: '/users/{id}', }, }) .input(z.object({ id: z.string() })) .output(z.object({ id: z.string(), name: z.string() })) .query(({ input }) => ({ id: input.id, name: 'John' })); ``` -------------------------------- ### GET /say-hello/{name} Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md A GET procedure that takes a name from the path and a greeting from the query parameter to return a personalized greeting. ```APIDOC ## GET /say-hello/{name} ### Description A GET procedure that takes a name from the path and a greeting from the query parameter to return a personalized greeting. ### Method GET ### Endpoint /say-hello/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name to greet. #### Query Parameters - **greeting** (string) - Required - The greeting to use. ### Request Example ```http GET http://localhost:3000/say-hello/Lily?greeting=Hello ``` ### Response #### Success Response (200) - **greeting** (string) - The personalized greeting. #### Response Example ```json { "greeting": "Hello Lily!" } ``` ``` -------------------------------- ### GET /say-hello (Protected) Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md A protected GET procedure that requires authentication and returns a personalized greeting based on the authenticated user. ```APIDOC ## GET /say-hello (Protected) ### Description A protected GET procedure that requires authentication and returns a personalized greeting based on the authenticated user. ### Method GET ### Endpoint /say-hello ### Parameters #### Query Parameters (No query parameters defined for this procedure) #### Request Body (No request body defined for this procedure) ### Request Example ```http GET http://localhost:3000/say-hello Authorization: Bearer usr_123 ``` ### Response #### Success Response (200) - **greeting** (string) - The personalized greeting. #### Response Example ```json { "greeting": "Hello Lily!" } ``` ### Authorization Requires `Authorization: Bearer ` header. ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/getting-started.md Ensure you have the necessary peer dependencies installed for trpc-to-openapi to function correctly. ```bash npm install @trpc/server zod zod-openapi ``` -------------------------------- ### Create and Test OpenAPI HTTP Handler Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/getting-started.md This example demonstrates creating an OpenAPI HTTP handler and testing a GET request. It simulates an incoming request and checks the response status code. ```typescript import { createOpenApiHttpHandler } from 'trpc-to-openapi'; import { appRouter } from './router'; describe('OpenAPI Handler', () => { it('should handle GET request', async () => { const handler = createOpenApiHttpHandler({ router: appRouter }); const req = new IncomingMessage(null); req.method = 'GET'; req.url = '/say-hello?name=World'; req.headers = {}; const res = new ServerResponse(req); await handler(req, res); expect(res.statusCode).toBe(200); }); }); ``` -------------------------------- ### Get User Procedure with Error Documentation Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of documenting specific error responses for a GET user endpoint, including status codes and descriptions. ```APIDOC ## GET /users/{id} ### Description Retrieves a user by ID. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. ### Error Handling - **400**: Invalid user ID format. - **404**: User not found. - **500**: Database error. ``` -------------------------------- ### Example Client Requests Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md Demonstrates how to make fetch requests to the exposed tRPC procedures via OpenAPI endpoints. ```typescript // client.ts const res = await fetch('http://localhost:3000/say-hello?name=OpenAPI', { method: 'GET' }); const body = await res.json(); /* { greeting: 'Hello OpenAPI!' } */ const statusRes = await fetch('http://localhost:3000/status', { method: 'GET' }); const statusBody = await statusRes.json(); /* { status: 'healthy' } */ ``` -------------------------------- ### Create User Procedure Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of configuring a POST request with a JSON request body for creating a new user. ```APIDOC ## POST /users ### Description Creates a new user record. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **age** (number) - Optional - The age of the user. ``` -------------------------------- ### POST Request Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/README.md Illustrates a POST request procedure with path parameters and a JSON body, detailing the request and expected response. ```typescript // Procedure .meta({ openapi: { method: 'POST', path: '/users/{orgId}' } }) .input(z.object({ orgId: z.string(), // from path name: z.string(), // from body email: z.string(), })) .output(userSchema) .mutation(({ input }) => {...}) // Request POST /api/users/org123 Content-Type: application/json { "name": "John", "email": "john@example.com" } // Extracted input { orgId: 'org123', name: 'John', email: 'john@example.com' } // Response 200 OK { "id": "123", "name": "John", "email": "john@example.com" } ``` -------------------------------- ### Admin User Creation with Security Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of configuring a procedure that requires authentication for administrative user creation. ```APIDOC ## POST /admin/users ### Description Creates a new user in the admin section. ### Method POST ### Endpoint /admin/users ### Security This endpoint requires authentication. ``` -------------------------------- ### Express Server Setup with OpenAPI Middleware Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/adapters.md Sets up an Express server to use the `createOpenApiExpressMiddleware` for handling OpenAPI requests. ```typescript import express from 'express'; import { createOpenApiExpressMiddleware } from 'trpc-to-openapi'; import { appRouter } from './router'; const app = express(); app.use('/api', createOpenApiExpressMiddleware({ router: appRouter })); app.listen(3000); ``` -------------------------------- ### Success Response Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Shows an example of a successful response payload based on a defined output schema. ```typescript .output(z.object({ id: z.string(), name: z.string() })) // Returns HTTP 200 with: // { "id": "123", "name": "John" } ``` -------------------------------- ### Webhook Procedure with Custom Headers Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example demonstrating the configuration of custom request and response headers for a webhook endpoint. ```APIDOC ## POST /webhooks ### Description Handles incoming webhooks. ### Method POST ### Endpoint /webhooks ### Parameters #### Request Body (No specific request body defined in this snippet, but content types are specified) ### Response #### Response Headers - **x-rate-limit-remaining** (string) - The number of remaining requests allowed in the current rate limit window. ``` -------------------------------- ### Next.js API Route Setup Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/adapters.md Sets up a Next.js API route handler using `createOpenApiNextHandler`. ```typescript // pages/api/[...trpc].ts import { createOpenApiNextHandler } from 'trpc-to-openapi'; import { appRouter } from '../../server/router'; export default createOpenApiNextHandler({ router: appRouter }); ``` -------------------------------- ### Fixing Unsupported Content Type Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/errors.md Example demonstrating how to set the correct Content-Type header to avoid the 'Unsupported Media Type' error. ```typescript const response = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, // ✓ Correct body: JSON.stringify({ name: 'John' }), }); ``` -------------------------------- ### Usage of createProcedureCache Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/utils.md Demonstrates how to use the `createProcedureCache` function to get a procedure and its associated path input. ```typescript const getProcedure = createProcedureCache(router); const result = getProcedure('GET', '/users/123'); if (result) { const { procedure, pathInput } = result; // pathInput = { id: '123' } } ``` -------------------------------- ### OpenAPI Endpoint with Documentation and Security Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/types.md Example demonstrating how to add documentation (summary, description) and security (protect: true) to an OpenAPI endpoint. This enhances API discoverability and access control. ```typescript .meta({ openapi: { method: 'POST', path: '/users', summary: 'Create user', description: 'Creates a new user account', protect: true, tags: ['users'], }, }) ``` -------------------------------- ### Basic OpenAPI Document Generation Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of generating an OpenAPI document with required options and specifying the OpenAPI version. ```typescript const doc = generateOpenApiDocument(router, { title: 'My API', version: '1.0.0', baseUrl: 'https://api.example.com', openApiVersion: '3.1.0', // or '3.0.0' }); ``` -------------------------------- ### Client POST Request Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Demonstrates how a client would make a POST request to the defined endpoint, including setting the Content-Type header and providing the JSON body. ```typescript const response = await fetch('/api/users/123/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'My Post', content: 'Content here...', }), }); ``` -------------------------------- ### Client DELETE Request Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Demonstrates how a client would make a DELETE request, including passing path parameters and query parameters. ```typescript const response = await fetch('/api/users/123?permanent=true', { method: 'DELETE', }); ``` -------------------------------- ### Multiple Custom Security Schemes Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of configuring multiple security schemes, including BearerAuth and ApiKeyAuth. ```typescript securitySchemes: { BearerAuth: { type: 'http', scheme: 'bearer', }, ApiKeyAuth: { type: 'apiKey', name: 'X-API-Key', in: 'header', }, } ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md Defines a GET endpoint with path and query parameters. The client fetches data using the specified URL and parameters. ```typescript export const appRouter = t.router({ sayHello: t.procedure .meta({ openapi: { method: 'GET', path: '/say-hello/{name}' /* 👈 */ } }) .input(z.object({ name: z.string() /* 👈 */, greeting: z.string() })) .output(z.object({ greeting: z.string() })) .query(({ input }) => { return { greeting: `${input.greeting} ${input.name}!` }; }); }); // Client const res = await fetch('http://localhost:3000/say-hello/Lily?greeting=Hello' /* 👈 */, { method: 'GET', }); const body = await res.json(); /* { greeting: 'Hello Lily!' } */ ``` -------------------------------- ### Implement Pagination for Products Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/getting-started.md This example demonstrates how to implement pagination for a tRPC procedure, defining input parameters for page number and limit, and structuring the output. ```typescript t.procedure .meta({ openapi: { method: 'GET', path: '/products', }, }) .input( z.object({ page: z.number().min(1).default(1), limit: z.number().min(1).max(100).default(20), }) ) .output( z.object({ items: z.array(z.object({ id: z.string() })), total: z.number(), page: z.number(), limit: z.number(), }) ) .query(({ input }) => { const offset = (input.page - 1) * input.limit; return { items: [], total: 0, page: input.page, limit: input.limit, }; }), ``` -------------------------------- ### GET Request with Combined Path and Query Parameters Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Defines a GET endpoint to retrieve a user's posts, using a path parameter for userId and optional query parameters for limit and sort. This shows how to combine different parameter types. ```typescript const router = t.router({ getUserPosts: t.procedure .meta({ openapi: { method: 'GET', path: '/users/{userId}/posts', }, }) .input(z.object({ userId: z.string(), // From path limit: z.number().optional(), // From query sort: z.enum(['date', 'title']).optional(), // From query })) .output(z.array(z.object({ id: z.string(), title: z.string(), }))) .query(({ input }) => { // input = { userId: '123', limit: 10, sort: 'date' } return []; }), }); // Client request: const response = await fetch('/api/users/123/posts?limit=10&sort=date'); ``` -------------------------------- ### Set up Cloudflare Workers Fetch Handler Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/getting-started.md This example demonstrates how to create an OpenAPI fetch handler for Cloudflare Workers. It configures the endpoint and the router. ```typescript import { createOpenApiFetchHandler } from 'trpc-to-openapi'; import { appRouter } from './router'; export default { async fetch(request: Request): Promise { return createOpenApiFetchHandler({ endpoint: '/api', router: appRouter, req: request, }); }, }; ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Defines a GET endpoint for listing users with optional query parameters for filtering and pagination. Inputs are passed via query parameters. ```typescript const router = t.router({ listUsers: t.procedure .meta({ openapi: { method: 'GET', path: '/users', }, }) .input(z.object({ limit: z.number().optional(), offset: z.number().optional(), search: z.string().optional(), })) .output(z.object({ users: z.array(z.object({ id: z.string(), name: z.string() })), total: z.number(), })) .query(({ input }) => { // input = { limit: 10, offset: 0, search: 'john' } return { users: [], total: 0, }; }), }); // Client request: const response = await fetch('/api/users?limit=10&offset=0&search=john'); const data = await response.json(); ``` -------------------------------- ### Log Generated OpenAPI Document to Console Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/getting-started.md This example demonstrates how to generate the OpenAPI document and then log its JSON representation to the console for inspection. ```typescript const doc = generateOpenApiDocument(appRouter, { title: 'My API', version: '1.0.0', baseUrl: 'http://localhost:3000', }); console.log(JSON.stringify(doc, null, 2)); ``` -------------------------------- ### Public Info Endpoint Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of configuring a public endpoint that does not require authentication. ```APIDOC ## GET /public/info ### Description Retrieves public information. ### Method GET ### Endpoint /public/info ### Security This endpoint is public and does not require authentication. ``` -------------------------------- ### Usage of getBody Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/utils.md Example of using `getBody` with a specified maximum body size limit. ```typescript const body = await getBody(req, 1_000_000); // 1MB limit ``` -------------------------------- ### Get Users Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/README.md Retrieves a list of users. Supports optional limit for the number of users to return. ```APIDOC ## GET /users ### Description Retrieves a list of users. Supports optional limit for the number of users to return. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of users to return. ### Response #### Success Response (200) - **Array of user objects** - Description of the user object structure is not provided in the source. ### Request Example ```http GET /api/users?limit=10 ``` ### Response Example ```json [ { "id": "123", "name": "John", "email": "john@example.com" } ] ``` ``` -------------------------------- ### Next.js API Route Setup with Context Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/adapters.md Configures a Next.js API route handler with a custom context creation function. ```typescript import { createOpenApiNextHandler } from 'trpc-to-openapi'; import { appRouter } from '../../server/router'; import { createContext } from '../../server/trpc'; export default createOpenApiNextHandler({ router: appRouter, createContext: async ({ req, res }) => { return createContext({ req, res }); }, }); ``` -------------------------------- ### Example tRPC Router with OpenAPI Metadata Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md Demonstrates how to add OpenAPI metadata (method and path) to tRPC procedures to enable RESTful endpoint generation. ```APIDOC ## Procedure: sayHello ### Description Exposes a tRPC procedure as a GET request to the '/say-hello' endpoint. It takes a 'name' string as input and returns a greeting. ### Method GET ### Endpoint /say-hello ### Parameters #### Query Parameters - **name** (string) - Required - The name to greet. ### Request Example ```json { "name": "string" } ``` ### Response #### Success Response (200) - **greeting** (string) - The greeting message. #### Response Example ```json { "greeting": "Hello string!" } --- ## Procedure: getStatus ### Description Exposes a tRPC procedure as a GET request to the '/status' endpoint. It returns the current status of the service. ### Method GET ### Endpoint /status ### Parameters No parameters required. ### Response #### Success Response (200) - **status** (string) - The status of the service. #### Response Example ```json { "status": "healthy" } ``` ``` -------------------------------- ### Generate OpenAPI Document - Basic Usage Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/generator.md Basic example of generating an OpenAPI document from a tRPC router. Ensure the router and necessary configuration options are provided. ```typescript import { generateOpenApiDocument } from 'trpc-to-openapi'; import { appRouter } from './router'; const openApiDocument = generateOpenApiDocument(appRouter, { title: 'My API', version: '1.0.0', baseUrl: 'http://localhost:3000', }); ``` -------------------------------- ### Use REST Endpoints (Client) Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/README.md Example of a client-side fetch request to a REST endpoint exposed by the tRPC router. ```typescript // Client code const response = await fetch('http://localhost:3000/api/users'); const users = await response.json(); ``` -------------------------------- ### Client Request with Custom Headers Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md When making a client request, include the documented custom headers. This example shows sending a POST request with specific GitHub headers. ```typescript const response = await fetch('/api/webhooks/github', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-github-event': 'push', 'x-github-signature': 'sha256=...', }, body: JSON.stringify({}), }); ``` -------------------------------- ### Express Server Setup with tRPC and OpenAPI Middleware Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/adapters.md Configures an Express server to handle both tRPC and OpenAPI requests using their respective middleware. ```typescript import { createExpressMiddleware } from '@trpc/server/adapters/express'; import { createOpenApiExpressMiddleware } from 'trpc-to-openapi'; import { appRouter } from './router'; const app = express(); // tRPC endpoints app.use('/api/trpc', createExpressMiddleware({ router: appRouter })); // OpenAPI REST endpoints app.use('/api', createOpenApiExpressMiddleware({ router: appRouter })); app.listen(3000); ``` -------------------------------- ### GET /users - List Users with Tags Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Retrieves a list of users. This endpoint is organized with tags for easier categorization and retrieval. ```APIDOC ## GET /users ### Description Retrieves a list of users. This endpoint is organized with tags for easier categorization and retrieval. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None specified in the source. #### Response Example None ### Tags - users - list ``` -------------------------------- ### Generate OpenAPI Document - Custom Security Schemes Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/generator.md Example of configuring custom security schemes like API keys or OAuth2. These schemes define how clients can authenticate with the API. ```typescript const openApiDocument = generateOpenApiDocument(appRouter, { title: 'My API', version: '1.0.0', baseUrl: 'http://localhost:3000', securitySchemes: { ApiKey: { type: 'apiKey', in: 'header', name: 'X-API-Key', }, OAuth2: { type: 'oauth2', flows: { authorizationCode: { authorizationUrl: 'https://auth.example.com/authorize', tokenUrl: 'https://auth.example.com/token', scopes: { 'read:users': 'Read user data', }, }, }, }, }, }); ``` -------------------------------- ### HTTP Handler for Express Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md Provides an example of creating an HTTP handler for an Express application using `createOpenApiHttpHandler` to serve OpenAPI-compatible REST endpoints for tRPC procedures. ```APIDOC ## Handler: createOpenApiHttpHandler (Node:HTTP Example) ### Description Creates an HTTP handler that can be used with Node.js's built-in `http` module to serve OpenAPI-compatible REST endpoints for your tRPC router. This handler translates incoming HTTP requests into tRPC calls. ### Parameters - **options** (object) - Required - Configuration options for the handler. - **router** (object) - Required - The tRPC router instance. ### Request Example ```typescript import http from 'http'; import { createOpenApiHttpHandler } from 'trpc-to-openapi'; import { appRouter } from '../appRouter'; const server = http.createServer(createOpenApiHttpHandler({ router: appRouter, })); server.listen(3000); ``` ### Response #### Success Response (200) The handler processes incoming HTTP requests and routes them to the appropriate tRPC procedure, returning the procedure's output. #### Response Example (for /say-hello) ```json { "greeting": "Hello OpenAPI!" } ``` #### Response Example (for /status) ```json { "status": "healthy" } ``` ``` -------------------------------- ### fastifyTRPCOpenApiPlugin Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/adapters.md Fastify plugin for handling OpenAPI requests. It registers OpenAPI handler as a Fastify plugin and creates routes for GET, POST, PATCH, PUT, DELETE methods. ```APIDOC ## fastifyTRPCOpenApiPlugin ### Description Registers OpenAPI handler as a Fastify plugin. Creates routes for GET, POST, PATCH, PUT, DELETE methods. ### Method POST, GET, PUT, PATCH, DELETE (handled by the underlying tRPC router) ### Endpoint Defined by `opts.basePath` and the request URL. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Handles JSON and form-encoded request bodies based on `Content-Type` header. #### Plugin Options (`opts`) - **fastify** (`FastifyInstance`) - Required - Fastify server instance. - **opts.router** (`OpenApiRouter`) - Required - The tRPC router. - **opts.basePath** (string) - Optional - Base path for all routes. Defaults to ''. - **opts.createContext** (Function) - Optional - Context factory function. - **opts.responseMeta** (Function) - Optional - Response customization function. - **opts.onError** (Function) - Optional - Error handler. - **opts.maxBodySize** (`number`) - Optional - Maximum body size in bytes. Defaults to 100000. - **done** (`(err?: Error) => void`) - Required - Callback to signal plugin completion. ### Request Example ```typescript import Fastify from 'fastify'; import { fastifyTRPCOpenApiPlugin } from 'trpc-to-openapi'; import { appRouter } from './router'; const fastify = Fastify(); await fastify.register(fastifyTRPCOpenApiPlugin, { router: appRouter, }); await fastify.listen({ port: 3000 }); ``` ### Response #### Success Response - **void** - Plugin modifies Fastify instance in place. #### Response Example (N/A - This is a plugin registration function) ``` -------------------------------- ### Rate Limit Exceeded Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/errors.md Demonstrates implementing rate limiting in middleware by checking client IP addresses and throwing a 'TOO_MANY_REQUESTS' TRPCError if the limit is exceeded. ```json { "message": "Too many requests", "code": "TOO_MANY_REQUESTS" } ``` ```typescript const handler = createOpenApiHttpHandler({ router: appRouter, createContext: async ({ req }) => { const ip = req.headers['x-forwarded-for']; if (await rateLimiter.isLimited(ip)) { throw new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'Rate limit exceeded', }); } return {}; }, }); ``` -------------------------------- ### Deprecated Get Old User Endpoint Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/configuration.md Example of marking an endpoint as deprecated, indicating it should no longer be used but still functions. ```APIDOC ## GET /users/old-endpoint ### Description Retrieves data from an old, deprecated endpoint. ### Method GET ### Endpoint /users/old-endpoint ### Deprecation This endpoint is deprecated and should not be used for new development. ``` -------------------------------- ### Documenting Custom Response Headers Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Specify custom response headers using `responseHeaders` with a Zod schema. This example documents rate limit and request ID headers. ```typescript .meta({ openapi: { method: 'GET', path: '/data', responseHeaders: z.object({ 'x-rate-limit-remaining': z.string(), 'x-request-id': z.string(), }), }, }) ``` -------------------------------- ### Documenting Custom Request Headers Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Define expected custom request headers using `requestHeaders` with a Zod schema. This example documents headers required for a GitHub webhook. ```typescript const router = t.router({ webhookHandler: t.procedure .meta({ openapi: { method: 'POST', path: '/webhooks/github', requestHeaders: z.object({ 'x-github-event': z.string(), 'x-github-signature': z.string(), }), }, }) .input(z.object({ data: z.any() })) .output(z.object({ received: z.boolean() })) .mutation(({ input }) => { return { received: true }; }), }); ``` -------------------------------- ### Dockerfile for tRPC to OpenAPI Deployment Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/getting-started.md This Dockerfile sets up a Node.js environment for deploying a tRPC to OpenAPI application. It installs dependencies, copies application code, and sets environment variables. ```dockerfile FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . ENV API_BASE_URL=https://api.example.com EXPOSE 3000 CMD ["node", "dist/index.js"] ``` -------------------------------- ### Set Up tRPC with OpenAPI Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/README.md Configure tRPC with OpenAPI metadata and define a sample procedure with input and output schemas. ```typescript import { initTRPC } from '@trpc/server'; import { OpenApiMeta } from 'trpc-to-openapi'; const t = initTRPC.meta().create(); export const appRouter = t.router({ sayHello: t.procedure .meta({ openapi: { method: 'GET', path: '/say-hello', }, }) .input(z.object({ name: z.string() })) .output(z.object({ greeting: z.string() })) .query(({ input }) => { return { greeting: `Hello ${input.name}!` }; }), }); ``` -------------------------------- ### Validation Error Response Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Provides an example of a validation error response, typically resulting in an HTTP 400 status code. ```json { "message": "Input validation failed", "code": "BAD_REQUEST", "issues": [ { "code": "invalid_type", "expected": "string", "received": "number", "path": ["email"], "message": "Expected string, received number" } ] } ``` -------------------------------- ### Protected GET Endpoint with Authorization Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md Configures a protected GET endpoint that requires authorization via the Authorization header. The server-side context is used to verify the user. ```typescript import { TRPCError, initTRPC } from '@trpc/server'; import { OpenApiMeta } from 'trpc-to-openapi'; type User = { id: string; name: string }; const users: User[] = [ { id: 'usr_123', name: 'Lily', }, ]; export type Context = { user: User | null }; export const createContext = async ({ req, res }): Promise => { let user: User | null = null; if (req.headers.authorization) { const userId = req.headers.authorization.split(' ')[1]; user = users.find((_user) => _user.id === userId); } return { user }; }; const t = initTRPC.context().meta().create(); export const appRouter = t.router({ sayHello: t.procedure .meta({ openapi: { method: 'GET', path: '/say-hello', protect: true /* 👈 */ } }) .input(z.void()) // no input expected .output(z.object({ greeting: z.string() })) .query(({ input, ctx }) => { if (!ctx.user) { throw new TRPCError({ message: 'User not found', code: 'UNAUTHORIZED' }); } return { greeting: `Hello ${ctx.user.name}!` }; }), }); // Client const res = await fetch('http://localhost:3000/say-hello', { method: 'GET', headers: { Authorization: 'Bearer usr_123' } /* 👈 */, }); const body = await res.json(); /* { greeting: 'Hello Lily!' } */ ``` -------------------------------- ### GET Request with Path Parameter Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Defines a GET endpoint to retrieve a single user by their ID, extracting the userId from the URL path. The input is validated as a UUID. ```typescript const router = t.router({ getUserById: t.procedure .meta({ openapi: { method: 'GET', path: '/users/{userId}', }, }) .input(z.object({ userId: z.string().uuid(), })) .output(z.object({ id: z.string(), name: z.string(), })) .query(({ input }) => { // input.userId is extracted from the URL path return { id: input.userId, name: 'John' }; }), }); // Client request: const response = await fetch('/api/users/550e8400-e29b-41d4-a716-446655440000'); const data = await response.json(); ``` -------------------------------- ### GET Request with Multiple Path Parameters Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Defines a GET endpoint to retrieve a user's post, extracting both userId and postId from the URL path. This demonstrates how to use multiple parameters in the path. ```typescript const router = t.router({ getUserPost: t.procedure .meta({ openapi: { method: 'GET', path: '/users/{userId}/posts/{postId}', }, }) .input(z.object({ userId: z.string(), postId: z.string(), })) .output(z.object({ id: z.string(), title: z.string(), })) .query(({ input }) => { return { id: input.postId, title: 'Hello' }; }), }); // Client request: const response = await fetch('/api/users/123/posts/456'); ``` -------------------------------- ### Get User Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Retrieves a specific user by their ID. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example { "id": "1", "name": "John", "email": "john@example.com" } ``` -------------------------------- ### GET /users/{userId} Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Retrieves a specific user by their unique ID, which is provided as a path parameter. ```APIDOC ## GET /users/{userId} ### Description Retrieves a specific user by their unique ID, which is provided as a path parameter. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the user. - **name** (string) - The name of the user. ``` -------------------------------- ### GET /users Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Retrieves a list of users. Supports filtering and pagination via query parameters. ```APIDOC ## GET /users ### Description Retrieves a list of users. Supports filtering and pagination via query parameters. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **limit** (number) - Optional - Maximum number of users to return. - **offset** (number) - Optional - Number of users to skip before starting to collect the result set. - **search** (string) - Optional - A search term to filter users by name. ### Response #### Success Response (200) - **users** (array) - An array of user objects, each containing an `id` (string) and `name` (string). - **total** (number) - The total number of users available matching the query. ``` -------------------------------- ### Create User Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/endpoints.md Creates a new user with the provided name and email. ```APIDOC ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example { "name": "John Doe", "email": "john.doe@example.com" } ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created user. - **name** (string) - The name of the created user. - **email** (string) - The email address of the created user. #### Response Example { "id": "1", "name": "John Doe", "email": "john.doe@example.com" } ``` -------------------------------- ### Perform Batch User Creation Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/getting-started.md This example demonstrates a tRPC procedure for batch creating users. It accepts an array of user objects, each with a name and email, and returns the count of created and failed users. ```typescript t.procedure .meta({ openapi: { method: 'POST', path: '/users/bulk-create', }, }) .input( z.object({ users: z.array( z.object({ name: z.string(), email: z.string().email(), }) ), }) ) .output( z.object({ created: z.number(), failed: z.number(), }) ) .mutation(({ input }) => { return { created: input.users.length, failed: 0 }; }), ``` -------------------------------- ### Increasing maxBodySize in Handler Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/errors.md Example of how to increase the `maxBodySize` limit for the OpenAPI HTTP handler on the server side. ```typescript // Server side createOpenApiHttpHandler({ router: appRouter, maxBodySize: 5_000_000, // 5MB }) ``` -------------------------------- ### Create Nuxt OpenAPI Handler Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/adapters.md Example of setting up the OpenAPI handler for Nuxt server routes using the `[...trpc].ts` pattern. Ensure the tRPC router is imported correctly. ```typescript // server/api/[...trpc].ts import { createOpenApiNuxtHandler } from 'trpc-to-openapi'; import { appRouter } from '~/server/api/routers'; export default createOpenApiNuxtHandler({ router: appRouter }); ``` -------------------------------- ### getRequestSignal Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/api-reference/utils.md Gets an AbortSignal for request cancellation handling. This is useful for managing long-running requests or implementing timeouts. ```APIDOC ## getRequestSignal ### Description Gets an AbortSignal for request cancellation handling. ### Method Signature ```typescript export const getRequestSignal = ( req: NodeHTTPRequest | Request, res: NodeHTTPResponse, maxBodySize?: number, ): AbortSignal ``` ### Parameters #### Path Parameters - **req** (NodeHTTPRequest | Request) - Required - HTTP request object - **res** (NodeHTTPResponse) - Required - HTTP response object - **maxBodySize** (number) - Optional - Optional body size limit ### Return Type `AbortSignal` — Signal for request cancellation ### Usage Example ```typescript const signal = getRequestSignal(req, res, 100000); const controller = new AbortController(); ``` ``` -------------------------------- ### Missing Required Path Parameter Example Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/errors.md Demonstrates how to correctly include path parameters in URLs to avoid 'Missing Required Path Parameter' errors. Ensure the parameter is present in both the route definition and the fetch request. ```json { "message": "Input validation failed", "code": "BAD_REQUEST", "issues": [ { "code": "invalid_type", "expected": "string", "received": "undefined", "path": ["id"], "message": "Required" } ] } ``` ```typescript // Route definition .meta({ openapi: { method: 'GET', path: '/users/{id}' } }) // ✓ Correct - id in path const response = await fetch('/api/users/123'); // ✗ Incorrect - missing id const response = await fetch('/api/users'); ``` -------------------------------- ### Get User by ID Source: https://github.com/mcampa/trpc-to-openapi/blob/master/_autodocs/README.md Retrieves a specific user by their ID. Supports optional query parameters for filtering. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by their ID. Supports optional query parameters for filtering. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. #### Query Parameters - **active** (boolean) - Optional - Filters users by their active status. ### Response #### Success Response (200) - **userSchema** (object) - The user object matching the provided ID. ### Request Example ```http GET /api/users/123?active=true ``` ### Response Example ```json { "id": "123", "name": "John", "email": "john@example.com" } ``` ``` -------------------------------- ### POST /say-hello/{name} Source: https://github.com/mcampa/trpc-to-openapi/blob/master/README.md A POST procedure that takes a name from the path and a greeting from the request body to return a personalized greeting. ```APIDOC ## POST /say-hello/{name} ### Description A POST procedure that takes a name from the path and a greeting from the request body to return a personalized greeting. ### Method POST ### Endpoint /say-hello/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name to greet. #### Request Body - **greeting** (string) - Required - The greeting to use. ### Request Example ```http POST http://localhost:3000/say-hello/Lily Content-Type: application/json { "greeting": "Hello" } ``` ### Response #### Success Response (200) - **greeting** (string) - The personalized greeting. #### Response Example ```json { "greeting": "Hello Lily!" } ``` ```