Generate OpenAPI Angular Client
Connect angular frontend via generated Services to your backend.
Angular is a popular web application framework that allows developers to build dynamic and interactive user interfaces. TypeScript is a strongly-typed superset of JavaScript that provides enhanced tooling and error checking for web development. OpenAPI, formerly known as Swagger, is a specification for describing RESTful APIs in a standardized way.
One powerful tool that can streamline the development process when working with Angular and TypeScript is generating an OpenAPI client. This article will explore the purpose and benefits of generating an Angular-Typescript OpenAPI client, which can be a time-saving and efficient way to integrate APIs into Angular applications.
By leveraging the OpenAPI specification, developers can automatically generate Angular-Typescript client code that serves as a bridge between the Angular application and the API server. This generated client code provides a strongly-typed interface to the API, allowing developers to call API endpoints and handle responses in a more efficient and type-safe manner.
The benefits of generating an Angular-Typescript OpenAPI client are numerous. It helps in reducing manual coding efforts, eliminates the need to manually maintain API endpoint URLs, and provides a single source of truth for the API contract, ensuring that the client code stays in sync with the API documentation. Additionally, the generated client code provides type checking, autocompletion, and error checking, which can improve the overall quality and stability of the Angular application.
In this article, we will delve into the process of generating an Angular-Typescript OpenAPI client and explore how it can be a valuable tool for developers when working with APIs in Angular applications. We will also discuss some best practices and tips for using generated OpenAPI clients effectively in Angular projects.
What are we going to do?
In this post, I want to show you how to generate an Angular-Typescript OpenAPI client and store it in a git repository as an npm package.
If you don’t know how to define OpenAPI Schema you may want to check out my other post or some other resource before you read this post.
Our workflow will look like this:
We use the openapi.json from here.
Before running the openapi-generator-cli command you need to install the Java Runtime (JRE) and Node.js.
First, we need to install the npm package openapi-generator globally. Open up your command line and execute the following command:
# install the latest version of "openapi-generator-cli"
npm install @openapitools/openapi-generator-cli -g
Generate the Angular-Typescript OpenAPI client from your command line :
# switch into a folder where you want to create the client
cd angular-openapi-client# generate the client
openapi-generator-cli generate -g typescript-angular -i ./openapi.json -o ./ --additional-properties npmName=slim-api,snapshot=false,ngVersion=10.0.0,npmVersion=0.0.1
In the openapi-generator command, we generate a typescript-angular client from file openapi.json, we add the additional properties so the generator will add a package.json file so we can load this later on into our angular project as an npm dependency.
On the left, you see the most important parts of our generated client.
The folder api will hold all of our services, the services are equivalent to the tags we have in our openapi.json
“tags”: [“user”]
The folder model will hold the objects we defined in section “schemas” in our openapi.json
In the file .openapi-generator-ignore you can add files and folders that should not be overwritten by the generator.
Now we publish our npm package on Github, you can choose another solution if you like. Execute the following command on the command line:
# switch into the folder where you generated the client
cd angular-openapi-client# initalize a git repository, add files, commit them and publish
git init
git add --a
git commit -m "inital commit"
git remote add origin git@github.com:pguso/openapi-typescript-angular-client.git
git push -u origin master
You find the repository here https://github.com/pguso/openapi-typescript-angular-client
We made our client available in a separate git repository. Next, we set up an angular project and use our services and models.
You need to have the Angular CLI installed https://cli.angular.io/, switch to the command line, and execute the following command:
# setup a new angular project
ng new angular-openapi-client-demo
It’s up to you which answers you give to the questions you are prompted in the command line, for our simple example the answers are not necessary.
Now we install the angular client from https://github.com/pguso/openapi-typescript-angular-client into our newly created angular project. Execute the command:
npm i git+ssh://github.com:pguso/openapi-typescript-angular-client.git
You will see a new entry in your package.json under dependencies:
"dependencies": {
...
"slim-api": "git+ssh://git@github.com/pguso/openapi-typescript-angular-client.git",
...
},
In the file tsconfig.app.json we need to include the slim-api package because it’s holding typescript files so we need to inform typescript to compile these files.
...# we add the slim-api node module to our include list
"include": [
"src/**/*.d.ts",
"node_modules/slim-api/**/*.ts"
]...
We add the HttpClientModule to our AppModule at src/app/app.module.ts so we can communicate with our backend, the generated OpenAPI services use under the hood the HttpClient
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Nice, now we start the angular project with the serve command:
ng serve
I will delete the content of the file src/app/app.component.html completely. So the site under http://localhost:4200 will be empty for now.
I changed the content of the AppComponent in path src/app/app.component.ts to the following:
import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
import {User, UserService} from 'slim-api';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
users$: Observable<User[]>;
constructor(private userService: UserService) {}
ngOnInit(): void {
this.users$ = this.userService.getUsers();
}
}
The relevant parts for the communication with our API are bold.
- import the service and model from the node package
- declare the variable that will hold the response from our API, this will be always an Observable of our models, in this example, the Observable will return an array of User objects
- inject the service into our component
- call the getUsers method that will load all users and save it into our declared variable this.users$
We switch to the file src/app/app.component.html and add the following code:
<h3>User list</h3>
<ul *ngFor="let user of users$ | async">
<li>{{user.username}}</li>
</ul>
With the async pipe we unwrap the values from the observable and get it back as an array of users, with ngFor we iterate over this array and just show the usernames as a list.
If you are getting typescript errors within the generated services on project start and using version 5.2.1 of the OpenAPI generator, a temporary fix is using version 5.1.0 with the following command:
openapi-generator-cli version-manager set 5.1.0
You find the code to this tutorial here https://github.com/pguso/angular-openapi-client-demo
I hope you enjoyed this tutorial and could easily follow my thoughts, if you miss something or an explanation was not clear enough don’t hesitate to ask!