[RFC] Using tRPC for public-facing APIs (OpenAPI/Swagger/etc)
See original GitHub issue👉👉👉👉 Update: For tRPC support of public-facing APIs, please use trpc-openapi
: https://github.com/jlalmes/trpc-openapi
It would be nice if there was a way to easily expose tRPC-endpoints as REST (or GraphQL) for people who want to use tRPC for a public API and is a bit more intuitive. Could potentially drive adoption a bit more.
See #752 for an example of what gets confusing.
… been thinking a bit about it, but it’s not obvious how it could work.
Maybe doing some sort of API-builder… or something where you define your API schema which then does automatic mapping to tRPC.
I’m also thinking that it might not be needed - JSON.stringify(encodeURIComponent(x))
is hard when you toy around with manual API-requests, but it’s not that bad when you’re actually working with the API, as it’s only needed once.
Current implementation, HTTP Methods <-> Type mapping
HTTP Method | Mapping | Notes |
---|---|---|
GET |
.query() |
Input JSON-stringified in query param. e.g. ?input=${JSON.stringify(encodeURIComponent(input)) |
POST |
.mutation() |
Input as post body. |
Considerations with OpenAPI
- Resources are usually
/{resource}/{id}?param1=x¶m2=y
-style - tRPC is [currently] with{resource}?input=JSON.stringify(encodeURIComponent(input))
-style - JSON-RPC based response shape might not be the ideal response shape for OpenAPI
- An output schema usually have a
$ref
-schema which would be possible to do automatically / first feature people would request is to make different paths request the same input type - Actually using zod or any other validation on a resolver’s
output
would slow down API outputs.
Related
Issue Analytics
- State:
- Created 2 years ago
- Reactions:41
- Comments:10 (2 by maintainers)
Top GitHub Comments
For tRPC support of public-facing APIs, please use
trpc-openapi
: https://github.com/jlalmes/trpc-openapiFor local development I’ve played around with an express middleware that just mutates
req.query
to make it more “traditional”. It only really works for very simple input schemas that are extensions ofRecord<string, string>
, and there may be a whole host of edge-cases, but it’s been handy for using postman etc.We are using trpc (I feel I should re-iterate - it is so awesome) for our whole API and we likely will have use cases in the pipeline where no-code marketing tools (example), used by non-engineers, need to hit an API of ours using liquid templating to create request urls etc. I think at that point it will be hard to do
encodeURIComponent(JSON.stringify({ abc: 'foo' }))
, although maybe not impossible. It might be pushing the limits of what liquid can do.Here’s the very dumb middleware that converts regular query params into TRPC-friendly format (haven’t considered batching or anything like that since this is just for localhost prototyping):