Skip to main content

Basic Usage

Learn how to use the API client for making type-safe requests.

Creating a Client

Use createApiClient to create a client instance:

import { createApiClient } from "@alt-stack/http-client-fetch";
import { Request, Response } from "./generated-types.js";

const client = createApiClient({
baseUrl: "http://localhost:3000",
Request,
Response,
headers: {
Authorization: "Bearer token",
},
});

Making Requests

The client provides methods for different HTTP methods:

GET Requests

const result = await client.get("/users/{id}", {
params: { id: "123" },
query: { include: "profile" },
});

POST Requests

const result = await client.post("/users", {
body: {
name: "Alice",
email: "alice@example.com",
},
});

PUT Requests

const result = await client.put("/users/{id}", {
params: { id: "123" },
body: { name: "Alice Updated", email: "alice@example.com" },
});

PATCH Requests

const result = await client.patch("/users/{id}", {
params: { id: "123" },
body: { email: "newemail@example.com" },
});

DELETE Requests

const result = await client.delete("/users/{id}", {
params: { id: "123" },
});

Handling Responses

All methods return a result object that can be either a success or error:

const result = await client.get("/users/{id}", {
params: { id: "123" },
});

if (result.success) {
// Type-safe access to response body
console.log(result.body);
console.log(result.code); // Status code string, e.g., "200"
console.log(result.raw); // Raw Response object for advanced use
} else {
// Handle error - check if it's a defined error or unexpected
if (typeof result.code === "string") {
// Server returned a defined error response
console.error(result.code, result.error);
} else {
// Unexpected error (network, validation, etc.)
console.error(result.error);
}
}

Request Options

You can pass additional options to requests:

const result = await client.get("/users/{id}", {
params: { id: "123" },
headers: {
"X-Custom-Header": "value",
},
timeout: 5000, // milliseconds
retries: 3, // number of retry attempts
shouldRetry: ({ response }) => response?.status >= 500, // custom retry logic
});
OptionTypeDescription
paramsobjectPath parameters to interpolate into the URL
queryobjectQuery parameters to append to the URL
bodyobjectRequest body (required for POST, PUT, PATCH)
headersobjectAdditional headers to include
timeoutnumberRequest timeout in milliseconds
retriesnumberNumber of retry attempts
shouldRetryfunctionCustom retry logic callback

See Error Handling for more details on shouldRetry.