Theo's Typesafe CultTTC
Theo's Typesafe Cult2y ago
5 replies
crbon

How can I configure tRPC to function as a REST API (single-route)?

I'm new to tRPC and not sure why this produces an error when an external POST request is sent to the /api/trpc/post.createExternal route.

I'm trying to expose a tRPC route / procedure, so that an external service can POST to it

Example POST
curl -X POST -H "Content-Type: application/json" -d '{"message": "please help"}' http://localhost:3000/api/trpc/post.createExternal


Error on server
:x: tRPC failed on post.createExternal: [
  {
    "code": "invalid_type",
    "expected": "object",
    "received": "undefined",
    "path": [],
    "message": "Required"
  }
]


Code
post.ts in src/server/api/routers (default create t3 app)
import { z } from "zod";

import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";
import { posts } from "~/server/db/schema";

export const postRouter = createTRPCRouter({
  createExternal: publicProcedure
    .input(z.object({ message: z.string().min(1) }))
    .mutation(async ({ ctx, input }) => {
      await ctx.db.insert(posts).values({
        message: input.message,
      });
    }),
});


As a side note, I did see https://github.com/jlalmes/trpc-openapi if I want something quick and dirty, should the create-t3-app structure be able to handle it?

Also, jlalmes/trpc-openapi doesn't seem to be supported in NextJS 14 with app router

Help would be much appreciated 🙂
Was this page helpful?