Not to be confused with trpc-openapi.
The openapi-trpc
package is a tool to generate OpenAPI v3 spec from a tRPC router, adhering to tRPC’s HTTP RPC Specification. This lets you take an existing tRPC router, and generate an OpenAPI spec from it. From there, you can use the spec to generate a client, or use it to document your API.
When initializing tRPC with initTRPC
, add .meta<OperationMeta>()
to the chain:
import { initTRPC } from '@trpc/server'
import { OperationMeta } from 'openapi-trpc'
const t = initTRPC.meta<OperationMeta>().create()
Whenever you want to generate an OpenAPI spec, call generateOpenAPIDocumentFromTRPCRouter()
:
import { generateOpenAPIDocumentFromTRPCRouter } from 'openapi-trpc'
import { appRouter } from './router'
const doc = generateOpenAPIDocumentFromTRPCRouter(appRouter, {
pathPrefix: '/trpc',
})
Inside your procedures, you can add metadata to the OpenAPI spec by adding .meta()
to the chain. If the meta object contains the deprecated
, description
, externalDocs
, summary
, or tags
keys, they will be added to the OpenAPI spec.
In your Zod schema (yes, you must use Zod, as other schema libraries are not supported), you can use .describe()
to add a description to each field, and they will be added to the schema in the OpenAPI spec (thanks to zod-to-json-schema).
t.procedure
.meta({ summary: '…', description: '…' })
.input(
z.object({
id: z.number().describe('…'),
/* ... */
}),
)
.query(() => {
/* … */
})
You can then use the doc
to generate API documentation or a client.
More advanced usage:
-
You can use your own type for the meta object, to add extra metadata to the tRPC procedure. It is recommended that the type should extend
OperationMeta
. -
You can also provide
processOperation
to customize the OpenAPI spec on a per-operation (i.e. tRPC procedure) basis. This allows adding more metadata to the spec, such assecurity
(for authentication) orservers
. The function is called with the operation’s OpenAPI spec, and the tRPC procedure’s metadata. It may mutate the spec, or return a new one. For more information, see the tests.
openapi-trpc
(this library):
- Generates an OpenAPI v3 document according to the existing HTTP RPC Specification. It is not RESTful, but matches how a normal tRPC client talks to the server. You API looks like this:
GET /trpc/sayHello?input={"name":"James"}
. - Does not require adding any extra request handlers to your app.
- Unproven code, full of hacks, PoC-quality code. However the scope of the library is very small and it works well enough for me.
- Generates RESTful endpoints. You can customize the path and HTTP method of each endpoint. You get nice-looking RESTful APIs like
GET /say-hello?name=James
. This requires adding an extra request handler to your app which comes with its own limitations. - Works with Express, Next.js, Serverless, and Node:HTTP servers. No adapters for Fetch, Fastify, Nuxt, or Workers yet.
- Well-tested, well-documented and well-maintained.