CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-swagger-client

SwaggerJS - a collection of interfaces for OAI specs

Pending
Overview
Eval results
Files

execution.mddocs/

API Execution and Operations

Execute operations against OpenAPI specifications with parameter handling, security, and response processing.

Capabilities

Execute Function

Execute an operation by operationId or path/method combination.

/**
 * Execute an OpenAPI operation
 * @param options - Execution configuration
 * @returns Promise resolving to response object
 */
function execute(options: ExecutionOptions): Promise<ResponseObject>;

interface ExecutionOptions {
  /** OpenAPI specification object */
  spec: object;
  /** Operation ID to execute */
  operationId?: string;
  /** Path name for the operation (alternative to operationId) */
  pathName?: string;
  /** HTTP method for the operation (alternative to operationId) */
  method?: string;
  /** Parameter values for the operation */
  parameters?: ParameterValues;
  /** Security requirements and credentials */
  securities?: SecurityRequirements;
  /** Base URL override */
  baseURL?: string;
  /** Context URL for relative URL resolution */
  contextUrl?: string;
  /** Server URL override (for OpenAPI 3.x) */
  server?: string;
  /** Server variable values (for OpenAPI 3.x) */
  serverVariables?: Record<string, string>;
  /** Function to intercept and modify requests */
  requestInterceptor?: RequestInterceptor;
  /** Function to intercept and modify responses */
  responseInterceptor?: ResponseInterceptor;
  /** Custom HTTP client */
  http?: HttpClient;
  /** Legacy fetch function */
  fetch?: FetchFunction;
  /** Custom fetch implementation */
  userFetch?: FetchFunction;
  /** AbortSignal for request cancellation */
  signal?: AbortSignal;
  /** URL scheme override (for Swagger 2.0) */
  scheme?: string;
  /** Response content type preference */
  responseContentType?: string;
  /** Custom parameter builders */
  parameterBuilders?: ParameterBuilders;
  /** Server variable encoder function */
  serverVariableEncoder?: (value: string) => string;
}

