question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[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&param2=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

https://github.com/trpc/trpc/discussions/271

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:41
  • Comments:10 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
jlalmescommented, Jun 10, 2022

For tRPC support of public-facing APIs, please use trpc-openapi: https://github.com/jlalmes/trpc-openapi

3reactions
mmkalcommented, Aug 20, 2021

For 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 of Record<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):

app.use((req, _res, next) => {
  // stupid middleware that, on localhost, rewrites `/foo?.x=abc&.y=def` to `/foo?input=${encodeURIComponent(JSON.stringify({x: 'abc', y: 'def'}))}` which is much harder to construct from postman!
  if (req.hostname !== 'localhost' || req.headers['user-agent']?.match(/Mozilla/)) {
    next()
    return
  }

  let input: any
  Object.keys(req.query)
    .filter(k => k.startsWith('.'))
    .forEach(k => {
      input ||= {}
      input[k.replace('.', '')] = req.query[k]
    })

  if (input) {
    req.query.input = JSON.stringify(input)
  }

  next()
})
Read more comments on GitHub >

github_iconTop Results From Across the Web

Introduction - tRPC
tRPC allows you to easily build & consume fully typesafe APIs without schemas or code generation. As TypeScript and static typing increasingly becomes...
Read more >
Build end-to-end typesafe APIs with tRPC - DEV Community ‍ ‍
tRPC is a very light library which lets you build fully typesafe APIs without the need of schemas or code generation. It allows...
Read more >
Chris Bautista: Making typesafe APIs easy with tRPC - YouTube
Get Trash Dev's take on how to leverage the full power of modern TypeScript with tRPC with Chris Bautista, Senior Software Engineer at ......
Read more >
Build a full-stack TypeScript app using tRPC and React
Build a simple, full-stack TypeScript app using tRPC that will be type-safe when it comes to the code and across the API boundary....
Read more >
Building Typesafe APIs with tRPC & TypeScript
tRPC exist to provide type safety end to end, ensuring the contract for the API boundary can be trusted by default. Join me...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found