Generate Angular/Ionic client code from OpenAPI/Swagger REST API specifications

When you are developing a full stack application with REST API and Angular client, you will always find yourself writing model classes, Angular services again and again for existing backend REST API. This leads to duplicate efforts and maintenance issues.

Swagger-codegen package helps solve this exact problem.

In this story, we will see how to generate client code from swagger.json file.

Backend REST API

* This demo is built using .NET Core 2.2 version for building REST API. But you can use any other language/framework as long as you can generate OpenAPI/Swagger file from it.

  • Add Swashbuckle.AspNetCore package for generating OpenAPI information
  • In Startup.cs file update Configure() method with below code:

swagger-codegen generate -i swagger.json -l typescript-angular -o ng-client-demo/backend

It will generate models and Angular DI ready service in backend folder.


➜ backend git:(master) ✗ tree
.
├── api
│ ├── api.ts
│ └── todos.service.ts
├── api.module.ts
├── configuration.ts
├── encoder.ts
├── git_push.sh
├── index.ts
├── model
│ ├── models.ts
│ └── todoModel.ts
└── variables.ts

Angular client code setup

  • Install rxjs-compat package if required. npm i rxjs-compat --save
  • You can inject auto generated services in your application component and start using its methods.

Now you don’t need to write Models and Services again and again for your REST API. Just start using it!

Generating code for different clients

You can generate client code for below client languages by specifying -l <lang-code> parameter.

swagger-codegen generate -i <path-to-swagger.json> -l <lang-code> -o <output-path>

csharp
csharp-dotnet2
dynamic-html
html
html2
java
jaxrs-cxf-client
jaxrs-cxf
inflector
jaxrs-cxf-cdi
jaxrs-spec
jaxrs-jersey
jaxrs-di
jaxrs-resteasy-eap
jaxrs-resteasy
spring
nodejs-server
openapi
openapi-yaml
kotlin-client
kotlin-server
php
python
scala
scala-akka-http-server
swift3
swift4
typescript-angular

GitHub repository

Here is the source code for .Net Core REST API and Angular client code used for this story:

Cloud Solution Architect | Author | Full Stack Developer | https://www.linkedin.com/in/balram-chavan | https://www.hiretheauthor.com/balramchavan

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store