interface ResponseObject {
  /** Request URL */
  url: string;
  /** HTTP method used */
  method: string;
  /** HTTP status code */
  status: number;
  /** HTTP status text */
  statusText: string;
  /** Response headers */
  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 { execute } from "swagger-client";

// Execute by operation ID
const response = await execute({
  spec: openApiSpec,
  operationId: "getPetById",
  parameters: {
    petId: 123
  }
});

// Execute by path and method
const response = await execute({
  spec: openApiSpec,
  pathName: "/pets/{petId}",
  method: "GET",
  parameters: {
    petId: 123
  }
});

// Execute with security
const response = await execute({
  spec: openApiSpec,
  operationId: "createPet",
  parameters: {
    body: {
      name: "Fluffy",
      status: "available"
    }
  },
  securities: {
    authorized: {
      ApiKeyAuth: { value: "your-api-key" }
    }
  }
});

// Execute with custom base URL
const response = await execute({
  spec: openApiSpec,
  operationId: "listPets",
  baseURL: "https://api-staging.example.com"
});

// Execute with interceptors
const response = await execute({
  spec: openApiSpec,
  operationId: "getPetById",
  parameters: { petId: 123 },
  requestInterceptor: (req) => {
    console.log("Sending request:", req.method, req.url);
    req.headers["X-Request-ID"] = crypto.randomUUID();
    return req;
  },
  responseInterceptor: (res) => {
    console.log("Received response:", res.status);
    return res;
  }
});

Operation Execution Errors

Handle common execution errors and exceptions.

/**
 * Error thrown when operation ID cannot be found in the spec
 */
class OperationNotFoundError extends Error {
  constructor(message: string);
  name: "OperationNotFoundError";
}

// Usage example:
try {
  const response = await execute({
    spec: openApiSpec,
    operationId: "nonExistentOperation"
  });
} catch (error) {
  if (error instanceof OperationNotFoundError) {
    console.error("Operation not found:", error.message);
  }
}

Parameter Handling

How parameters are processed and validated for different OpenAPI versions.

interface ParameterValues {
  /** Parameter values by name */
  [parameterName: string]: any;
  /** Alternative format: parameter values by location and name */
  [locationAndName: string]: any; // e.g., "query.limit", "header.authorization"
}

interface ParameterBuilders {
  /** Build path parameters */
  path?: ParameterBuilder;
  /** Build query parameters */
  query?: ParameterBuilder;
  /** Build header parameters */
  header?: ParameterBuilder;
  /** Build cookie parameters */
  cookie?: ParameterBuilder;
  /** Build form data parameters */
  formData?: ParameterBuilder;
  /** Build request body */
  body?: ParameterBuilder;
}

interface ParameterBuilder {
  (options: ParameterBuildOptions): void;
}

interface ParameterBuildOptions {
  req: RequestObject;
  parameter: ParameterObject;
  value: any;
  operation: OperationObject;
  spec: object;
  baseURL: string;
}

Parameter Examples:

// Path parameters
await execute({
  spec: openApiSpec,
  operationId: "getUserById",
  parameters: {
    userId: "12345" // Replaces {userId} in path
  }
});

// Query parameters
await execute({
  spec: openApiSpec,
  operationId: "searchUsers",
  parameters: {
    q: "john",
    limit: 10,
    offset: 0
  }
});

// Header parameters
await execute({
  spec: openApiSpec,
  operationId: "getProtectedResource",
  parameters: {
    "X-API-Key": "your-api-key",
    "Accept-Language": "en-US"
  }
});

// Request body (OpenAPI 3.x)
await execute({
  spec: openApiSpec,
  operationId: "createUser",
  parameters: {
    body: {
      name: "John Doe",
      email: "john@example.com"
    }
  }
});

// Form data (Swagger 2.0)
await execute({
  spec: swagger2Spec,
  operationId: "uploadFile",
  parameters: {
    file: fileObject,
    description: "My file"
  }
});

// Ambiguous parameter names (use location.name format)
await execute({
  spec: openApiSpec,
  operationId: "operation",
  parameters: {
    "query.id": "query-id",
    "header.id": "header-id"
  }
});

Security Requirements

Handle authentication and authorization for protected operations.

interface SecurityRequirements {
  /** Authorized security schemes */
  authorized?: SecurityAuthorizations;
}

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

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

Security Examples:

// API Key authentication
const response = await execute({
  spec: openApiSpec,
  operationId: "getProtectedData",
  securities: {
    authorized: {
      ApiKeyAuth: { value: "your-api-key" }
    }
  }
});

// Basic authentication
const response = await execute({
  spec: openApiSpec,
  operationId: "getProtectedData",
  securities: {
    authorized: {
      BasicAuth: {
        username: "user",
        password: "password"
      }
    }
  }
});

// Bearer token authentication
const response = await execute({
  spec: openApiSpec,
  operationId: "getProtectedData",
  securities: {
    authorized: {
      BearerAuth: { value: "jwt-token-here" }
    }
  }
});

// OAuth2 authentication
const response = await execute({
  spec: openApiSpec,
  operationId: "getProtectedData",
  securities: {
    authorized: {
      OAuth2: {
        clientId: "client-id",
        clientSecret: "client-secret"
      }
    }
  }
});

Server Selection (OpenAPI 3.x)

Override server URLs and server variables for OpenAPI 3.x specifications.

// Server selection by URL
const response = await execute({
  spec: openApiSpec,
  operationId: "getData",
  server: "https://api-staging.example.com"
});

// Server variables
const response = await execute({
  spec: openApiSpec,
  operationId: "getData",
  server: "https://{environment}.example.com",
  serverVariables: {
    environment: "staging"
  }
});

// Custom server variable encoder
const response = await execute({
  spec: openApiSpec,
  operationId: "getData",
  serverVariables: {
    version: "v2"
  },
  serverVariableEncoder: (value) => encodeURIComponent(value)
});

Common Types

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 RequestObject {
  url: string;
  method: string;
  headers: Record<string, string>;
  body?: any;
  credentials: RequestCredentials;
  signal?: AbortSignal;
  requestInterceptor?: RequestInterceptor;
  responseInterceptor?: ResponseInterceptor;
  userFetch?: FetchFunction;
}

interface ParameterObject {
  name: string;
  in: "query" | "header" | "path" | "cookie" | "body" | "formData";
  required?: boolean;
  schema?: SchemaObject;
  type?: string;
  default?: any;
  allowEmptyValue?: boolean;
}

interface OperationObject {
  operationId?: string;
  tags?: string[];
  parameters?: ParameterObject[];
  security?: SecurityRequirement[];
  servers?: ServerObject[];
}

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