Installation#
Install what-the-fetch using your preferred package manager:
You'll also need a schema validation library that implements Standard Schema:
TypeScript Support
what-the-fetch is written in TypeScript and includes type definitions out of the
box. No need to install separate @types packages!
Basic Usage#
Importing#
Quick Examples#
Here are some common use cases to get you started:
Simple GET Request#
Define a schema and make a type-safe request:
With Query Parameters#
Add query parameters to your request:
POST Request with Body#
Send data in the request body:
Using HTTP Methods#
what-the-fetch automatically infers HTTP methods, but you can also specify them explicitly using the @method prefix:
Method Inference
The @method prefix is optional. Without it, what-the-fetch automatically uses POST for requests with a body and GET for requests without a body. Both /users/:id and @get/users/:id are equivalent and result in the same GET request.
Step-by-Step Tutorial#
Let's build a complete type-safe API client using what-the-fetch:
Define Your API Schema#
Start by defining schemas for all your API endpoints:
Create the Fetch Function#
Use createFetch to build your typed API client:
You can also provide shared options that apply to all requests:
Make Type-Safe Requests#
Now you can make fully typed requests with autocomplete:
Add Custom Headers (Optional)#
You can pass custom headers using the third parameter:
Common Patterns#
Using Different Schema Libraries#
what-the-fetch works with any Standard Schema implementation:
Combining Path and Query Parameters#
Mix path parameters with query parameters:
Custom Request Configuration#
Pass additional fetch options as the third parameter:
Reusing the Same Fetch Function#
Create one fetch function and reuse it throughout your application:
Shared Configuration#
Use shared configuration to set common options for all requests:
Schema Validation Benefits#
what-the-fetch validates both requests and responses automatically:
Parameterized Paths Require Schema
If your path contains parameters (e.g., /users/:id), you must define a params schema. The library will throw an error at runtime if you attempt to use a parameterized path without a params schema.
Error Handling#
what-the-fetch provides clear error messages for both validation and HTTP errors:
Handling HTTP Errors#
what-the-fetch automatically throws on non-2xx status codes:
Handling Validation Errors#
Schema validation errors are thrown when response doesn't match schema:
Type Safety
With TypeScript, most parameter errors are caught at compile time, preventing runtime errors before they happen!