{{announcement.body}}
{{announcement.title}}

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

DZone 's Guide to

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

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

· Integration Zone ·
Free Resource

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. That's where Swagger comes into the picture. Swagger is the most popular framework to generate and consume OpenAPI specifications. The tool greatly relieves the burden of documenting and interacting with APIs.

In this article, we are going to generate API documentation from a Spring Boot REST API and generate an 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 it using Spring Initializer.

I will go over each package in a bit.

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

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

    <groupId>com.swathisprasad</groupId>
    <artifactId>springboot-swagger</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath />
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <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>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

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

If we do not provide a 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", "techshard08@gmail.com"))
                .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 >>> 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 that contains an API endpoint as below. We can customize the 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<List<Language>> getLanguages() {
        final List<Language> languages = languageRepository.findAll();
        return new ResponseEntity<>(languages, HttpStatus.OK);
    }

}

Now, let us run Application class as a Java application. Note that we will see the below warning when the 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 the 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 an API client.

Download the jar file from the 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 a 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 will be as follows:

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 the required configuration files and typescript files to create an angular (ng) package. I have published the generated Angular package to npm. Let's 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 the 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 the 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 the 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.

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 a 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!

Topics:
spring boot 2 ,angular ,swagger 2 ,rest api ,typescript ,integration ,tutorial ,generating rest apis ,consuming rest apis

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}