Repository navigation
Closed
Labels
Description
Note: I do not want to have this as part of the library itself, but an example would be good
Overview
With the addition of output parser (#1699), we should now have all the pieces to automatically create an OpenAPI-compliant endpoint
Some rough ideas:
- Create a new endpoint
/api/openapi.yml.tsthat can use the method earlier to generate a schema - Create a catch-all
/api/openapi/[...params].tsthat can dynamically read and call tRPC queries - https://github.com/StefanTerdell/zod-to-json-schema#readme can be useful
- Example how to create JSON schema from tRPC routes: https://gist.github.com/KATT/993fbcbaf123f08098a154631e5af68c
- This package can be of good inspo for the openapi output https://github.com/RobinTail/express-zod-api
A starting point for the api handler:
import { ProcedureType, TRPCError } from '@trpc/server';
import { NextApiRequest, NextApiResponse } from 'next';
import { createContext } from '~/server/context';
import { appRouter } from '~/server/routers/_app';
export default async function swag(req: NextApiRequest, res: NextApiResponse) {
const { params, ...queryParams } = req.query;
if (req.method !== 'POST' && req.method !== 'GET') {
res.status(405).json({
message: 'Invalid method',
});
return;
}
const path = Array.isArray(params) ? params.join('/') : params;
const ctx = await createContext({ req, res });
const type: ProcedureType = req.method === 'POST' ? 'mutation' : 'query';
try {
const caller = appRouter.createCaller({ ctx });
const fn = caller[type] as any;
const result = await fn(path, queryParams);
res.json(result);
return;
} catch (error) {
if (!(error instanceof TRPCError)) {
res.status(500).json({
message: 'Something went wrong',
});
return;
}
const formatted = appRouter.getErrorShape({
error,
path,
ctx,
input: params,
type,
});
// TODO: use https://github.com/trpc/trpc/blob/main/packages/server/src/http/internals/getHTTPStatusCode.ts#L55-L59
// Feel free to make them publicly exposed
const status = 500;
res.status(500).json(formatted);
}
}Reacted by James Berry, Amir Hossein Hashemi, Sachin Raja, lukemt, Boubouh Karim, Timothy Cole, Misha Kaletsky, Pierre Teo, Juan Alvarado, Lori Karikari and 2 more
Activity
LouisHaftmann commentedon Apr 6, 2022
Would this be used to generate mutation/query routes that comply to the OpenAPI specification or just to generate a swagger schema?
KATT commentedon Apr 6, 2022
Ideally both. We should have all the information needed to create a new api handler and automatically expose a REST-esque version of trpc
KATT commentedon Apr 6, 2022
With #1736 we should be able to give hints too to remap paths or to say that something should be a PUT/PATCH/DELETE method
jlalmes commentedon Apr 7, 2022
Proposal tRPC <> OpenAPI
Sharing my thoughts regarding OpenAPI support.
@trpc/openapi01. Router
We will export a
openApiRouter()function that will return anOpenApiCompliantRouterthat extendsRouter.OpenApiCompliantRouterwill omit the.subscription()method.OpenApiCompliantRouterwill ensure theinputof.query()method extendsRecord<string, string>(Router methods input type narrowing #1743).OpenApiCompliantRouterwill ensuremetaextendsRecord<string, any> & { openapi?: { method?: ..., description?: string, etc... } }(feat(server): route metadata #1736).02. Generator
We will export a
createOpenApiSchema()function that will accept aOpenApiCompliantRouterand return anOpenAPIV3.Document(https://www.npmjs.com/package/openapi-types). This will generate the parameters(query)/requestBody(mutation) schema and responseBody schema using theinputParserandoutputParservalidators defined on the procedure. The generated OpenAPI spec will usemeta.openapimetadata where applicable.3.0.0.zodparsers will be supported (https://www.npmjs.com/package/zod-to-json-schema).outputis specified, it will default tonull.meta.openapi.methodis specified query methods will default toGET, mutation methods will default toPOST.03. Adapters
We will export
createHTTPOpenApiHandler(),createHTTPOpenApiServer(),createExpressOpenApiMiddleware(),createNextOpenApiHandler(),fastifyTRPCOpenApiPlugin()functions. These should be drop-in replacements for their@trpc/servercounterparts, except for the following changes:OpenApiCompliantRouter.Example usage
Happy to hear any feedback!
KATT commentedon Apr 7, 2022
I am not sure if I am ready to commit to maintaining a new sub-library for a use-case that I don't have use for myself. I am all for having the necessary hooks to enable this, but I don't know if I want to make an official
@trpc/openapi-package.How I would see this working:
createOpenApiSchemaas suggested above could be a completely standalone package or just a reference project to start with.meta.openapiand ignore the rest - it's pretty common to only have some methods publicly exposed/public/,public/schema) are handled in said helperLouisHaftmann commentedon Apr 7, 2022
A plugin system (#1742) would probably be more usefull because it allows users to create all kinds of plugins (including an openapi plugin)
Brian-McBride commentedon Apr 12, 2022
The main reason I would like to have an OpenAPI spec generator is just to have an easier integration with all the various cloud-based API Gateways. Nearly all of them have the step of defining the API Proxy with an OpenAPI schema.
jlalmes commentedon Apr 12, 2022
@Brian-McBride I plan to publish my
trpc-openapiwork promptly after tRPCv10is released.mwarger commentedon May 23, 2022
This would be fantastic, as I think it could also be used with this: https://github.com/api-platform/admin
jlalmes commentedon May 23, 2022
You can try out the
alpharelease oftrpc-openapithat is compatible with the current stable version of@trpc/server@9. Bear in mind that the API may change before official release.https://www.npmjs.com/package/trpc-openapi
Brian-McBride commentedon May 24, 2022
@jlalmes Would it work with the Fastify adaptor?
jlalmes commentedon May 24, 2022
Absolutely! We would just need to add a
fastifyOpenApiRequestHandler&fastifyTRPCOpenApiPluginadapter here: https://github.com/jlalmes/trpc-openapi/tree/v0.1.0/src/adapters. I am not familiar with Fastify so can't be too much help, but happy to assist where possible if you want to open a PR.Here's a good starting point: https://github.com/trpc/trpc/tree/main/packages/server/src/adapters/fastify
jlalmes commentedon Jun 10, 2022
For tRPC to OpenAPI compliant endpoints & schema generator, please use
trpc-openapi: https://github.com/jlalmes/trpc-openapigithub-actions commentedon Oct 4, 2022
This issue has been locked because it had no new activity for 14 days. If you are running into a similar issue, please create a new issue. Thank you.