Installations
npm install swaggie
Developer Guide
Typescript
Yes
Module System
CommonJS
Min. Node Version
>=18.0.0
Node Version
20.15.1
NPM Version
10.7.0
Score
67.4
Supply Chain
98
Quality
83.8
Maintenance
100
Vulnerability
99.3
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (84.82%)
EJS (13.99%)
JavaScript (1.2%)
Developer
Download Statistics
Total Downloads
202,063
Last Day
16
Last Week
435
Last Month
2,939
Last Year
48,451
GitHub Statistics
22 Stars
439 Commits
9 Forks
5 Watching
3 Branches
17 Contributors
Package Meta Information
Latest Version
1.0.1
Package Id
swaggie@1.0.1
Unpacked Size
81.07 kB
Size
21.31 kB
File Count
43
NPM Version
10.7.0
Node Version
20.15.1
Publised On
14 Jul 2024
Total Downloads
Cumulative downloads
Total Downloads
202,063
Last day
-76.8%
16
Compared to previous day
Last week
-20.8%
435
Compared to previous week
Last month
-8.2%
2,939
Compared to previous month
Last year
-20.1%
48,451
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Swaggie
Generate Typescript code from an OpenAPI 3.0 document, so that accessing REST API resources from the client code is less error-prone, static-typed and just easier to use long-term.
You can take a look at the Examples section down below.
Project is based and inspired by OpenApi Client.
Features
- Generate TypeScript code from OpenAPI 3.0 spec
- Supports
fetch
,axios
,xior
,SWR + axios
,Angular 1
,Angular 2+
templates. It's flexible. - Possible to create your own template that works with your existing codebase
- It's a dev tool that generates code, so it's not a runtime dependency
- Support for
allOf
,oneOf
,anyOf
and$ref
in schemas - Support for different types of enums
- Support for different content types
- JSDoc comments for generated code
- Small library size and very small and tree-shakable output that is all placed in one file
- OpenAPI 3.1 is partially supported (mostly enums, more to come)
Install
In your project
npm install swaggie --save-dev
Or globally to run CLI from anywhere
npm install swaggie -g
OpenAPI versions
Swaggie from version 1.0 supports OpenAPI 3.0 (and some features of 3.1). Swagger or OpenAPI 2.0 documents are not supported anymore, but you have few options how to deal with it:
- (preferred) From your backend server generate OpenAPI 3.0 spec instead of version 2 (samples are updated to use OpenAPI 3.0)
- Convert your OpenAPI 2.0 spec to 3.0 using swagger2openapi tool (or something similar)
- If you can't do that for any reason, you can stick to
Swaggie v0.x
. But upgrade is suggested
Please note that OpenAPI 3.0 is a major spec upgrade and it's possible that there will be some breaking changes in the generated code. I have tried my best to minimize the impact, but it was not possible to avoid it completely.
More info about breaking changes can be found in the Releases.
CLI
Usage: swaggie [options]
Options:
-V, --version output the version number
-c, --config <path> The path to the configuration JSON file. You can do all the set up there instead of parameters in the CLI
-s, --src <url|path> The url or path to the Open API spec file
-o, --out <filePath> The path to the file where the API would be generated. Use stdout if left empty
-b, --baseUrl <string> Base URL that will be used as a default value in the clients (default: "")
-t, --template <string> Template used forgenerating API client. Default: "axios"
--preferAny Use "any" type instead of "unknown" (default: false)
--servicePrefix <string> Prefix for service names. Useful when you have multiple APIs and you want to avoid name collisions (default: "")
--allowDots <bool> Determines if dots should be used for serialization object properties
--arrayFormat <format> Determines how arrays should be serialized (choices: "indices", "repeat", "brackets")
-h, --help display help for command
Sample CLI usage using Swagger's Pet Store:
1swaggie -s https://petstore3.swagger.io/api/v3/openapi.json -o ./client/petstore.ts
swaggie
outputs TypeScript that is somehow formatted, but it's far from perfect. You can adjust the generated code by prettifying output using your preferred beautify tool using your repo's styling guidelines. For example involving prettier
looks like this:
1swaggie -s $URL -o ./client/petstore.ts && prettier ./client/petstore.ts --write`
And this can be easily automated (in the npm scripts for example)
Configuration File
Instead of providing all required flags from the command line you can alternatively create a new JSON file where you can fill up all settings.
Sample configuration looks like this:
1{ 2 "$schema": "https://raw.githubusercontent.com/yhnavein/swaggie/master/schema.json", 3 "out": "./src/client/petstore.ts", 4 "src": "https://petstore3.swagger.io/api/v3/openapi.json", 5 "template": "axios", 6 "baseUrl": "/api", 7 "preferAny": true, 8 "servicePrefix": "", 9 "dateFormat": "Date", // "string" | "Date" 10 "queryParamsSerialization": { 11 "arrayFormat": "repeat", // "repeat" | "brackets" | "indices" 12 "allowDots": true 13 } 14}
Templates
The following templates are bundled with Swaggie:
axios Default template. Recommended for React / Vue / similar frameworks. Uses axios
xior Lightweight and modern alternative to axios. Uses [xior](https://github.com/suhaotian/xior#intro)
swr-axios Template that embraces SRW for GET requests and as a fallback uses axios.
fetch Template similar to axios, but with fetch API instead. Recommended for React / Vue / similar frameworks
ng1 Template for Angular 1 (this is for the old one)
ng2 Template for Angular 2+ (uses HttpClient, InjectionTokens, etc)
If you want to use your own template, you can use the path to your template for the -t
parameter:
1swaggie -s https://petstore3.swagger.io/api/v3/openapi.json -o ./client/petstore --template ./my-swaggie-template/
Usage – Integrating into your project
Let's assume that you have a PetStore API as your REST API and you are developing a client app written in TypeScript that will consume this API.
Instead of writing any code by hand for fetching particular resources, we will let Swaggie do it for us.
Query Parameters Serialization
When it comes to use of query parameters then you might need to adjust the way these parameters will be serialized, as backend server you are using expects them to be in a specific format. Thankfully in Swaggie you can specify how they should be handled. If you won't provide any configuration, then Swaggie will use the defaults values expected in the ASP.NET Core world.
For your convenience there are few config examples to achieve different serialization formats for an object { "a": { "b": 1 }, "c": [2, 3] }
:
Expected Format | allowDots | arrayFormat |
---|---|---|
?a.b=1&c=2&c=3 | true | repeat |
?a.b=1&c[]=2&c[]=3 | true | brackets |
?a.b=1&c[0]=2&c[1]=3 | true | indices |
?a[b]=1&c=2&c=3 | false | repeat |
?a[b]=1&c[]=2&c[]=3 | false | brackets |
?a[b]=1&c[0]=2&c[1]=3 | false | indices |
Once you know what your backend expects, you can adjust the configuration file accordingly: (below are default values)
1{ 2 "queryParamsSerialization": { 3 "arrayFormat": "repeat", 4 "allowDots": true 5 } 6}
Code Quality
Please note that it's recommended to pipe Swaggie command to some prettifier like
prettier
,biome
ordprint
to make the generated code look not only nice, but also persistent. Because Swaggie relies on a templating engine, whitespaces are generally a mess, so they may change between versions.
Suggested prettiers
prettier - the most popular one
1prettier ./FILE_PATH.ts --write
biome - the super fast one
1biome check ./FILE_PATH.ts --apply-unsafe
You are not limited to any of these, but in our examples we will use Prettier. Please remember that these tools needs to be installed first and they need a config file in your project.
Example
Let's run swaggie
against PetStore API and see what will happen:
1swaggie -s https://petstore3.swagger.io/api/v3/openapi.json -o ./api/petstore.ts && prettier ./api/petstore.ts --write
1// ./api/petstore.ts 2 3import Axios, { AxiosPromise } from 'axios'; 4const axios = Axios.create({ 5 baseURL: '/api', 6 paramsSerializer: (params) => 7 encodeParams(params, null, { 8 allowDots: true, 9 arrayFormat: 'repeat', 10 }), 11}); 12 13/** [...] **/ 14 15export const petClient = { 16 /** 17 * @param petId 18 */ 19 getPetById(petId: number): AxiosPromise<Pet> { 20 let url = `/pet/${encodeURIComponent(`${petId}`)}`; 21 22 return axios.request<Pet>({ 23 url: url, 24 method: 'GET', 25 }); 26 }, 27 28 // ... and other methods ... 29};
When we have that we can write some domain code and use this auto-generated classes:
1// app.ts 2 3import { petClient } from './api/petClient'; 4 5petClient.getPetById(123).then((pet) => console.log('Pet: ', pet));
If Petstore owners decide to remove method we use, then after running swaggie
again it will no longer be present in the petClient
class. This will result in the build error, which is very much appreciated at this stage.
Without this approach, the error would be spotted by our end-user and he/she would not appreciate it at all!
Server config
You might wonder how to set up server to fully utilize Swaggie's features. For that I've added a samples/
folder with sample configurations.
Server is not necessary to use Swaggie. Swaggie cares only about the JSON/yaml file with the Open API spec, but for your development purpose you might want to have a server that can serve this file automatically from the actual endpoints.
Using Swaggie programmatically
1const swaggie = require('swaggie'); 2swaggie 3 .genCode({ 4 src: 'https://petstore3.swagger.io/api/v3/openapi.json', 5 out: './api/petstore.ts', 6 }) 7 .then(complete, error); 8 9function complete(spec) { 10 console.info('Service generation complete'); 11} 12 13function error(e) { 14 console.error(e.toString()); 15}
Notes
Supported | Not supported |
---|---|
OpenAPI 3 | Swagger, Open API 2.0 |
allOf , oneOf , anyOf , $ref to schemas | not |
Spec formats: JSON , YAML | Very complex query params |
Extensions: x-position , x-name , x-enumNames , x-enum-varnames | Multiple response types (one will be used) |
Content types: JSON , text , multipart/form-data | Multiple request types (one will be used) |
Content types: application/x-www-form-urlencoded , application/octet-stream | References to other spec files |
Different types of enum definitions (+ OpenAPI 3.1 support for enums) | |
Paths inheritance, comments (descriptions) | |
Getting documents from remote locations or as path reference (local file) | |
Grouping endpoints by tags + handle gracefully duplicate operation ids |
Used by
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
1 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
Reason
Found 0/6 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/node.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/yhnavein/swaggie/node.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/yhnavein/swaggie/node.yml/master?enable=pin
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 25 are checked with a SAST tool
Score
3.7
/10
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More