Generating and Consuming REST APIs with Spring Boot 2, Angular 7 and Swagger 2

Imagine you want to integrate backend APIs or third party APIs with minimal effort, how do you pull it off?

Integrating Backend APIs manually can be time consuming and error-prone. Hence, Swagger comes into picture. Swagger is the most popular framework to generate and consume OpenAPI specification. The tool greatly relieves the burden of documenting and interacting with APIs.

In this article, we are going to generate API documentation from Spring Boot REST API and generate Angular API client from the documentation using Swagger.

Tools and Technologies Used

  • Spring Boot — 2.1.4.RELEASE
  • JDK — OpenJDK 12
  • Spring Framework — 5.1.6 RELEASE
  • JPA
  • Hibernate
  • H2 in-memory database
  • Swagger — 2
  • springfox-swagger2–2.9.4
  • springfox-swagger-ui — 2.9.4
  • Swagger Codegen CLI — 2.4.4
  • IDE — IntelliJ and Visual Studio Code
  • Angular CLI — 7.2.0
  • Node — 8.11.3
  • NPM — 6.3.0

Generating Swagger API Documentation

Create a sample Spring Boot application. Here is my sample project structure. I have created the project manually, but you could also create using Spring Intializer.

I will go over each package in a bit.

Spring Boot Project Structure

There are several implementations of Swagger 2 which adheres to Open API specification. Springfox is one of those implementations. Currently, Springfox supports only Swagger 1.2 and Swagger 2.0. Add Springfox dependencies as follows:


Here is the complete Maven POM.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


<relativePath />




Let us first enable Swagger support in the application. We enable using @EnableSwagger2 annotation. Notice that we are specifying base package “com.swathisprasad.springboot”. This is to generate API documentation within our custom package.

If we do not provide base package, Swagger would generate documentation even for Spring Boot actuator endpoints which may not be of our interest.

package com.swathisprasad.springboot.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

