SwaggerJS - a collection of interfaces for OAI specs
—
Customizable HTTP client with request/response serialization, interceptors, and platform-specific implementations.
Core HTTP client for making requests with automatic serialization and error handling.
/**
* Make HTTP request with automatic serialization
* @param url - Request URL or request object
* @param request - Request options (if url is string)
* @returns Promise resolving to response object
*/
function http(url: string | RequestObject, request?: HttpOptions): Promise<ResponseObject>;
interface HttpOptions {
/** HTTP method */
method?: string;
/** Request headers */
headers?: Record<string, string>;
/** Request body */
body?: any;
/** Request credentials policy */
credentials?: RequestCredentials;
/** Query parameters object */
query?: Record<string, any>;
/** Function to intercept and modify request */
requestInterceptor?: RequestInterceptor;
/** Function to intercept and modify response */
responseInterceptor?: ResponseInterceptor;
/** Custom fetch implementation */
userFetch?: FetchFunction;
/** AbortSignal for request cancellation */
signal?: AbortSignal;
}
interface ResponseObject {
/** Request URL */
url: string;
/** HTTP method used */
method: string;
/** HTTP status code */
status: number;
/** HTTP status text */
statusText: string;
/** Response headers as object */
headers: Record<string, string>;
/** Response body as text */
text: string;
/** Parsed response body */
body: any;
/** Alias for body */
obj: any;
/** Whether response was successful (2xx status) */
ok: boolean;
/** Alias for body */
data: any;
}Usage Examples:
import http from "swagger-client/http";
// Simple GET request
const response = await http("https://api.example.com/users");
console.log(response.body);
// POST request with JSON body
const response = await http("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: {
name: "John Doe",
email: "john@example.com"
}
});
// Request with query parameters
const response = await http("https://api.example.com/users", {
query: {
page: 1,
limit: 10,
sort: "name"
}
});
// Request with custom headers
const response = await http("https://api.example.com/protected", {
headers: {
"Authorization": "Bearer token",
"X-API-Key": "api-key"
}
});
// Request object format
const response = await http({
url: "https://api.example.com/users",
method: "POST",
headers: { "Content-Type": "application/json" },
body: { name: "Jane Doe" }
});Create custom HTTP clients with pre-configured interceptors.
/**
* Create custom HTTP client with interceptors
* @param httpFn - Base HTTP function
* @param preFetch - Function to modify request before sending
* @param postFetch - Function to modify response after receiving
* @returns Configured HTTP client function
*/
function makeHttp(
httpFn: HttpFunction,
preFetch?: PreFetchFunction,
postFetch?: PostFetchFunction
): HttpFunction;
interface PreFetchFunction {
(request: RequestObject): RequestObject | Promise<RequestObject>;
}
interface PostFetchFunction {
(response: ResponseObject): ResponseObject | Promise<ResponseObject>;
}
interface HttpFunction {
(url: string | RequestObject, options?: HttpOptions): Promise<ResponseObject>;
}Factory Examples:
import { makeHttp, http } from "swagger-client";
// Create HTTP client with authentication
const authenticatedHttp = makeHttp(
http,
(req) => {
req.headers = req.headers || {};
req.headers.Authorization = "Bearer " + getAccessToken();
return req;
}
);
// Create HTTP client with logging
const loggingHttp = makeHttp(
http,
(req) => {
console.log("→", req.method, req.url);
return req;
},
(res) => {
console.log("←", res.status, res.url);
return res;
}
);
// Create HTTP client with retry logic
const retryHttp = makeHttp(
http,
null, // no pre-fetch modification
async (res) => {
if (res.status >= 500 && res.retryCount < 3) {
res.retryCount = (res.retryCount || 0) + 1;
await new Promise(resolve => setTimeout(resolve, 1000));
return http(res.url, { ...res.originalRequest });
}
return res;
}
);
// Use custom HTTP client
const response = await authenticatedHttp("https://api.example.com/protected");Automatic serialization of request data including query parameters and form data.
/**
* Serialize request object
* @param request - Request object to serialize
* @returns Serialized request object
*/
function serializeRequest(request: RequestObject): RequestObject;
interface RequestObject {
url: string;
method: string;
headers: Record<string, string>;
body?: any;
query?: Record<string, any>;
credentials?: RequestCredentials;
requestInterceptor?: RequestInterceptor;
responseInterceptor?: ResponseInterceptor;
userFetch?: FetchFunction;
}Serialization Examples:
// Query parameter serialization
const request = {
url: "https://api.example.com/search",
query: {
q: "javascript",
page: 1,
filters: ["recent", "popular"]
}
};
// Results in: https://api.example.com/search?q=javascript&page=1&filters=recent&filters=popular
// Form data serialization
const request = {
url: "https://api.example.com/upload",
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
body: {
file: fileObject,
description: "My file"
}
};
// Automatically creates FormData object
// JSON body serialization
const request = {
url: "https://api.example.com/users",
method: "POST",
body: {
name: "John",
email: "john@example.com"
}
};
// Body is automatically JSON.stringify'd when content-type is application/jsonAutomatic response parsing and header processing.
/**
* Serialize response object
* @param response - Raw fetch Response
* @param url - Request URL
* @param request - Original request object
* @returns Serialized response object
*/
function serializeResponse(response: Response, url: string, request: RequestObject): Promise<ResponseObject>;
/**
* Serialize response headers
* @param headers - Headers object or Headers instance
* @returns Headers as plain object
*/
function serializeHeaders(headers: Headers | Record<string, string>): Record<string, string>;
/**
* Determine if response should be downloaded as text
* @param contentType - Response content type
* @returns Whether to download as text
*/
function shouldDownloadAsText(contentType: string): boolean;Response Processing Examples:
// Automatic JSON parsing
const response = await http("https://api.example.com/users.json");
console.log(response.body); // Parsed JSON object
console.log(response.text); // Raw JSON string
// Text response handling
const response = await http("https://api.example.com/readme.txt");
console.log(response.text); // Raw text content
console.log(response.body); // Same as text for non-JSON responses
// Binary response handling
const response = await http("https://api.example.com/image.png");
console.log(response.body); // ArrayBuffer or Blob depending on environment
// Header access
const response = await http("https://api.example.com/data");
console.log(response.headers["content-type"]);
console.log(response.headers["x-rate-limit"]);Support for file uploads and multipart form data.
/**
* Check if value is a file object
* @param value - Value to check
* @returns Whether value is a file
*/
function isFile(value: any): boolean;
/**
* Check if value is an array of files
* @param value - Value to check
* @returns Whether value is array of files
*/
function isArrayOfFile(value: any): boolean;
/**
* File wrapper with additional metadata
*/
class FileWithData {
constructor(data: any, file: File);
data: any;
file: File;
}File Examples:
// File upload
const fileInput = document.getElementById('file');
const file = fileInput.files[0];
const response = await http("https://api.example.com/upload", {
method: "POST",
body: {
file: file,
description: "Profile picture"
}
});
// Multiple file upload
const response = await http("https://api.example.com/upload-multiple", {
method: "POST",
body: {
files: [file1, file2, file3],
category: "documents"
}
});
// File with metadata
const fileWithData = new FileWithData({ id: 123 }, file);
const response = await http("https://api.example.com/upload", {
method: "POST",
body: {
fileData: fileWithData
}
});Modify requests and responses during processing.
interface RequestInterceptor {
(request: RequestObject): RequestObject | Promise<RequestObject>;
}
interface ResponseInterceptor {
(response: ResponseObject): ResponseObject | Promise<ResponseObject>;
}Interceptor Examples:
// Request interceptor for authentication
const authInterceptor = (req) => {
req.headers = req.headers || {};
req.headers.Authorization = `Bearer ${getToken()}`;
return req;
};
// Response interceptor for error handling
const errorInterceptor = (res) => {
if (res.status === 401) {
// Handle authentication error
redirectToLogin();
}
return res;
};
// Using interceptors
const response = await http("https://api.example.com/protected", {
requestInterceptor: authInterceptor,
responseInterceptor: errorInterceptor
});
// Async interceptors
const asyncInterceptor = async (req) => {
const token = await getTokenAsync();
req.headers.Authorization = `Bearer ${token}`;
return req;
};Features that work differently in browser vs Node.js environments.
// Browser-specific: Works with native fetch, XMLHttpRequest fallback
// Node.js-specific: Works with node-fetch or native fetch (Node 18+)
// Credential handling
const response = await http("https://api.example.com/data", {
credentials: "include" // Browser: sends cookies, Node.js: no effect
});
// Custom fetch implementation
const response = await http("https://api.example.com/data", {
userFetch: customFetchImplementation
});
// Request cancellation
const controller = new AbortController();
const response = await http("https://api.example.com/data", {
signal: controller.signal
});
// Cancel the request
setTimeout(() => controller.abort(), 5000);interface RequestInterceptor {
(request: RequestObject): RequestObject | Promise<RequestObject>;
}
interface ResponseInterceptor {
(response: ResponseObject): ResponseObject | Promise<ResponseObject>;
}
interface FetchFunction {
(url: string, options?: RequestInit): Promise<Response>;
}
interface RequestCredentials {
"include" | "omit" | "same-origin";
}
interface RequestObject {
url: string;
method: string;
headers: Record<string, string>;
body?: any;
credentials?: RequestCredentials;
signal?: AbortSignal;
query?: Record<string, any>;
requestInterceptor?: RequestInterceptor;
responseInterceptor?: ResponseInterceptor;
userFetch?: FetchFunction;
}
interface ResponseObject {
url: string;
method: string;
status: number;
statusText: string;
headers: Record<string, string>;
text: string;
body: any;
obj: any;
ok: boolean;
data: any;
}Install with Tessl CLI
npx tessl i tessl/npm-swagger-client