Why Swagger schemes are needed in frontend development ?
Tags: webdev, frontend, typescript, swagger
Published: 2020-03-24 19:12:21

Hi everyone! 👋  

Question which I ask in title of this article is quite actual even for modern projects because in frontend development we use Swagger not at 100%.  

In Russian big IT companies where I worked even not known about Swagger (That's truth) and that's not good. Current company where I work build all interaction between client and server via Swagger schemas. With Swagger client gets type checking and all endpoints.  

Some teams when being developing frontend project makes manually all requests to the server, declaring types and endpoints looking at Swagger schema. It is not needed to do because already have ~~ready solutions~~ codogenerators for that.  

## Codegenerators 🖨  
![](https://media.giphy.com/media/26tn33aiTi1jkl6H6/giphy.gif)
In company where I currently work use own frontend code generator API module based on Swagger schema, because of this I can't use it for personal use, and search ready solutions was so hard (may be I just wanted to create own)  

For example what I found in npm:  
- [api-client-generator](https://www.npmjs.com/package/api-client-generator) - generates Angular service but what if I have React application ?  
- [swagger-taxos-codegen](https://www.npmjs.com/package/swagger-taxos-codegen) - generates TypeScript Api module, but it requires [`axios`](https://github.com/axios/axios) in project.  
- [@ps-aux/swagger-codegen](https://www.npmjs.com/package/@ps-aux/swagger-codegen) - May be that's what I'm looking for but it not have any description. What if that is virus ? :)  
- [swagger-api-ts-generator](https://www.npmjs.com/package/swagger-api-ts-generator) - I'm not sure that this is for frontend development  
- [@openapitools/openapi-generator-cli](https://www.npmjs.com/package/@openapitools/openapi-generator-cli) - This really helpful tool, which supports different generator cases like `Dart`, `Angular` or even `Flow`. But it generates big count of output files what don't needed to me (`typescript-fetch` generator) and also I was tempted to create own tool  

This and all other ready solutions were not suitable for my needs, because I wanted to get API module from tool, which will use [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for generating requests and will not have anything extra like Angular service or axios.  

In this way I start working at own codegenerator and gave him most simple and obvious name - [`swagger-typescript-api`](https://www.npmjs.com/package/swagger-typescript-api)

## swagger-typescript-api 🎉  

{% github acacode/swagger-typescript-api %}  

I'll tell right away about his benefits over other alternatives:  
1. Supports **Swagger 2.0**, **OA 3.0**, and also file formats `json`, `yaml`  
2. Generated code not have any additional dependencies (like `axios`). Just generate API module and enjoy.  
3. Good types parsing from schema.  
4. Have extra features to use generated code in NodeJS environment.  
5. Flexible - we can override any method or property of generated API class.  
6. Not highly specialized - It could work for Angular applications and for React  
7. Good support - I have [Slack](https://join.slack.com/t/acacode/shared_invite/enQtOTQ5ODgyODQzMzYwLWYxOGI1MzQ3Yzg1ZWI5ZTI5NzNiZjExZTE5OWI1YjQ4NjBiNTk4NWVlNjM5YmU1ZWI2ZDkyMzZkZGIxNjA5NTQ) channel, where I'll answer at any questions based this tool.  
8. Ability to use custom codegenerator templates based on [ETA](https://eta.js.org/docs/syntax) syntax  

### For what it neeeded ? 🤷‍♂️  
Before at all it's type checking, which in my humble opinion very important in frontend development. TypeScript will give information that you send wrong typed structure to the server and it should be fixed.  
Next case it is no needs to write endpoints manually. It should to reduce count of problems of interaction between client and server.  

### How to use 🚀  
It's real simple. Just put it to console:  
```sh
npx swagger-typescript-api -p path-or-url/to-your-swagger/schema.json -o src
```  
```
  -p, --path <path>             path/url to swagger scheme
  -o, --output <output>         output path of typescript api file (default: "./")
  -n, --name <name>             name of output typescript api file (default: "Api.ts")
  -t, --templates <path>        path to folder containing templates
  -d, --default-as-success      use "default" response status code as success response too.
                                some swagger schemas use "default" response status code
                                as success response type by default. (default: false)
  -r, --responses               generate additional information about request responses
                                also add typings for bad responses (default: false)
  --union-enums                 generate all "enum" types as union types (T1 | T2 | TN) (default: false)
  --route-types                 generate type definitions for API routes (default: false)
  --no-client                   do not generate an API class
  --enum-names-as-values        use values in 'x-enumNames' as enum values (not only as keys) (default: false)
  --js                          generate js api module with declaration file (default: false)
  --extract-request-params      extract request params to data contract (default: false)
                                Also combine path params and query params into one object
  --module-name-index <number>  determines which path index should be used for routes separation (default: 0)
                                (example: GET:/fruites/getFruit -> index:0 -> moduleName -> fruites)
  --module-name-first-tag       splits routes based on the first tag
  --modular                     generate separated files for http client, data contracts, and routes (default: false)
  --disableStrictSSL            disabled strict SSL (default: false)
  --clean-output                clean output folder before generate api. WARNING: May cause data loss (default: false)
  --axios                       generate axios http client (default: false)
  --single-http-client          Ability to send HttpClient instance to Api constructor (default: false)
  --silent                      Output only errors to console (default: false)
  --default-response <type>     default type for empty response schema (default: "void")
```

For example:  
```
npx swagger-typescript-api -p http://js2me.pw/api/v1/swagger.json -o src
```
![](https://dev-to-uploads.s3.amazonaws.com/i/pprzog94bv2g8mvni249.png)  
![](https://dev-to-uploads.s3.amazonaws.com/i/8ym24248wbqpurcw7ifl.png) 
![](https://media.giphy.com/media/UShTMzewjPIIRA0QDB/giphy.gif)   



More examples you can find [**here**](https://github.com/acacode/swagger-typescript-api/tree/master/tests)  

Thanks for reading!