CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-swagger-client

SwaggerJS - a collection of interfaces for OAI specs

Pending
Overview
Eval results
Files

client-construction.mddocs/

Client Construction and Configuration

SwaggerClient constructor and configuration options for initializing clients with OpenAPI specifications.

Capabilities

SwaggerClient Constructor

Creates a SwaggerClient instance with automatic spec resolution and interface generation.

/**
 * Creates a SwaggerClient instance
 * @param options - Configuration options for the client
 * @returns Promise resolving to configured SwaggerClient instance
 */
function SwaggerClient(options?: SwaggerClientOptions): Promise<SwaggerClientInstance>;
function SwaggerClient(url: string, options?: SwaggerClientOptions): Promise<SwaggerClientInstance>;

interface SwaggerClientOptions {
  /** URL to fetch the OpenAPI spec from */
  url?: string;
  /** OpenAPI spec object (alternative to url) */
  spec?: object;
  /** Security authorizations for protected operations */
  authorizations?: SecurityAuthorizations;
  /** Function to intercept and modify requests before sending */
  requestInterceptor?: RequestInterceptor;
  /** Function to intercept and modify responses after receiving */
  responseInterceptor?: ResponseInterceptor;
  /** Allow patching of meta patches during resolution */
  allowMetaPatches?: boolean;
  /** Use circular structures during resolution */
  useCircularStructures?: boolean;
  /** Custom HTTP client implementation */
  http?: HttpClient;
  /** Legacy fetch function (use userFetch instead) */
  fetch?: FetchFunction;
  /** Custom fetch implementation */
  userFetch?: FetchFunction;
  /** Disable automatic interface generation */
  disableInterfaces?: boolean;
  /** Skip normalization during resolution */
  skipNormalization?: boolean;
  /** Array of paths to discriminate during resolution */
  pathDiscriminator?: string[];
  /** Use v2 operation ID compatibility mode */
  v2OperationIdCompatibilityMode?: boolean;
}

interface SwaggerClientInstance {
  /** Resolved OpenAPI specification */
  spec: object;
  /** Original spec before resolution */
  originalSpec?: object;
  /** Resolution errors encountered */
  errors: ResolutionError[];
  /** Tag-based operation interfaces */
  apis: TaggedOperations;
  /** Security authorizations */
  authorizations?: SecurityAuthorizations;
  /** Execute an operation */
  execute(options: ExecutionOptions): Promise<ResponseObject>;
  /** Re-resolve the specification */
  resolve(options?: ResolveOptions): Promise<SwaggerClientInstance>;
}

Usage Examples:

// Initialize with URL
const client = await SwaggerClient({
  url: "https://petstore.swagger.io/v2/swagger.json"
});

// Initialize with spec object  
const client = await SwaggerClient({
  spec: {
    openapi: "3.0.0",
    info: { title: "API", version: "1.0.0" },
    paths: {}
  }
});

// Initialize with URL as first parameter
const client = await SwaggerClient("https://api.example.com/openapi.json");

// Initialize with authorizations
const client = await SwaggerClient({
  url: "https://api.example.com/openapi.json",
  authorizations: {
    ApiKeyAuth: { value: "your-api-key" },
    BasicAuth: { username: "user", password: "pass" }
  }
});

// Initialize with interceptors
const client = await SwaggerClient({
  url: "https://api.example.com/openapi.json",
  requestInterceptor: (req) => {
    req.headers["X-Custom-Header"] = "value";
    return req;
  },
  responseInterceptor: (res) => {
    console.log("Response received:", res.status);
    return res;
  }
});

Static Methods

Static methods available on the SwaggerClient constructor.

/** Default HTTP client */
SwaggerClient.http: HttpFunction;

/** Create custom HTTP client wrapper */
SwaggerClient.makeHttp: (httpFn: HttpFunction, preFetch?: Function, postFetch?: Function) => HttpFunction;

/** Resolve OpenAPI specifications */
SwaggerClient.resolve: (options: ResolveOptions) => Promise<ResolutionResult>;

/** Resolve specification subtrees */
SwaggerClient.resolveSubtree: (options: ResolveOptions) => Promise<ResolutionResult>;

/** Execute operations */
SwaggerClient.execute: (options: ExecutionOptions) => Promise<ResponseObject>;

/** Build HTTP requests */
SwaggerClient.buildRequest: (options: BuildRequestOptions) => RequestObject;

/** Get base URL for operations */
SwaggerClient.getBaseUrl: (options: BaseUrlOptions) => string;

/** Serialize responses */
SwaggerClient.serializeRes: (response: Response, url: string, request: RequestObject) => Promise<ResponseObject>;

/** Serialize headers */
SwaggerClient.serializeHeaders: (headers: Headers) => Record<string, string>;

