Generate TypeScript API clients from OpenAPI/Swagger specifications with support for Fetch and Axios HTTP clients
—
Complete TypeScript type definitions for swagger-typescript-api, providing full type safety for all configuration options, return values, and customization hooks.
type HttpClientType = "fetch" | "axios";interface FileInfo {
/** File name without extension (e.g., "Api") */
fileName: string;
/** File extension (e.g., ".ts", ".d.ts") */
fileExtension: string;
/** Generated file content */
fileContent: string;
}interface GenerateApiOutput {
/** Final configuration used for generation */
configuration: GenerateApiConfiguration;
/** Array of generated files with content */
files: FileInfo[];
/** Function to write files to disk */
createFile: (params: CreateFileParams) => void;
/** Function to render EJS templates with data */
renderTemplate: (
templateContent: string,
data: Record<string, unknown>,
etaOptions?: Partial<EtaConfig>
) => Promise<string> | string;
/** Function to retrieve template content */
getTemplate: (params: GetTemplateParams) => string;
/** Function to format TypeScript code */
formatTSContent: (content: string) => Promise<string>;
}
interface CreateFileParams {
path: string;
fileName: string;
content: string;
withPrefix: boolean;
}
interface GetTemplateParams {
fileName?: string;
name?: string;
path?: string;
}interface GenerateTemplatesOutput {
/** Array of generated template files */
files: FileInfo[];
/** Function to write template files to disk */
createFile: (params: CreateFileParams) => void;
}interface GenerateApiConfiguration {
/** API metadata from OpenAPI specification */
apiConfig: ApiConfig;
/** Generation configuration options */
config: GenerationConfig;
/** Generated model type definitions */
modelTypes: ModelType[];
/** Parsed route information */
routes: RouteInfo;
/** Utility functions for template processing */
utils: TemplateUtils;
/** Flags for different generation aspects */
hasFormDataRoutes: boolean;
hasSecurityRoutes: boolean;
hasQueryRoutes: boolean;
generateResponses: boolean;
/** Request configuration for schema fetching */
requestOptions?: Partial<RequestInit>;
}
interface ApiConfig {
/** Base URL from OpenAPI specification */
baseUrl: string;
/** API title from specification */
title: string;
/** API version from specification */
version: string;
/** Description split into lines */
description: string[];
/** Flag indicating if description is present */
hasDescription: boolean;
}interface GenerationConfig {
/** Input/Output Options */
input: string;
url: string;
spec: unknown;
output: string | false;
fileName: string;
templates: string;
modular: boolean;
/** HTTP Client Configuration */
httpClientType: HttpClientType;
singleHttpClient: boolean;
/** Generation Flags */
generateClient: boolean;
generateResponses: boolean;
generateRouteTypes: boolean;
generateUnionEnums: boolean;
/** Type Generation Options */
addReadonly: boolean;
anotherArrayType: boolean;
extractEnums: boolean;
extractRequestBody: boolean;
extractResponseBody: boolean;
extractResponseError: boolean;
extractRequestParams: boolean;
extractResponses: boolean;
/** Processing Options */
defaultResponseAsSuccess: boolean;
defaultResponseType: string;
disableThrowOnError: boolean;
patch: boolean;
unwrapResponseData: boolean;
/** Naming Options */
apiClassName: string;
typePrefix: string;
typeSuffix: string;
enumKeyPrefix: string;
enumKeySuffix: string;
fixInvalidTypeNamePrefix: string;
fixInvalidEnumKeyPrefix: string;
/** Organization Options */
moduleNameIndex: number;
moduleNameFirstTag: boolean;
sortTypes: boolean;
sortRoutes: boolean;
/** Output Options */
cleanOutput: boolean;
toJS: boolean;
silent: boolean;
debug: boolean;
/** Advanced Configuration */
hooks: Partial<Hooks>;
primitiveTypeConstructs?: (struct: PrimitiveTypeStruct) => Partial<PrimitiveTypeStruct>;
codeGenConstructs?: (struct: CodeGenConstruct) => Partial<CodeGenConstruct>;
customTranslator?: new () => Translator;
schemaParsers?: Partial<SchemaParserMap>;
extractingOptions: Partial<ExtractingOptions>;
/** Internal Configuration */
version: string;
constants: typeof CONSTANTS;
compilerTsConfig: Record<string, unknown>;
successResponseStatusRange: [number, number];
templatePaths: TemplatePaths;
templatesToRender: TemplatesToRender;
fileNames: FileNames;
internalTemplateOptions: InternalTemplateOptions;
}interface SchemaComponent {
/** Schema reference path */
$ref: string;
/** Generated type name */
typeName: string;
/** Original schema data */
rawTypeData?: RawTypeData;
/** Component category */
componentName: "schemas" | "paths";
/** Parsed type information */
typeData: ParsedSchema<SchemaContent> | null;
}
interface ParsedSchema<C> {
$parsedSchema: boolean;
schemaType: string;
type: string;
typeIdentifier: string;
name: string;
description?: string;
allFieldsAreOptional?: boolean;
content: C;
isExtractedRequestParams?: boolean;
isExtractedRequestBody?: boolean;
isExtractedResponseBody?: boolean;
isExtractedResponseError?: boolean;
}
interface ParsedRoute {
/** Unique route identifier */
id: string;
/** Route namespace/module */
namespace: string;
/** Route parameters */
routeParams?: Record<string, any>;
/** Request body information */
requestBodyInfo?: RequestBodyInfo;
/** Response body information */
responseBodyInfo?: ResponseBodyInfo;
/** Specific route arguments */
specificArgs?: Record<string, any>;
/** Request information */
request: ParsedRouteRequest;
/** Response information */
response: ParsedRouteResponse;
/** Route naming information */
routeName: RouteNameInfo;
/** Original route data */
raw: RawRouteInfo;
}
interface ModelType {
/** Type identifier */
typeIdentifier: string;
/** Type name */
name: string;
/** Raw content string */
rawContent: string;
/** Type description */
description: string;
/** Formatted content */
content: string;
}interface RawTypeData {
type: string;
required?: string[];
properties?: Record<string, {
name?: string;
type: string;
required: boolean;
$parsed?: SchemaTypePrimitiveContent;
}>;
discriminator?: {
propertyName?: string;
};
$parsed: ParsedSchema<SchemaTypeObjectContent | SchemaTypeEnumContent | SchemaTypePrimitiveContent>;
}
interface HeaderInfo {
/** Header name */
name: string | null;
/** Whether header is optional */
optional: boolean | undefined;
/** Header type definition */
type: Record<string, any>;
}
interface PayloadInfo {
/** Payload parameter name */
name: string | null;
/** Whether payload is optional */
optional?: boolean;
/** Payload type */
type: string;
}
interface RequestBodyInfo {
/** Parameter name for request body */
paramName: any;
/** Content types accepted */
contentTypes: any[];
/** Content kind */
contentKind: string;
/** Request body schema */
schema: any;
/** Request body type */
type: any;
/** Whether request body is required */
required: any;
}
interface ResponseBodyInfo {
/** Response content types */
contentTypes: any[];
/** Response definitions */
responses: any[];
/** Success response info */
success?: Record<string, any>;
/** Error response info */
error?: Record<string, any>;
/** Full response info */
full?: Record<string, any>;
}
interface CodeGenProcess {
/** Code generation process methods and properties */
start(): Promise<any>;
}
interface SchemaTypePrimitiveContent {
$parsedSchema: boolean;
schemaType: string;
type: string;
typeIdentifier: string;
name?: unknown;
description: string;
content: string;
}
interface SchemaTypeObjectContent extends Array<{
$$raw: {
type: string;
required: boolean;
$parsed: SchemaTypePrimitiveContent;
};
isRequired: boolean;
field: string;
}> {}
interface SchemaTypeEnumContent extends Array<{
key: string;
type: string;
value: string;
}> {}
type SchemaContent =
| SchemaTypeObjectContent
| SchemaTypeEnumContent
| SchemaTypePrimitiveContent;
interface RouteInfo {
/** Routes not organized into modules */
outOfModule: ParsedRoute[];
/** Routes organized by modules */
combined?: {
moduleName: string;
routes: ParsedRoute[];
}[];
}
interface SchemaParserMap {
complexOneOf?: MonoSchemaParser;
complexAllOf?: MonoSchemaParser;
complexAnyOf?: MonoSchemaParser;
complexNot?: MonoSchemaParser;
enum?: MonoSchemaParser;
object?: MonoSchemaParser;
complex?: MonoSchemaParser;
primitive?: MonoSchemaParser;
discriminator?: MonoSchemaParser;
array?: MonoSchemaParser;
}
interface MonoSchemaParser {
/** Schema parser function */
parse(schemaParserInput: any): any;
}
interface SchemaParser {
/** Parse schema with given input */
parseSchema(schema: Record<string, unknown>): any;
}
abstract class Translator {
/** Abstract translator class for TypeScript to other languages */
abstract translate(content: string): string;
}interface ParsedRouteRequest {
contentTypes?: string[];
formData?: boolean;
headers?: HeaderInfo;
isQueryBody?: boolean;
method?: string;
parameters?: Record<string, unknown>[];
path?: string;
pathParams?: Record<string, unknown>;
payload?: PayloadInfo;
query?: Record<string, unknown>;
requestParams?: Record<string, unknown> | null;
security?: boolean;
}
interface ParsedRouteResponse {
contentTypes?: string[];
errorType?: string;
fullTypes?: string;
type?: string;
}
interface RequestResponseInfo {
/** Content types accepted/returned */
contentTypes: string[];
/** Content category */
contentKind: RequestContentKind;
/** TypeScript type */
type: string;
/** Description from OpenAPI */
description: string;
/** HTTP status code */
status: string | number;
/** Whether this is a success response */
isSuccess: boolean;
}
enum RequestContentKind {
JSON = "JSON",
URL_ENCODED = "URL_ENCODED",
FORM_DATA = "FORM_DATA",
IMAGE = "IMAGE",
OTHER = "OTHER",
TEXT = "TEXT"
}interface RouteNameInfo {
/** Generated usage name */
usage: string;
/** Original name from OpenAPI */
original: string;
/** Whether name is duplicated */
duplicate: boolean;
}
interface RawRouteInfo {
/** OpenAPI operationId */
operationId: string;
/** HTTP method */
method: string;
/** Route path */
route: string;
/** Module name for organization */
moduleName: string;
/** Response type information */
responsesTypes: RequestResponseInfo[];
/** Route description */
description?: string;
/** OpenAPI tags */
tags?: string[];
/** Route summary */
summary?: string;
/** OpenAPI responses object */
responses?: import("swagger-schema-official").Spec["responses"];
/** Produced content types */
produces?: string[];
/** Request body definition */
requestBody?: object;
/** Consumed content types */
consumes?: string[];
}
interface PathArgInfo {
/** Parameter name */
name: string;
/** Whether parameter is optional */
optional: boolean;
/** Parameter type */
type: string;
/** Parameter description */
description?: string;
}interface Hooks {
/** Called before processing route path */
onPreBuildRoutePath?: (routePath: string) => string | undefined;
/** Called after processing route path */
onBuildRoutePath?: (data: BuildRoutePath) => BuildRoutePath | undefined;
/** Called before inserting path parameter */
onInsertPathParam?: (
paramName: string,
index: number,
arr: BuildRouteParam[],
resultRoute: string
) => string | undefined;
/** Called after parsing schema component */
onCreateComponent?: (component: SchemaComponent) => SchemaComponent | undefined;
/** Called before parsing any schema */
onPreParseSchema?: (
originalSchema: unknown,
typeName: string,
schemaType: string
) => undefined;
/** Called after parsing any schema */
onParseSchema?: (
originalSchema: unknown,
parsedSchema: unknown
) => unknown | undefined;
/** Called after creating route (can return false to ignore route) */
onCreateRoute?: (routeData: ParsedRoute) => ParsedRoute | false | undefined;
/** Called at initialization */
onInit?: <C extends GenerationConfig>(
configuration: C,
codeGenProcess: CodeGenProcess
) => C | undefined;
/** Called before preparing configuration for templates */
onPrepareConfig?: <C extends GenerateApiConfiguration>(
currentConfiguration: C
) => C | undefined;
/** Called when creating route names */
onCreateRouteName?: (
routeNameInfo: RouteNameInfo,
rawRouteInfo: RawRouteInfo
) => RouteNameInfo | undefined;
/** Called when creating request parameters */
onCreateRequestParams?: (
rawType: SchemaComponent["rawTypeData"]
) => SchemaComponent["rawTypeData"] | undefined;
/** Called when formatting type names */
onFormatTypeName?: (
typeName: string,
rawTypeName?: string,
schemaType?: "type-name" | "enum-key"
) => string | undefined;
/** Called when formatting route names */
onFormatRouteName?: (
routeInfo: RawRouteInfo,
templateRouteName: string
) => string | undefined;
}type PrimitiveTypeStruct = Record<
"integer" | "number" | "boolean" | "object" | "file" | "string" | "array",
| string
| ({ $default: PrimitiveTypeStructValue } & Record<string, PrimitiveTypeStructValue>)
>;
type PrimitiveTypeStructValue =
| string
| ((schema: Record<string, unknown>, parser: SchemaParser) => string);
interface CodeGenConstruct {
Keyword: {
Number: string;
String: string;
Boolean: string;
Any: string;
Void: string;
Unknown: string;
Null: string;
Undefined: string;
Object: string;
File: string;
Date: string;
Type: string;
Enum: string;
Interface: string;
Array: string;
Record: string;
Intersection: string;
Union: string;
};
CodeGenKeyword: {
UtilRequiredKeys: string;
};
ArrayType: (content: unknown) => string;
StringValue: (content: unknown) => string;
BooleanValue: (content: unknown) => string;
NumberValue: (content: unknown) => string;
NullValue: (content: unknown) => string;
UnionType: (content: unknown) => string;
ExpressionGroup: (content: unknown) => string;
IntersectionType: (content: unknown) => string;
RecordType: (content: unknown) => string;
TypeField: (content: unknown) => string;
InterfaceDynamicField: (content: unknown) => string;
EnumUsageKey: (enumStruct: unknown, key: unknown) => string;
EnumField: (content: unknown) => string;
EnumFieldDescription: (content: unknown) => string;
EnumFieldsWrapper: (content: unknown) => string;
ObjectWrapper: (content: unknown) => string;
MultilineComment: (content: unknown) => string;
TypeWithGeneric: (content: unknown) => string;
Tuple: (content: unknown) => string;
}interface ExtractingOptions {
requestBodySuffix: string[];
responseBodySuffix: string[];
responseErrorSuffix: string[];
requestParamsSuffix: string[];
enumSuffix: string[];
discriminatorMappingSuffix: string[];
discriminatorAbstractPrefix: string[];
requestBodyNameResolver: (name: string, reservedNames: string) => string | undefined;
responseBodyNameResolver: (name: string, reservedNames: string) => string | undefined;
responseErrorNameResolver: (name: string, reservedNames: string) => string | undefined;
requestParamsNameResolver: (name: string, reservedNames: string) => string | undefined;
enumNameResolver: (name: string, reservedNames: string) => string | undefined;
discriminatorMappingNameResolver: (name: string, reservedNames: string) => string | undefined;
discriminatorAbstractResolver: (name: string, reservedNames: string) => string | undefined;
}interface TemplateUtils {
formatDescription: (description: string, inline?: boolean) => string;
internalCase: (value: string) => string;
pascalCase: (value: string) => string;
getInlineParseContent: (rawTypeData: RawTypeData, typeName?: string) => string;
getParseContent: (rawTypeData: RawTypeData, typeName?: string) => ModelType;
getComponentByRef: (ref: string) => SchemaComponent;
parseSchema: (
rawSchema: string | RawTypeData,
typeName?: string,
formattersMap?: Record<MainSchemaTypes, (content: ModelType) => string>
) => ModelType;
formatters: Record<MainSchemaTypes, (content: string | object | string[] | object[]) => string>;
inlineExtraFormatters: Record<Exclude<MainSchemaTypes, SCHEMA_TYPES.PRIMITIVE>, (schema: ModelType) => string>;
formatModelName: (name: string) => string;
fmtToJSDocLine: (line: string, params?: { eol?: boolean }) => string;
_: import("lodash").LoDashStatic;
require: (path: string) => unknown;
}enum SCHEMA_TYPES {
ARRAY = "array",
OBJECT = "object",
ENUM = "enum",
REF = "$ref",
PRIMITIVE = "primitive",
COMPLEX = "complex",
COMPLEX_ONE_OF = "oneOf",
COMPLEX_ANY_OF = "anyOf",
COMPLEX_ALL_OF = "allOf",
COMPLEX_NOT = "not",
COMPLEX_UNKNOWN = "__unknown"
}
type MainSchemaTypes =
| SCHEMA_TYPES.PRIMITIVE
| SCHEMA_TYPES.OBJECT
| SCHEMA_TYPES.ENUM;interface TemplatePaths {
base: string;
default: string;
modular: string;
original: string;
custom: string | null;
}
interface TemplatesToRender {
api: string;
dataContracts: string;
httpClient: string;
routeTypes: string;
routeName: string;
dataContractJsDoc: string;
interfaceDataContract: string;
typeDataContract: string;
enumDataContract: string;
objectFieldJsDoc: string;
}
interface FileNames {
dataContracts: string;
routeTypes: string;
httpClient: string;
outOfModuleApi: string;
}
interface InternalTemplateOptions {
addUtilRequiredKeysType: boolean;
}Install with Tessl CLI
npx tessl i tessl/npm-swagger-typescript-api