-
Notifications
You must be signed in to change notification settings - Fork 3
getting‐started‐fetch
@zimic/fetch
is a minimal (1 kB minified and gzipped), zero-dependency, and type-safe
fetch
-like API client.
- If you are on the client side:
- Any relatively modern browser
- If you are on the server side:
- Node >= 18.0.0
- TypeScript >= 4.8
-
JavaScript >= ES6
-
@zimic/fetch
is fully functional on JavaScript, but consider using TypeScript for improved type safety and editor support.
-
If you are using TypeScript, we recommend enabling strict
in your tsconfig.json
:
{
"compilerOptions": {
"strict": true
}
}
@zimic/fetch
is available on npm.
Manager | Command |
---|---|
npm | npm install @zimic/http @zimic/fetch --save-dev |
yarn | yarn add @zimic/http @zimic/fetch --dev |
pnpm | pnpm add @zimic/http @zimic/fetch --dev |
We also canary releases under the tag canary
, containing the latest features and bug fixes:
Manager | Command |
---|---|
npm | npm install @zimic/http@canary @zimic/fetch@canary --save-dev |
yarn | yarn add @zimic/http@canary @zimic/fetch@canary --dev |
pnpm | pnpm add @zimic/http@canary @zimic/fetch@canary --dev |
-
Declare your HTTP schema using
@zimic/http
:import { type HttpSchema } from '@zimic/http'; interface User { username: string; } interface RequestError { code: string; message: string; } type Schema = HttpSchema<{ '/users': { POST: { request: { body: User }; response: { 201: { body: User }; 400: { body: RequestError }; 409: { body: RequestError }; }; }; GET: { request: { searchParams: { query?: string; limit?: `${number}` }; }; response: { 200: { body: User[] }; 400: { body: RequestError }; 401: { body: RequestError }; }; }; }; '/users/:userId': { PATCH: { request: { headers: { authorization: string }; body: Partial<User>; }; response: { 204: {}; 400: { body: RequestError }; }; }; }; }>;
You can also use
zimic-http typegen
to automatically generate types for your HTTP schema. -
Create your fetch instance:
import { createFetch } from '@zimic/fetch'; const fetch = createFetch<Schema>({ baseURL: 'http://localhost:3000', });
-
Enjoy requests and responses typed by default!
const response = await fetch('/users', { method: 'GET', searchParams: { query: 'u', limit: '10' }, }); if (response.status === 404) { return null; // User not found } if (!response.ok) { throw response.error; } const users = await response.json(); return users; // User[]
-
Check out
@zimic/interceptor
if you'd like to intercept and mock HTTP requests during development or in your tests:-
@zimic/interceptor
provides a flexible and type-safe way to intercept and mock HTTP requests. Use your HTTP schema to type your interceptors and create realistic mocks in development and testing.
-
-
Take a look at our examples.
-
Check out the API reference:
-
View our guides on common use cases:
© Zimic
Docs |
Issues | Examples |
Roadmap
Help us improve these docs!
Report an issue or
edit on GitHub.