/** Clear resolver caches */
SwaggerClient.clearCache: () => void;

/** Create tag-based operation interfaces */
SwaggerClient.makeApisTagOperation: (swaggerClient: SwaggerClientInstance) => { apis: TaggedOperations };

/** Create custom resolver with strategies */
SwaggerClient.makeResolve: (defaultOptions: ResolveOptions) => (options: ResolveOptions) => Promise<ResolutionResult>;

/** Create custom subtree resolver with strategies */
SwaggerClient.makeResolveSubtree: (defaultOptions: SubtreeOptions) => (obj: object, path: string[], options?: SubtreeOptions) => Promise<ResolutionResult>;

/** Helper utilities */
SwaggerClient.helpers: {
  opId: (operation: OperationObject, pathName: string, method: string, options?: OpIdOptions) => string;
};

Resolution Strategies

Available resolution strategies for different OpenAPI versions.

SwaggerClient.resolveStrategies: {
  "openapi-3-1-apidom": ResolveStrategy;
  "openapi-3-0": ResolveStrategy;
  "openapi-2-0": ResolveStrategy;
  "generic": ResolveStrategy;
};

interface ResolveStrategy {
  match(spec: object): boolean;
  normalize(spec: object): object;
  resolve(options: ResolveOptions): Promise<ResolutionResult>;
}

ApiDOM Integration

Advanced parsing and dereferencing capabilities using ApiDOM.

SwaggerClient.apidom: {
  resolve: {
    resolvers: {
      HTTPResolverSwaggerClient: ApiDOMResolver;
    };
  };
  parse: {
    parsers: {
      JsonParser: ApiDOMParser;
      YamlParser: ApiDOMParser;
      OpenApiJson3_1Parser: ApiDOMParser;
      OpenApiYaml3_1Parser: ApiDOMParser;
    };
  };
  dereference: {
    strategies: {
      OpenApi3_1SwaggerClientDereferenceStrategy: ApiDOMDereferenceStrategy;
    };
  };
};

Instance Methods

Methods available on SwaggerClient instances.

/**
 * Execute an operation on this client instance
 * @param options - Execution options
 * @returns Promise resolving to response object
 */
execute(options: Omit<ExecutionOptions, 'spec'>): Promise<ResponseObject>;

/**
 * Re-resolve the specification for this client instance  
 * @param options - Resolution options
 * @returns Promise resolving to this client instance
 */
resolve(options?: ResolveOptions): Promise<SwaggerClientInstance>;

/**
 * Apply default values to the specification
 * Adds default hosts, schemes, servers for different OpenAPI versions
 */
applyDefaults(): void;

Common Types

interface SecurityAuthorizations {
  [securityName: string]: SecurityValue;
}

interface SecurityValue {
  /** Username for basic auth */
  username?: string;
  /** Password for basic auth */
  password?: string;
  /** Client ID for OAuth2 */
  clientId?: string;
  /** Client secret for OAuth2 */
  clientSecret?: string;
  /** API key or bearer token value */
  value?: string;
}

interface RequestInterceptor {
  (request: RequestObject): RequestObject | Promise<RequestObject>;
}

interface ResponseInterceptor {
  (response: ResponseObject): ResponseObject | Promise<ResponseObject>;
}

interface HttpClient {
  (url: string, options?: HttpOptions): Promise<ResponseObject>;
  withCredentials?: boolean;
}

interface FetchFunction {
  (url: string, options?: RequestInit): Promise<Response>;
}

interface ResolutionError {
  message: string;
  fullPath: string[];
}

interface TaggedOperations {
  [tagName: string]: {
    [operationId: string]: (parameters?: ParameterValues, options?: ExecutionOptions) => Promise<ResponseObject>;
  };
}

interface SubtreeOptions {
  /** Return entire tree instead of just the subtree */
  returnEntireTree?: boolean;
  /** Base document for resolution context */
  baseDoc?: object;
  /** Function to intercept requests */
  requestInterceptor?: RequestInterceptor;
  /** Function to intercept responses */
  responseInterceptor?: ResponseInterceptor;
  /** Use circular structures in resolution */
  useCircularStructures?: boolean;
  /** Resolution strategies to use */
  strategies?: ResolveStrategy[];
}

interface ResolveStrategy {
  /** Check if this strategy can handle the given spec */
  match(spec: object): boolean;
  /** Normalize the specification */
  normalize(spec: object): object;
  /** Resolve the specification */
  resolve(options: ResolveOptions): Promise<ResolutionResult>;
}

Install with Tessl CLI

npx tessl i tessl/npm-swagger-client

docs

client-construction.md

execution.md

helpers.md

http-client.md

index.md

request-building.md

resolution.md

tile.json