API Methods
Use HTTP method helpers for schema-validated JSON requests.
The api object exposes method-bound $fetch helpers.
Use it when the response should be validated and the HTTP method is known up front.
The schema argument always validates the response body.
It does not validate json or body request payloads.
Methods
| Method | HTTP method |
|---|---|
api.get | GET |
api.post | POST |
api.put | PUT |
api.patch | PATCH |
api.delete | DELETE |
Each helper has the same overloads and error behavior as $fetch, but injects its HTTP method for you.
Read Data
import { api } from "@zap-studio/fetch";
import { z } from "zod";
const UserSchema = z.object({
id: z.string(),
name: z.string(),
});
const user = await api.get("/api/users/1", UserSchema);Send JSON
Use json for JSON request bodies.
const CreateUserResponseSchema = z.object({
id: z.string(),
name: z.string(),
});
const user = await api.post("/api/users", CreateUserResponseSchema, {
json: {
name: "Ada",
},
});CreateUserResponseSchema validates the response from the server.
The json object is only the outgoing request body.
The json option is stringified and gets Content-Type: application/json when no content type is already set.
Use Native Body
Use native body when sending FormData, Blob, ReadableStream, or an already-serialized payload.
const formData = new FormData();
formData.set("avatar", file);
const profile = await api.patch("/api/profile", ProfileSchema, {
body: formData,
});body and json cannot be used together.
Query Params
const page = await api.get("/api/users", UserListSchema, {
searchParams: {
page: "1",
limit: "20",
},
});Non-throw Modes
HTTP errors and validation issues throw by default. You can disable either behavior per request.
const response = await api.get("/api/users/missing", UserSchema, {
throwOnFetchError: false,
});
const result = await api.get("/api/users/1", UserSchema, {
throwOnValidationError: false,
});When throwOnValidationError is false, the return value is a Standard Schema result object.
Raw Responses
The method helpers can be called without a schema because they mirror $fetch.
For clarity, prefer $fetch directly when raw response handling is the main goal.
Last updated on