swagger-typescript-api
Generate the API Client for Fetch or Axios from an OpenAPI Specification
Top Related Projects
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification
Generate TypeScript types from OpenAPI 3 specs
Generate TypeScript types from OpenAPI 3 specs
Quick Overview
Swagger-typescript-api is a tool that generates TypeScript/JavaScript API modules from Swagger/OpenAPI schemas. It automates the process of creating strongly-typed API clients, reducing manual coding efforts and improving type safety in API integrations.
Pros
- Generates TypeScript/JavaScript API modules with full type support
- Supports both Swagger 2.0 and OpenAPI 3.0 specifications
- Customizable output through templates and configuration options
- Integrates well with popular build tools and frameworks
Cons
- Learning curve for advanced customization
- May require manual adjustments for complex API structures
- Generated code can be verbose for large APIs
- Limited support for certain OpenAPI features
Code Examples
- Basic usage with default options:
import { generateApi } from 'swagger-typescript-api';
generateApi({
name: 'MyApi',
url: 'https://api.example.com/swagger.json',
output: './src/api',
});
- Generating API with custom templates:
import { generateApi } from 'swagger-typescript-api';
generateApi({
name: 'CustomApi',
input: './swagger.yaml',
output: './src/api',
templates: './custom-templates',
});
- Using generated API client:
import { Api } from './src/api/MyApi';
const api = new Api();
const users = await api.users.getUsers();
Getting Started
-
Install the package:
npm install swagger-typescript-api --save-dev
-
Create a script in your
package.json
:{ "scripts": { "generate-api": "swagger-typescript-api -p ./swagger.json -o ./src/api" } }
-
Run the script to generate the API:
npm run generate-api
-
Import and use the generated API in your TypeScript/JavaScript code:
import { Api } from './src/api/Api'; const api = new Api(); // Use the API methods
Competitor Comparisons
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
Pros of swagger-codegen
- Supports multiple programming languages and frameworks
- Extensive community support and regular updates
- Offers a wide range of customization options
Cons of swagger-codegen
- Can be complex to set up and configure
- Generated code may require additional refinement
- Larger codebase and potentially slower generation process
Code comparison
swagger-codegen (Java):
public class PetApi {
private final ApiClient apiClient;
public PetApi() {
this(Configuration.getDefaultApiClient());
}
public PetApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
}
swagger-typescript-api (TypeScript):
export class PetApi extends HttpClient {
constructor(config?: Partial<ApiConfig>) {
super(config);
}
getPetById = (petId: number): Promise<Pet> => {
return this.request({ url: `/pet/${petId}`, method: "GET" });
};
}
swagger-codegen offers a more traditional object-oriented approach with separate classes for API client and endpoints, while swagger-typescript-api provides a more concise, TypeScript-friendly structure with inline method definitions.
swagger-codegen is better suited for projects requiring multi-language support and extensive customization, whereas swagger-typescript-api excels in TypeScript-specific environments with its simpler setup and more idiomatic output.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
Pros of openapi-generator
- Supports a wide range of programming languages and frameworks
- Offers more customization options and templates
- Has a larger community and more frequent updates
Cons of openapi-generator
- Can be more complex to set up and use
- May generate more boilerplate code
- Slower generation process for large API specifications
Code Comparison
swagger-typescript-api:
import { Api } from './api';
const api = new Api({
baseUrl: 'https://api.example.com',
});
const response = await api.users.getUser({ userId: 123 });
openapi-generator:
import { DefaultApi, Configuration } from './api';
const config = new Configuration({
basePath: 'https://api.example.com',
});
const api = new DefaultApi(config);
const response = await api.getUserById(123);
Summary
openapi-generator is a more versatile tool supporting multiple languages and offering extensive customization options. It has a larger community and more frequent updates. However, it can be more complex to set up and may generate more boilerplate code. swagger-typescript-api is more focused on TypeScript and generally easier to use, but with fewer features and language support. The choice between the two depends on project requirements, target language, and desired level of customization.
The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
Pros of NSwag
- Supports multiple programming languages and frameworks, not limited to TypeScript
- Offers more comprehensive tooling, including code generation for clients and servers
- Provides a user interface for API exploration and testing
Cons of NSwag
- Can be more complex to set up and configure due to its broader feature set
- May generate more verbose code compared to swagger-typescript-api
- Steeper learning curve for developers new to the tool
Code Comparison
NSwag (C# client generation):
var document = await OpenApiDocument.FromUrlAsync("https://api.example.com/swagger/v1/swagger.json");
var settings = new CSharpClientGeneratorSettings { ... };
var generator = new CSharpClientGenerator(document, settings);
var code = generator.GenerateFile();
swagger-typescript-api (TypeScript client generation):
import { generateApi } from 'swagger-typescript-api';
const { files } = await generateApi({
input: './swagger.json',
output: './src/api',
});
Both tools generate API clients from OpenAPI/Swagger specifications, but NSwag offers more language options and additional features, while swagger-typescript-api focuses on TypeScript and provides a simpler, more streamlined approach for TypeScript projects.
NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification
Pros of openapi-typescript-codegen
- Supports a wider range of OpenAPI versions (2.0, 3.0, and 3.1)
- Generates more comprehensive client code, including models, services, and core functionality
- Offers better TypeScript type inference and stricter typing
Cons of openapi-typescript-codegen
- Less flexible configuration options compared to swagger-typescript-api
- May generate more verbose code, which could lead to larger bundle sizes
- Lacks some advanced features like runtime data validation
Code Comparison
openapi-typescript-codegen:
export class PetsService {
public static getPets(): CancelablePromise<Array<Pet>> {
return __request(OpenAPI, {
method: 'GET',
url: '/pets',
});
}
}
swagger-typescript-api:
export const Api = {
getPets: () =>
httpClient.request<Pet[]>({
method: "GET",
url: "/pets",
}),
};
Both libraries generate TypeScript code for API clients, but openapi-typescript-codegen tends to create more structured and class-based code, while swagger-typescript-api generates more concise, functional-style code. The choice between them depends on your project's specific needs, preferred coding style, and the level of type safety required.
Generate TypeScript types from OpenAPI 3 specs
Pros of openapi-typescript
- Generates TypeScript types directly from OpenAPI schemas, without creating API client code
- Supports a wider range of OpenAPI/Swagger versions (2.0, 3.0, and 3.1)
- Offers a more lightweight and focused approach, ideal for projects that only need type definitions
Cons of openapi-typescript
- Does not generate API client code, requiring additional setup for making API calls
- May require more manual work to integrate with existing codebases or frameworks
- Limited customization options compared to swagger-typescript-api
Code Comparison
openapi-typescript:
import { paths } from './api';
type UserResponse = paths['/users/{userId}']['get']['responses']['200']['content']['application/json'];
swagger-typescript-api:
import { Api } from './api';
const api = new Api();
const user = await api.users.getUserById(userId);
Summary
openapi-typescript focuses on generating accurate TypeScript types from OpenAPI schemas, providing a lightweight solution for type-safe API interactions. It supports multiple OpenAPI versions but requires additional setup for making API calls. swagger-typescript-api, on the other hand, generates both types and API client code, offering a more comprehensive solution out of the box but with potentially less flexibility in certain scenarios.
Generate TypeScript types from OpenAPI 3 specs
Pros of openapi-typescript
- Generates TypeScript types directly from OpenAPI schemas, without creating API client code
- Supports a wider range of OpenAPI/Swagger versions (2.0, 3.0, and 3.1)
- Offers a more lightweight and focused approach, ideal for projects that only need type definitions
Cons of openapi-typescript
- Does not generate API client code, requiring additional setup for making API calls
- May require more manual work to integrate with existing codebases or frameworks
- Limited customization options compared to swagger-typescript-api
Code Comparison
openapi-typescript:
import { paths } from './api';
type UserResponse = paths['/users/{userId}']['get']['responses']['200']['content']['application/json'];
swagger-typescript-api:
import { Api } from './api';
const api = new Api();
const user = await api.users.getUserById(userId);
Summary
openapi-typescript focuses on generating accurate TypeScript types from OpenAPI schemas, providing a lightweight solution for type-safe API interactions. It supports multiple OpenAPI versions but requires additional setup for making API calls. swagger-typescript-api, on the other hand, generates both types and API client code, offering a more comprehensive solution out of the box but with potentially less flexibility in certain scenarios.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Swagger TypeScript API
- Support for OpenAPI 3.0, 2.0, JSON and YAML
- Generate the API Client for Fetch or Axios from an OpenAPI Specification
Any questions you can ask here
Examples
All examples you can find here
Usage
You can use this package in two ways:
CLI
npx swagger-typescript-api generate --path ./swagger.json
Or install locally in your project:
npm install --save-dev swagger-typescript-api
npx swagger-typescript-api generate --path ./swagger.json
Library
npm install --save-dev swagger-typescript-api
import * as path from "node:path";
import * as process from "node:process";
import { generateApi } from "swagger-typescript-api";
await generateApi({ input: path.resolve(process.cwd(), "./swagger.json") });
For more detailed configuration options, please consult the documentation.
Mass media
- 5 Lessons learned about swagger-typescript-api
- Why Swagger schemes are needed in frontend development ?
- Migration en douceur vers TypeScript (French)
- swagger-typescript-api usage (Japanese)
License
Licensed under the MIT License.
Top Related Projects
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification
Generate TypeScript types from OpenAPI 3 specs
Generate TypeScript types from OpenAPI 3 specs
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot