All Projects → yhnavein → swaggie

yhnavein / swaggie

Licence: MIT license
Tool for generating TypeScript services for given Swagger API endpoints

Programming Languages

typescript
32286 projects
EJS
674 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to swaggie

CreateAPI
Delightful code generator for OpenAPI specs
Stars: ✭ 176 (+877.78%)
Mutual labels:  openapi, code-generation
php-json-schema-model-generator
Creates (immutable) PHP model classes from JSON-Schema files including all validation rules as PHP code
Stars: ✭ 36 (+100%)
Mutual labels:  openapi, code-generation
openapi-client
Generate ES6 or Typescript service integration code from an OpenAPI 2 spec
Stars: ✭ 92 (+411.11%)
Mutual labels:  openapi, code-generation
Quenya
Quenya is a framework to build high-quality REST API applications based on extended OpenAPI spec
Stars: ✭ 121 (+572.22%)
Mutual labels:  openapi, code-generation
Nswag
The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
Stars: ✭ 4,825 (+26705.56%)
Mutual labels:  openapi, nswag
Goa
Design-based APIs and microservices in Go
Stars: ✭ 4,493 (+24861.11%)
Mutual labels:  openapi, code-generation
Unchase.OpenAPI.Connectedservice
📜 Visual Studio extension to generate OpenAPI (Swagger) web service reference.
Stars: ✭ 69 (+283.33%)
Mutual labels:  openapi, nswag
Swaggen
OpenAPI/Swagger 3.0 Parser and Swift code generator
Stars: ✭ 385 (+2038.89%)
Mutual labels:  openapi, code-generation
Gnostic
A compiler for APIs described by the OpenAPI Specification with plugins for code generation and other API support tasks.
Stars: ✭ 870 (+4733.33%)
Mutual labels:  openapi, code-generation
oag
Idiomatic Go (Golang) client package generation from OpenAPI documents
Stars: ✭ 51 (+183.33%)
Mutual labels:  openapi, code-generation
ArchitectNow.ApiStarter
Sample ASP.NET Core 2 API Setup used by ArchitectNow for corresponding workshop presentations
Stars: ✭ 35 (+94.44%)
Mutual labels:  nswag
apitte-openapi
👪 OpenAPI specification for Apitte stack
Stars: ✭ 15 (-16.67%)
Mutual labels:  openapi
sanic-ext
Extended Sanic functionality
Stars: ✭ 26 (+44.44%)
Mutual labels:  openapi
solregex
Regex compilation to Solidity
Stars: ✭ 37 (+105.56%)
Mutual labels:  code-generation
swagger-editor-validate
This GitHub Actions validates OpenAPI (OAS) definition file using Swagger Editor.
Stars: ✭ 30 (+66.67%)
Mutual labels:  openapi
cookbook
VueJS + NodeJS Evergreen Cookbook
Stars: ✭ 440 (+2344.44%)
Mutual labels:  openapi
cakephp-swagger-bake
Automatically generate OpenAPI, Swagger, and Redoc documentation from your existing CakePHP code.
Stars: ✭ 48 (+166.67%)
Mutual labels:  openapi
openapi4j
OpenAPI 3 parser, JSON schema and request validator.
Stars: ✭ 92 (+411.11%)
Mutual labels:  openapi
openapi-python-client
Generate modern Python clients from OpenAPI
Stars: ✭ 543 (+2916.67%)
Mutual labels:  openapi
oauth1-signer-ruby
Zero dependency library for generating a Mastercard API compliant OAuth signature.
Stars: ✭ 15 (-16.67%)
Mutual labels:  openapi
Swaggie logo

Swaggie

npm latest version NodeCI Snyk Vulnerabilities for GitHub Repo npm downloads npm bundle size npm install size

Generate ES6 or Typescript code from an OpenAPI 2.0 spec, 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.

Install

In your project

npm install swaggie --save-dev

Or globally to run CLI from anywhere

npm install swaggie -g

CLI

Usage: swaggie [options]

Options:

  -h, --help               output usage information
  -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
  -t, --template <string>  Template used forgenerating API client. Default: "axios"
  -o, --out <path>         The path to the file where the API would be generated
  -b, --baseUrl <string>   Base URL that will be used as a default value in the clients. Default: ""
  --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: ''
  --queryModels <bool>     Generate models for query string instead list of parameters. Default: false

Sample CLI usage using Swagger's Pet Store:

swaggie -s https://petstore.swagger.io/v2/swagger.json -o ./client/petstore/

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:

swaggie -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:

{
  "$schema": "https://raw.githubusercontent.com/yhnavein/swaggie/master/schema.json",
  "out": "./src/client/petstore.ts",
  "src": "https://petstore.swagger.io/v2/swagger.json",
  "template": "axios",
  "baseUrl": "/api",
  "preferAny": true,
  "servicePrefix": "",
  "queryModels": true,
  "dateFormat": "Date" // "string" | "Date"
}

Templates

The following templates are bundled with Swaggie:

axios     Default template. Recommended for React / Vue / similar frameworks. Uses axios
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:

swaggie -s https://petstore.swagger.io/v2/swagger.json -o ./client/petstore --template ./my-swaggie-template/

Code

const swaggie = require('swaggie');
swaggie
  .genCode({
    src: 'http://petstore.swagger.io/v2/swagger.json',
    out: './api/petstore.ts',
  })
  .then(complete, error);

function complete(spec) {
  console.info('Service generation complete');
}

function error(e) {
  console.error(e.toString());
}

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.

Please note that it's recommended to pipe Swaggie command to some prettifier like prettier or dprint 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

prettier ./FILE_PATH.ts --write

dprint - the superfast one

dprint fmt ./FILE_PATH.ts

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:

swaggie -s https://petstore.swagger.io/v2/swagger.json -o ./api/petstore.ts && prettier ./api/petstore.ts --write
// ./api/petstore.ts

import Axios, { AxiosPromise } from 'axios';
const axios = Axios.create({
  baseURL: '/api',
});

/** [...] **/

export const petClient = {
  /**
   * @param petId
   * @return Success
   */
  getPetById(petId: number): AxiosPromise<Pet> {
    let url = '/pet/{petId}';

    url = url.replace('{petId}', encodeURIComponent('' + petId));

    return axios.request<Pet>({
      url: url,
      method: 'GET',
    });
  },

  // ... and other methods ...
};

When we have that we can write some domain code and use this auto-generated classes:

// app.ts

import { petClient } from './api/petClient';

petClient.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.

ASP.NET Core + Nswag

ASP.NET Core + Swashbuckle

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.

Notes

If you are familiar with the client-code generators for the Swagger / OpenAPI standards then you might wonder why swaggie is better than existing tools. Currently the most popular alternative is an open-source NSwag.

Quick comparison table:

swaggie NSwag
- Written in node.js - Written in .NET
- Fast - Slow
- swaggie size - nswag size
- Easy to contribute to - Contributing hard
- Lightweight - Complicated templates
- Only features generating API clients for TS/JS - Many more features (but mostly for .NET apps)
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].