Generate an Angular Typescript API Client with Swagger Codegen

Introduction 
 
Consuming an API in an angular application is a very easy job. Generally, we developers use the following approach to consume an API in the angular application:
  • Create a common service that will have all the API interaction methods (ex. get, put, post and delete.)
  • Create an application functionality for a specific service (ex. user service, contact service which will call the common service to make an API call.)
Is there any issue with this approach? No, I wouldn't say there is an issue, but creating a client is a better approach. Just think about your C#, Java or any other language application where you can directly download a package/jar/dll and start using those methods directly. It gives you:
  • Better Intellisense.
  • Every time you call/use the method, there is no chance you misspell the method name or property name.
  • All the classes required are already created, you don't have to create manually. When I say creating a class, I mean when you call your post method of the API and you need to pass an object. You must create a class or interface in your angular application that will be passed in the post request.

Wouldn't it be better if you had an API client for your angular application so that you could directly call the API method without managing or creating a common service and the replicate API model creation?

You will be happy to know that there is a way you can create an API client and consume it directly in your angular application. You must follow the below steps:

Step 1: Install swagger in your API to get swagger.json file.

Installing swagger in your Web APIs a very straightforward process. You can do that by following my blog, Implement swagger in asp net core web API

Step 2: Get the Jar file.

You need a Swagger Codegen jar file to generate the client. There are a couple of ways to get that:

  1. Download jar file from the MVN repository. Here is the link.
  2. Clone the Swagger Codegen repo from git hub and run the MVN clean package command. You must have Maven installed in your system.

I would recommend directly downloading the jar file. Since you don’t have any changes to Swagger Codegen repo, it will generate the same jar which you can download from the MVN repository.

Step 3: Generate the angular client

From steps 1 and 2, we now have the swagger.json and .jar files. Now, we can run the following command to generate the angular client:

  1. java -jar "<path-of-jar-file>" generate -i <url-of-swagger-spec-file> -l typescript-angular -o <relative-output-path> -c <path-of-option-file>  
Please note that the path here is the relative path from your current folder as shown below. An example command would look like the following: 
 
 
An example command would look like the following:
  1. java -jar "Helper/swagger-codegen-cli-2.4.10.jar" generate -i http://localhost:65099/swagger/DemoAPI/swagger.json -l typescript-angular -o ClientGeneratedForSwaggerCodegen -c Helper/options.json  
As you can see:
 
 -i: used for specifying the swagger.json file URL 
 -l: used for specifying the language.
-o: used for specifying output folder.
-c: it's optional for specifying other options like node version, angular version, etc.
 
An example of an option.json file would look like the following:
  1. {  
  2.    "npmName""sample-webapi",  
  3.    "ngVersion":"6.0.0"  
  4. }  
Here, the ngVersion will be the angular version in the generated client. 
After running the command you should see the complete angular application of your API in your output folder, as shown below. It is ClientGeneratedForSwaggerCodegen. 

Step 4: Consuming the client in your front-end application

Generate the final consumable client 

If you look at the generated output, it's a complete application. Generally, when you use a client, it is a compiled version of source code, not the actual source code. So, in the same way, this application needs to be compiled before being used as a client. There are a couple of ways you can compile this: 
  1. Build the angular application using the npm run build command.
  2. Compile the angular application using a typescript compiler, which will generate the type definition files *.d.ts files. The command to compile is "./node_modules/.bin/tsc"
Note: Make sure you are in the generated output folder and already ran the npm install command.

I recommend the second approach, and here is why:
  • If you observe carefully, the output folder doesn't have a component or template, it just has services. Publishing this will generate a lot of code that we probably don't need.
  • The size of the output bundle will be less if it's compiled using a typescript compiler.
After running the "./node_modules/.bin/tsc" command you will see a dist folder in the ClientGeneratedForSwaggerCodegen. you will find the compiled code of the generated angular application as shown below:
 
Now, this is the client you can consume in your front end angular application. 

Using the final generated client in your front end angular application

Use the below steps:

  • Import the following modules in app.module.ts. Please note that I have copied the output files in the sample-webapi folder and put it into the node_module folder.
  1. Import { HttpClientModule } from '@angular/common/http';  
  2. Import { ApiModule, BASE_PATH } from 'sample-webapi';  
  • Add HttpClientModule, ApiModule, in import section
  • Add the following in the provider, you need to change URL of your API application.     
  1. { provide: BASE_PATH, useValue: 'http://localhost:65099' }   
Finally your app.module.ts should look like:
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4. import { ApiModule, BASE_PATH } from 'sample-webapi';  
  5.   
  6. import { AppRoutingModule } from './app-routing.module';  
  7. import { AppComponent } from './app.component';  
  8.   
  9. @NgModule({  
  10. declarations: [  
  11. AppComponent,  
  12. ],  
  13. imports: [  
  14. BrowserModule,  
  15. AppRoutingModule,  
  16. HttpClientModule,  
  17. ApiModule,  
  18. ],  
  19. providers: [{ provide: BASE_PATH, useValue: 'http://localhost:65099' }],  
  20. bootstrap: [AppComponent]  
  21. })  
  22. export class AppModule { }  
Now you are good to use the User API in your agnular application. Below is one example  
  1. import { Component, OnInit } from '@angular/core';  
  2. import { UserService } from 'sample-webapi';  
  3.   
  4. @Component({  
  5. selector: 'app-root',  
  6. templateUrl: './app.component.html',  
  7. styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent implements OnInit {  
  10. title = 'SampleClientApp';  
  11.   
  12. constructor(private userService: UserService) {  
  13. }  
  14.   
  15. ngOnInit(): void {  
  16. this.userService.getUsers().subscribe(elem => {  
  17. console.log(elem);  
  18. });  
  19. }  
  20. }  
I hope that now you can see the benifit of generating the client and know how to generate one using Swagger Codegen.