Simplifying API Consumption in Angular: Leveraging Auto-Generated Client Code

Saunak Surani
Widle Studio LLP
Published in
6 min readJul 24, 2023

Developing modern web applications often involves working with APIs to fetch and manipulate data. In Angular applications, the process of consuming APIs can be streamlined and made more efficient by using auto-generated client code. This approach saves time and reduces the chance of errors by automating the creation of service classes and API request handling.

In this article, we will explore how to use auto-generated client code to consume your API from an Angular app. We will walk through the steps to set up the auto-generation process, demonstrate how to make API calls using the generated client code, and discuss the benefits of adopting this approach. By the end of this article, you will have a solid understanding of how to leverage auto-generated client code to enhance your Angular app’s API consumption.

Table of Contents:

1. Understanding Auto-Generated Client Code
2. Setting Up the API and Generating the Client Code
2.1. Creating the API
2.2. Generating the Client Code
3. Implementing API Consumption in Angular
3.1. Installing Required Dependencies
3.2. Consuming the API Using Auto-Generated Client Code
4. Handling Authentication with Auto-Generated Client Code
5. Benefits of Auto-Generated Client Code
6. Conclusion

1. Understanding Auto-Generated Client Code

Auto-generated client code is a technique used to automatically generate TypeScript classes that act as wrappers for API endpoints. These classes are generated based on your API’s OpenAPI Specification (formerly known as Swagger). The OpenAPI Specification defines the structure and operations of your API, making it easier to create consistent and standardized client code.

By using tools like OpenAPI Generator or Swagger Codegen, you can automatically generate client code for Angular apps. This code includes service classes and model classes, simplifying the process of making API calls and handling API responses.

2. Setting Up the API and Generating the Client Code

In this section, we’ll start by creating a simple API and then generate the client code using the OpenAPI Generator. For demonstration purposes, we will use a fictional API that manages a collection of books.

2.1. Creating the API

For the sake of simplicity, we’ll create a basic RESTful API using Node.js and Express.js. Make sure you have Node.js and npm installed.

Step 1: Create a new directory for your API and initialize a new Node.js project:

mkdir book-api
cd book-api
npm init -y

Step 2: Install Express.js and create the main server file (index.js):

npm install express
touch index.js

Step 3: Open index.js and add the following code to set up a basic Express server:

// index.js
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());

let books = [
{ id: 1, title: 'Angular Basics', author: 'John Doe' },
{ id: 2, title: 'React in Action', author: 'Jane Smith' },
{ id: 3, title: 'Vue.js Essentials', author: 'Bob Johnson' },
];

app.get('/api/books', (req, res) => {
res.json(books);
});

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

In this simple API, we have a collection of books stored in memory. The `/api/books` endpoint returns the list of books in JSON format.

2.2. Generating the Client Code

Now that we have our API set up, we can generate the client code using the OpenAPI Generator. Install the generator using npm:

npm install @openapitools/openapi-generator-cli -g

Next, we need an OpenAPI Specification file for our API. For demonstration purposes, we’ll use a simplified version of the specification in YAML format:

# book-api-spec.yaml
openapi: 3.0.0
info:
title: Book API
version: 1.0.0
paths:
/api/books:
get:
summary: Get all books
operationId: getAllBooks
responses:
'200':
description: OK

Save this specification as `book-api-spec.yaml` in the root directory of your project.

Now, generate the client code using the OpenAPI Generator:

openapi-generator-cli generate -i book-api-spec.yaml -g typescript-angular -o ./client-code

This command will generate the client code and place it in the `client-code` directory.

3. Implementing API Consumption in Angular

With the auto-generated client code in place, we can now use it in our Angular app to consume the API. Let’s create an Angular app and integrate the generated client code.

3.1. Installing Required Dependencies

Step 1: Generate a new Angular app:

ng new book-app
cd book-app

Step 2: Install the required dependencies to use the generated client code:

npm install axios @openapitools/openapi-generator-cli @openapitools/openapi-generator-cli -D

3.2. Consuming the API Using Auto-Generated Client Code

In this section, we will demonstrate how to consume the API using the auto-generated client code in an Angular service.

Step 1: Copy the generated client code to the Angular app’s src/app folder:

cp -r ../client-code/* src/app/

Step 2: Create a new Angular service to interact with the API:

ng generate service book

Step 3: Open the generated service file (book.service.ts) and implement the service as follows:

// book.service.ts
import { Injectable } from '@angular/core
';
import { Configuration, BookControllerService, Book } from './api';
@Injectable({
providedIn: 'root',
})

export class BookService {
private bookController: BookControllerService;

constructor() {
const configuration = new Configuration();
this.bookController = new BookControllerService(configuration);
}

getAllBooks(): Promise<Book[]> {
return this.bookController.getAllBooks().toPromise();
}
}

In the service, we import the generated `Configuration` and `BookControllerService` from the auto-generated code. The `BookControllerService` provides methods to interact with the API’s `/api/books` endpoint, including the `getAllBooks` method.

Now, we can use this service in our components to fetch data from the API and display it in the Angular app.

4. Handling Authentication with Auto-Generated Client Code

In real-world scenarios, APIs often require authentication to access certain endpoints. With auto-generated client code, handling authentication becomes easier.

Typically, APIs require an access token or an API key for authentication. The generated client code allows you to set headers, including authentication tokens, for every API request. This can be done by modifying the `Configuration` instance used to initialize the service:

// book.service.ts
import { Injectable } from '@angular/core';
import { Configuration, BookControllerService, Book } from './api';
@Injectable({
providedIn: 'root',
})

export class BookService {
private bookController: BookControllerService;

constructor() {
const configuration = new Configuration({
basePath: 'https://your-api-base-url',
accessToken: 'your-access-token', // Replace with your actual token
});

this.bookController = new BookControllerService(configuration);
}
// Rest of the service code…
}

By setting the `accessToken` property in the `Configuration`, the client code will automatically include the access token in every API request.

5. Benefits of Auto-Generated Client Code

Using auto-generated client code to consume your API in an Angular app offers several benefits:

1. Time Savings: Auto-generating client code eliminates the need to write boilerplate API request handling code, saving development time.

2. Consistency: The generated client code follows the API’s OpenAPI Specification, ensuring consistent request/response handling across the app.

3. Less Error-Prone: With the auto-generated code, there is a reduced chance of errors, as the code adheres to the API’s definition.

4. Easy Maintenance: If the API’s specification changes, simply regenerate the client code to reflect the updates.

5. Authentication Handling: The client code allows easy integration of authentication tokens or API keys for secure API requests.

6. Conclusion

In this article, we explored the benefits of using auto-generated client code to consume APIs in Angular apps. We learned how to generate client code from an OpenAPI Specification and implement it in an Angular service. Additionally, we discussed how to handle authentication with the generated client code.

By adopting auto-generated client code, developers can streamline API consumption, reduce manual errors, and enhance the overall efficiency of their Angular apps. This approach simplifies the process of making API calls, leaving developers more time to focus on building feature-rich and robust web applications.

As you continue to develop Angular apps, consider integrating auto-generated client code to optimize your API consumption and improve your development workflow.

--

--

Saunak Surani
Widle Studio LLP

Passionate about technology, design, startups, and personal development. Bringing ideas to life at https://widle.studio