Getting Started
Install fetch and make your first schema-validated HTTP request.
Installation
npm install @zap-studio/fetchyarn add @zap-studio/fetchpnpm add @zap-studio/fetchbun add @zap-studio/fetchdeno add jsr:@zap-studio/fetchQuick Example
import { api } from "@zap-studio/fetch";
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
});
const user = await api.get("https://api.example.com/users/1", UserSchema);
console.log(user.email);The schema argument validates the response body returned by the server.
Send JSON
Use json when the package should serialize a JSON body and set Content-Type: application/json when missing.
const created = await api.post("/api/users", UserSchema, {
json: {
name: "Ada",
email: "ada@example.com",
},
});In this example, UserSchema validates the response from /api/users.
The json object is the outgoing request body; it is not validated by UserSchema.
json and native body are mutually exclusive.
Raw Responses
Use $fetch without a schema when you need the raw Response.
import { $fetch } from "@zap-studio/fetch";
const response = await $fetch("/api/health");
console.log(response.status);Configured Client
Use createFetch when many requests share a base URL, headers, or query params.
import { createFetch } from "@zap-studio/fetch";
const { api } = createFetch({
baseURL: "https://api.example.com",
headers: {
Authorization: `Bearer ${token}`,
},
});
const user = await api.get("/users/1", UserSchema);Edit on GitHub
Last updated on