tea
is a lightweight, type-safe API client builder for TypeScript, powered by Zod for runtime validation. It provides a simple way to define your API schema and create a fully typed client for making HTTP requests.
npm i @bethel-nz/tea
bun add @bethel-nz/tea
yarn add @bethel-nz/tea
- Define your API schema using Zod for both request and response validation
- Fully typed responses and request parameters
- Support for path parameters, query parameters, and request bodies
- Automatic parsing of JSON responses
- Custom headers and request options
- Caching with query invalidation
First, define your API schema using Zod schemas:
import { z } from 'zod';
import { createTea } from '@bethel-nz/tea/core';
import type { TeaSchema } from '@bethel-nz/tea/schema';
const userSchema = {
getUsers: {
method: 'GET',
path: '/users',
schema: {
response: z.array(
z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
})
),
query: z.object({
page: z.number().optional(),
limit: z.number().optional(),
}),
},
},
//...other schema
} satisfies TeaSchema;
Create your API client using createTea
:
const tea = createTea('https://jsonplaceholder.typicode.com', userSchema);
Now you can make fully typed requests to your API:
async function basicExample() {
try {
// Get all users with query params
const users = await tea('getUsers', {
query: { page: 1, limit: 5 },
});
console.log('Users:', users);
// Get single user with path params
const user = await tea('getUser', {
params: { id: '1' }, // Type-safe params
});
console.log('Single user:', user);
// Create user with body
const newUser = await tea('createUser', {
body: {
// Type-safe body
name: 'John Doe',
email: '[email protected]',
},
});
console.log('Created user:', newUser);
} catch (error) {
console.error('Error:', error);
}
}
see Examples Here
Tea provides a balance between simplicity and type safety. It allows you to:
- Define your API schema in one place
- Get full type inference for requests and responses
- Validate responses at runtime using Zod
- Keep your API client code clean and concise
It's a simple API for building a type and runtime-safe fetcher function using Zod schemas.
- Zod Fetch
- Typesafe Fetch
- Zod
- Ky - a more feature-rich alternative but isn't typed
MIT