tRPC
Install
npm install trpc-openapi
Setup
Mark tRPC procedures with .meta({ openapi: ... }) to include them in the spec:
// router.ts
import { initTRPC } from '@trpc/server'
import { OpenApiMeta } from 'trpc-openapi'
import { z } from 'zod'
const t = initTRPC.meta<OpenApiMeta>().create()
export const appRouter = t.router({
getItem: t.procedure
.meta({
openapi: {
method: 'GET',
path: '/items/{id}',
summary: 'Get a single item',
tags: ['items'],
},
})
.input(z.object({ id: z.number() }))
.output(z.object({ id: z.number(), name: z.string() }))
.query(({ input }) => {
return { id: input.id, name: 'Widget' }
}),
})
export type AppRouter = typeof appRouter
Expose the spec
Generate and serve the OpenAPI document from your Express or Next.js server:
// server.ts
import express from 'express'
import { createExpressMiddleware } from '@trpc/server/adapters/express'
import { generateOpenApiDocument } from 'trpc-openapi'
import { appRouter } from './router'
const app = express()
// Generate the OpenAPI spec
const openApiDocument = generateOpenApiDocument(appRouter, {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://your-api.example.com',
})
// Expose the spec
app.get('/openapi.json', (req, res) => {
res.json(openApiDocument)
})
// Mount tRPC REST handler
app.use('/api', createExpressMiddleware({ router: appRouter }))
app.listen(3000)
The spec is available at:
http://localhost:3000/openapi.json
Make it publicly accessible
Deploy your app or use a tunnel for local testing:
ngrok http 3000
# then use: https://<random>.ngrok.io/openapi.json
Verify
Visit /openapi.json in your browser. You should see a valid OpenAPI 3.x JSON document.
Paste this URL into Automiel’s import step.