Auto-generate models/types and web clients in the Angular app with OpenAPI Specification

Shubham Nikam
3 min readAug 14, 2023

--

I’ll provide you with a concise explanation of how to utilize the ng-openapi-gen package within an Angular application to create types, models, and web clients. To illustrate this, I'll draw examples from my own project, the URL shortener. Below, you'll find the automatically generated models and services produced by ng-openapi-gen.

I’ll try to brief you on how to generate the types/models & web clients using ng-openapi-gen package in the angular app. For reference, I’ll use the code from my url-shortener project. following are the auto-generated models & services using ng-openapi-gen.

#1: Setup

Create an angular app & install ng-openapi-gen package with the following command

npm i -g ng-openapi-gen

#2: Create an OpenAPI spec file (JSON/yml)

If your backend is ready & integrated with swagger/open API then you can easily get it from there else you will have to create your own spec file using openAPI docs. use swagger editor.

In my case, I had a project created in the dotnet core backend with Swagger integrated.

spec file

Refer to my spec file from the Url-Shortener project.

#3: Generate the models & web client API

Use ng-openapi-gen CLI command to generate models & web clients.

# use following command:
ng-openapi-gen --input <path-to-openapi-json> --output <angular-app-path>/src/app/api

#
for example:
ng-openapi-gen --input src/app/core/api/template/swagger.json --output src/app/core/api

You’ll see something like the following in your directory structure/editor.

#4: Update config rootUrl

To update the rootUrl, include generated module in AppModule’s imports section (assuming AppModule is the default module) & pass your API url as config. (use environment file). Refer app.module.ts

ApiModule.forRoot({ rootUrl: environment.API_ENDPOINT })

#5: Create a Component & call REST endpoint using a service from API

import service from ~api/services/<your-service> in components &call the required method & subscribe to it. Refer service call from the component.

I hope you find something useful. If you like this article then please clap for me…👏👏👏 Check out my GitHub profile…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response