or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-usage.mdconfiguration.mdcore-api.mdindex.mdtypes-interfaces.md

index.mddocs/

0

# swagger-typescript-api

1

2

swagger-typescript-api is a TypeScript code generation tool that automatically creates API client code from OpenAPI/Swagger specifications. It supports both OpenAPI 3.0 and 2.0 in JSON and YAML formats, generating type-safe TypeScript interfaces and HTTP client implementations for both Fetch and Axios.

3

4

## Package Information

5

6

- **Package Name**: swagger-typescript-api

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install --save-dev swagger-typescript-api`

10

11

## Core Imports

12

13

```typescript

14

import { generateApi, generateTemplates, constants } from "swagger-typescript-api";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { generateApi, generateTemplates, constants } = require("swagger-typescript-api");

21

```

22

23

## Basic Usage

24

25

### Programmatic API

26

27

```typescript

28

import { generateApi } from "swagger-typescript-api";

29

import * as path from "node:path";

30

31

// Generate from local file

32

const { files } = await generateApi({

33

input: path.resolve(process.cwd(), "./swagger.json"),

34

output: path.resolve(process.cwd(), "./src/api"),

35

fileName: "ApiClient.ts",

36

httpClientType: "fetch"

37

});

38

39

// Generate from URL

40

const result = await generateApi({

41

url: "https://api.example.com/swagger.json",

42

output: "./generated",

43

generateResponses: true,

44

generateRouteTypes: true

45

});

46

```

47

48

### CLI Usage

49

50

```bash

51

# Generate from local file

52

npx swagger-typescript-api generate --path ./swagger.json --output ./src/api

53

54

# Generate with custom options

55

npx swagger-typescript-api generate \

56

--path ./api-spec.yaml \

57

--output ./api \

58

--name ApiClient.ts \

59

--axios \

60

--responses \

61

--route-types

62

```

63

64

## Architecture

65

66

swagger-typescript-api is built around several key components:

67

68

- **Code Generation Engine**: Core `generateApi` function that orchestrates the entire generation process

69

- **Schema Parser**: Converts OpenAPI schemas into TypeScript type definitions with support for complex schema patterns

70

- **Route Generator**: Creates API client methods from OpenAPI path definitions with proper parameter handling

71

- **Template System**: EJS-based template engine allowing full customization of generated code structure

72

- **CLI Interface**: Command-line tool with comprehensive options for build pipeline integration

73

- **Type Safety**: Complete TypeScript type definitions throughout the generation pipeline

74

75

## Capabilities

76

77

### Core API Generation

78

79

Primary programmatic interface for generating TypeScript API clients from OpenAPI specifications. Supports both local files and remote URLs with extensive configuration options.

80

81

```typescript { .api }

82

function generateApi(params: GenerateApiParams): Promise<GenerateApiOutput>;

83

84

type GenerateApiParams =

85

| GenerateApiParamsFromPath

86

| GenerateApiParamsFromUrl

87

| GenerateApiParamsFromSpecLiteral;

88

89

interface GenerateApiOutput {

90

configuration: GenerateApiConfiguration;

91

files: FileInfo[];

92

createFile: (params: CreateFileParams) => void;

93

renderTemplate: (templateContent: string, data: Record<string, unknown>) => Promise<string>;

94

getTemplate: (params: GetTemplateParams) => string;

95

formatTSContent: (content: string) => Promise<string>;

96

}

97

```

98

99

[Core API](./core-api.md)

100

101

### CLI Interface

102

103

Command-line interface providing full access to generation capabilities with comprehensive options for integration into build pipelines and development workflows.

104

105

```bash { .api }

106

# Main generation command

107

swagger-typescript-api generate [options]

108

109

# Template generation command

110

swagger-typescript-api generate-templates [options]

111

```

112

113

[CLI Usage](./cli-usage.md)

114

115

### Template Generation

116

117

Generate customizable EJS templates for API code generation, allowing full control over the structure and style of generated code.

118

119

```typescript { .api }

120

function generateTemplates(params: GenerateTemplatesParams): Promise<GenerateTemplatesOutput>;

121

122

interface GenerateTemplatesParams {

123

cleanOutput?: boolean;

124

output?: string;

125

httpClientType?: HttpClientType;

126

modular?: boolean;

127

rewrite?: boolean;

128

silent?: boolean;

129

debug?: boolean;

130

}

131

```

132

133

[Core API](./core-api.md)

134

135

### Type Definitions & Configuration

136

137

Comprehensive TypeScript interfaces and configuration options for customizing the generation process, including hooks for advanced customization.

138

139

```typescript { .api }

140

interface GenerateApiConfiguration {

141

apiConfig: ApiConfig;

142

config: GenerationConfig;

143

modelTypes: ModelType[];

144

routes: RouteInfo;

145

utils: TemplateUtils;

146

}

147

148

interface Hooks {

149

onInit?: (config: GenerationConfig) => GenerationConfig | undefined;

150

onParseSchema?: (originalSchema: unknown, parsedSchema: unknown) => unknown | undefined;

151

onCreateRoute?: (routeData: ParsedRoute) => ParsedRoute | false | undefined;

152

// ... additional lifecycle hooks

153

}

154

```

155

156

[Types & Interfaces](./types-interfaces.md)

157

158

[Configuration](./configuration.md)

159

160

### Constants

161

162

Exported constants used throughout the library for configuration and schema processing.

163

164

```typescript { .api }

165

export const constants: {

166

DEFAULT_BODY_ARG_NAME: string;

167

FILE_PREFIX: string;

168

HTTP_CLIENT: {

169

FETCH: "fetch";

170

AXIOS: "axios";

171

};

172

PROJECT_VERSION: string;

173

RESERVED_BODY_ARG_NAMES: string[];

174

RESERVED_HEADER_ARG_NAMES: string[];

175

RESERVED_PATH_ARG_NAMES: string[];

176

RESERVED_QUERY_ARG_NAMES: string[];

177

RESERVED_REQ_PARAMS_ARG_NAMES: string[];

178

SCHEMA_TYPES: {

179

ARRAY: "array";

180

OBJECT: "object";

181

ENUM: "enum";

182

REF: "$ref";

183

PRIMITIVE: "primitive";

184

COMPLEX: "complex";

185

DISCRIMINATOR: "discriminator";

186

COMPLEX_ONE_OF: "oneOf";

187

COMPLEX_ANY_OF: "anyOf";

188

COMPLEX_ALL_OF: "allOf";

189

COMPLEX_NOT: "not";

190

COMPLEX_UNKNOWN: "__unknown";

191

};

192

};

193

```

194

195

## Error Handling

196

197

The library handles various error scenarios:

198

199

- **Invalid OpenAPI schemas**: Detailed error messages for schema validation failures

200

- **Network errors**: Proper handling of remote URL fetching with timeout and retry options

201

- **File system errors**: Clear error messages for file access and write permission issues

202

- **Template errors**: Comprehensive error reporting for template processing failures

203

204

Most functions throw descriptive errors that can be caught and handled in your application code.