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

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

<strong>Originally published by </strong><a href="https://medium.com/@swathisprasad" target="_blank">Swathi Prasad</a><strong> </strong><em>at&nbsp;</em><a href="https://medium.com/@swathisprasad/generating-and-consuming-rest-apis-with-spring-boot-2-angular-7-and-swagger-2-ee4abc3c6459" target="_blank"><em>Medium&nbsp;</em></a>

Originally published by Swathi Prasad at Medium 

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:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Here is the complete Maven POM.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

&lt;groupId&gt;com.swathisprasad&lt;/groupId&gt;
&lt;artifactId&gt;springboot-swagger&lt;/artifactId&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

&lt;parent&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
    &lt;version&gt;2.1.4.RELEASE&lt;/version&gt;
    &lt;relativePath /&gt;
&lt;/parent&gt;

&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;exclusions&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;
            &lt;/exclusion&gt;
        &lt;/exclusions&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-undertow&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.springfox&lt;/groupId&gt;
        &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
        &lt;version&gt;2.9.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.springfox&lt;/groupId&gt;
        &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;
        &lt;version&gt;2.9.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.h2database&lt;/groupId&gt;
        &lt;artifactId&gt;h2&lt;/artifactId&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;

</project>

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.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; 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;

@Configuration @EnableSwagger2 public class SwaggerConfig {

@Bean
public Docket api() {

    return new Docket(DocumentationType.SWAGGER_2).select()
            .apis(RequestHandlerSelectors
                    .basePackage("com.swathisprasad.springboot"))
            .paths(PathSelectors.any())
            .build().apiInfo(apiEndPointsInfo());
}

private ApiInfo apiEndPointsInfo() {

    return new ApiInfoBuilder().title("Spring Boot REST API")
            .description("Language Management REST API")
            .contact(new Contact("Swathi Prasad", "www.techshard.com", "[email protected]"))
            .license("Apache 2.0")
            .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
            .version("1.0-SNAPSHOT")
            .build();
}

}

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.*;

@Entity public class Language {

@Id
@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) {
    this.name = name;
}

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

@Override
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 (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
}

} package com.swathisprasad.springboot.dao.repository;

import com.swathisprasad.springboot.dao.entity.Language; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;

@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;

@Component public class DataInitializer {

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

@Autowired
ILanguageRepository languageRepository;

public void initData() {

    try {
        Language language = new Language();
        language.setName("Java");
        languageRepository.save(language);

        language = new Language();
        language.setName("JavaScript");
        languageRepository.save(language);

        language = new Language();
        language.setName("C++");
        languageRepository.save(language);

        language = new Language();
        language.setName("Groovy");
        languageRepository.save(language);

        language = new Language();
        language.setName("Python");
        languageRepository.save(language);

        language = new Language();
        language.setName("Swift");
        languageRepository.save(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;

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

@Autowired
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&lt;List&lt;Language&gt;&gt; getLanguages() {
    final List&lt;Language&gt; languages = languageRepository.findAll();
    return new ResponseEntity&lt;&gt;(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 </em>
-l typescript-angular </em>
-o angular-client </em>
— additional-properties [email protected]/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:

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.

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';

@NgModule({

declarations: [

AppComponent,

LanguageComponent

],

imports: [

BrowserModule,

AppRoutingModule,

ApiModule,

HttpClientModule

],

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';

@Component({

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) {

this.languages.push(res[i]);

}

});

}

}

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

<p

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

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

</p>

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="https://en.wikipedia.org/wiki/List_of_programming_languages">

List of programming languages</a>

</div>

</div>

</nav>

</div>

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

<app-language></app-language>

</div>

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

<router-outlet></router-outlet>

</div>

</div>

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:

Conclusion

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!

---------------------------------------------------------------------------------------------------

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ JavaScript Bootcamp - Build Real World Applications

☞ The Web Developer Bootcamp

☞ JavaScript: Understanding the Weird Parts

☞ Building a Simple URL Shortener With Just HTML and Javascript

☞ The JavaScript Developer’s Guide To Node.JS

☞ From Javascript to Typescript to Elm

☞ Google’s Go Essentials For Node.js / JavaScript Developers

☞ 3 things you didn’t know about the forEach loop in JavaScript



javascript angular spring-boot typescript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

How to Build a Basic Web Application using Angular and Spring-Boot

In this post, we learn how to build a basic web application with Spring Boot and Angular

Angular file upload Spring Boot backend

This tutorial shows a step by step solution to Angular file upload Spring Boot backend and store it on file system. We will cover a file upload from a basic input and also from a drag-drop area.

JavaScript Vs TypeScript

Get to know here difference between JavaScript & TypeScript, In this blog explained with pros and cons of TypeScript & JavaScript.

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc

How to Build a CRUD App with Angular 9 and Spring Boot 2.2

This screencast shows how to develop a secure CRUD application using Angular 9 and Spring Boot