public class SwaggerConfig {

public Docket api() {

return new Docket(DocumentationType.SWAGGER_2).select()

private ApiInfo apiEndPointsInfo() {

return new ApiInfoBuilder().title("Spring Boot REST API")
.description("Language Management REST API")
.contact(new Contact("Swathi Prasad", "", ""))
.license("Apache 2.0")


Before we create an API endpoint, let’s create a JPA entity Language and a corresponding JPA repository ILanguageRepository. I have also created a DataInitializer class to create mock data at server startup.

package com.swathisprasad.springboot.dao.entity;

import javax.persistence.*;

public class Language {

@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

private String name;

public Language() {

public String getName() {
return name;

public void setName(final String name) { = name;

public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
return result;

public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Language))
return false;
final Language other = (Language) obj;
if (name == null) {
if ( != null)
return false;
} else if (!name.equals(
return false;
return true;
package com.swathisprasad.springboot.dao.repository;

import com.swathisprasad.springboot.dao.entity.Language;
import org.springframework.stereotype.Repository;

public interface ILanguageRepository extends JpaRepository<Language, Long> {
package com.swathisprasad.springboot;

import com.swathisprasad.springboot.dao.entity.Language;
import com.swathisprasad.springboot.dao.repository.ILanguageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class DataInitializer {

private final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

ILanguageRepository languageRepository;

public void initData() {

try {
Language language = new Language();

language = new Language();

language = new Language();

language = new Language();

language = new Language();

language = new Language();

} catch (final Exception ex) {
logger.error("Exception while inserting mock data {}", ex);



Create a REST controller which contains an API endpoint as below. We can customize API documentation using @API, @APIOperation and @APIResponse annotations provided by Springfox as shown below.

package com.swathisprasad.springboot.controller;

import com.swathisprasad.springboot.dao.entity.Language;
import com.swathisprasad.springboot.dao.repository.ILanguageRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(value="Language API", description="Operations pertaining to Language")
public class LanguageController {

ILanguageRepository languageRepository;

@ApiOperation(value = "View a list of available languages", response = Iterable.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved list"),
@ApiResponse(code = 401, message = "You are not authorized to view the resource"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
@GetMapping(value = "/languages", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Language>> getLanguages() {
final List<Language> languages = languageRepository.findAll();
return new ResponseEntity<>(languages, HttpStatus.OK);


Now, let us run Application class as Java application. Note that we will see below warning when Undertow server is started. Undertow complains about XNIO Illegal reflective access since Java 9+ and the issue has been reported here.

WARNING: An illegal reflective access operation has occurred

Once the server has started successfully, open http://localhost:8080/v2/api-docs in the browser. We will see Swagger documentation and save it as JSON on your file system.

This documentation adheres to OpenAPI 2.0 specification.

The Swagger UI can be viewed at http://localhost:8080/swagger-ui.html .

NOTE: If you wish to generate OpenAPI 3.0 spec, the above generated spec can also be imported and converted into OpenAPI 3.0 spec at SwaggerHub.


Generating Angular API Clients with Swagger

The biggest advantage of generated API clients would save a lot of time from writing Angular services and model manually. Let us see how it can be achieved.

In this tutorial, we will use Swagger Codegen library to generate API clients. The library can be downloaded directly from Maven Repository.

Swagger Codegen 2.x supports OpenAPI Spec 2.0 and 3.x supports both OpenAPI spec 2.0 and 3.0. Since our Swagger spec is compliant to OpenAPI spec 2.0, we will use Swagger Codegen 2.x for generating API client.

Download the jar file from Maven repository. Open the command prompt or terminal and run the following command. If you are on windows, remove the backslashes and write the entire command in single line.

java -jar swagger-codegen-cli-2.4.4.jar generate -i api-docs.json \

-l typescript-angular \

-o angular-client \

— additional-properties npmName=@techschard/language-api,snapshot=true,ngVersion=7.2.0

  • -i or --input-spec defines the location of the input swagger spec, as URL or file (required)
  • -l or --lang defines the client language to generate (required)
  • -o or --output defines the output directory, where the generated files should be written to (current directory by default)
  • -c or --config defines the path to an additional JSON configuration file. Supported options can be different for each language. We will look at this argument in the paragraph.

Note that the — additional-properties is added to generate the client as an Angular package. These properties can also be provided via a config file through -c or — config parameter.

The detailed explanation can be found via the following command.

java -jar swagger-codegen-cli.jar help generate

The generated file structure would be as follows:

Generated Angular API Client

Here, the .ng_pkg_build directory and ng-package.json can be ignored for now. They are not generated by Swagger Codegen.

This is a complete Angular project with all required configuration files and typescript files to create an angular (ng) package. I have published the generated Angular package to npm. Let us see how to publish to npm.

Publish Angular Package to NPM

Login to NPM and create a new user account if you don’t have one. In the terminal or command prompt, type npm adduser. Provide your new npm username and password. This is to authorize your machine to publish npm packages.

Run npm install in the above generated npm package. Then, run npm run build command.

We might have to install tsickle module as required by npm packager module. Install the module if necessary.

Finally, run npm publish dist — access=public command to publish to npm repository.

Here, the — access=public makes the repository public. By, default the repository would be set to restricted.

Once it is published, you will find your package under your account as below.

Uploded NPM package

Consuming API Clients with Swagger

Now that we have generated API client and uploaded it to NPM, we will create a small Angular project through Angular CLI and include the generated API client.

Run the following command in terminal to create a new Angular project.

ng new angular7-swagger

Once the project is created, install the following npm module within the project.

npm install @techshard/language-rest-api

Here, language-rest-api is the npm package that contains our generated Angular.
Edit the app.module.ts file and include this npm package. Here is the complete file.

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { ApiModule, BASE_PATH } from '@techshard/language-rest-api';

import { HttpClientModule } from '@angular/common/http';

import { environment } from './../environments/environment';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { LanguageComponent } from './language/language.component';


declarations: [




imports: [






providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],

bootstrap: [AppComponent]


export class AppModule { }

Let’s create a new module “language” and import generated service and data model in this new component. Then, we will call the API to retrieve the list of languages.

import { Component, OnInit } from '@angular/core';

import { LanguageControllerService, Language } from '@techshard/language-rest-api';


selector: 'app-language',

templateUrl: './language.component.html',

styleUrls: ['./language.component.scss']


export class LanguageComponent implements OnInit {

languages: Language[] = [];

constructor(private languageControllerService: LanguageControllerService) { }

ngOnInit() {

this.languageControllerService.getLanguagesUsingGET().subscribe(res => {

for (var i in res) {






The language.component.html shall be modified as follows to display the list of languages.


*ngFor="let l of languages; index as i" class="panel-body">

<a class="text-success">{{}}</a>


Now, edit the app.component.html and add the language template. The complete HTML file is here:

<div class="container blue">

<div class="page-header">

<nav class="navbar navbar-inverse">

<div class="container-fluid">

<div class="navbar-header">

<a class="navbar-brand" href="">

List of programming languages</a>





<div class="col-md-2">



<div class="col-md-9">




Note that I have installed Bootstrap 4 and imported into the project.

Running the Angular App

Run the following command in the terminal.

ng serve

Once the project is compiled successfully, open http://localhost:4200 in the browser and we will see list of languages as follows:

Final Angular App


Congratulations! We have learned to automatically generate and consume API code. This approach reduces errors and writing a lot of boilerplate code. Also, this approach can be very useful for developing Micro Frontends.

The complete source code can be found on my GitHub repository.

I hope you enjoyed my article. Feel free to leave any comments or suggestions.

Happy learning!

Software developer living in Germany. Sharing my opinion and what I learn.

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