ts-rest

RPC-like client, contract, and server implementation for a pure REST API

README

ts-rest



RPC-like client and server helpers for a magical end to end typed experience


Introduction


ts-rest offers a simple way to define a contract for your API, which can be both consumed and implemented by your application, giving you end to end type safety without the hassle or code generation.

Features


- End to end type safety 🛟
- RPC-like client side interface 📡
- Well-tested and production ready ✅
- No Code Generation 🏃‍♀️
- Zod support for runtime type checks 👮‍♀️
- Full optional OpenAPI integration 📝

Super Simple Example


Easily define your API contract somewhere shared

  1. ```typescript
  2. const contract = c.contract({
  3.   getPosts: {
  4.     method: 'GET',
  5.     path: '/posts',
  6.     query: z.object({
  7.       skip: z.number(),
  8.       take: z.number(),
  9.     }), // <-- Zod schema
  10.     responses: {
  11.       200: c.response<Post[]>(), // <-- OR normal TS types
  12.     },
  13.   },
  14. });
  15. ```

Fulfil the contract on your sever, with a type-safe router:

  1. ```typescript
  2. const router = s.router(contract, {
  3.   getPost: async ({ params: { id } }) => {
  4.     return {
  5.       status: 200,
  6.       body: prisma.post.findUnique({ where: { id } }),
  7.     };
  8.   },
  9. });
  10. ```

Consume the api on the client with a RPC-like interface:

  1. ```typescript
  2. const result = await client.getPosts({
  3.   query: { skip: 0, take: 10 },
  4.   // ^-- Fully typed!
  5. });
  6. ```

Quickstart


Install the core package

  1. ```bash
  2. yarn add @ts-rest/core
  3. # Optional react-query integration
  4. yarn add @ts-rest/react-query
  5. # Pick your backend
  6. yarn add @ts-rest/nest @ts-rest/express
  7. # For automatic server OpenAPI gen
  8. yarn add @ts-rest/open-api
  9. ```

Create a contract, implement it on your server then consume it in your client. Incrementally adopt, trial it with your team, then get shipping faster.

👉 Read more on the official Quickstart Guide👈


Star History


Star History Chart

Contributors ✨


Thanks goes to these wonderful people (emoji key):

Youssef Gaber
Youssef Gaber

💻 🤔 ⚠️
Per Hermansson
Per Hermansson

📖 💻
Grégory Houllier
Grégory Houllier

📖
Michael Angelo
Michael Angelo

📖
Pieter Venter
Pieter Venter

📖
Rifaldhi AW
Rifaldhi AW

📖



This project follows the all-contributors specification. Contributions of any kind welcome!

  <a
    href="https://vercel.com/?utm_source=ts-rest&utm_campaign=oss"
    target="_blank"
    rel="noreferrer"
  >
    <img
      src="https://ts-rest.com/img/powered-by-vercel.svg"
      alt="Powered by Vercel"
      height="40"
    />