[JAVA] Connect Spring Boot and Angular type-safely with OpenAPI Generator

This article is an upgraded version of the following previous articles. Connect Spring Boot and Angular2 to type-safe

It was an issue

I was afraid that the web backend and the web frontend were communicating loosely with JSON. I wanted to detect problems as much as possible during build. I wanted to be able to communicate type-safely like RPC.

Various version upgrades from the previous configuration

Old new
backend language Java8 Java11
backend framework Spring Boot 1 Spring Boot 2
frontend framework Angular5 Angular7
Code generation tool Swagger Codegen OpenAPI Generator

OpenAPI Generator and Swagger Codegen are tools that generate client code and server stub code based on the REST API specification. Unfortunately the operation of Swagger Codegen? There seemed to be a problem with OpenAPI Generator, which was forked by top contributors. Currently, OpenAPI Generator has more commits and contributors. This time, I switched to OpenAPI Generator.

What I made

This is a template project. https://github.com/chibat/spring-openapi-angular-starter

Project structure

The OpenAPI Spec file is automatically generated by SpringFox and does not need to be created manually.

Development flow

Let's take a simple addition application included in the template project as an example.

1. Creating a web backend

Web backends are created in Spring Boot. It is a Controller class that just receives two integers in a request, adds them, and responds.

package app.backend.web;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.Value;

@RestController
public class CalculatorController {

    @PostMapping("/rest/api/add")
    @ApiOperation(value = "", tags = "calculator", nickname = "add")
    public Response add(@RequestBody final Request request) {
        return new Response(request.getArg1() + request.getArg2());
    }

    @Data
    public static class Request {
        private Integer arg1;
        private Integer arg2;
    }

    @Value
    public static class Response {
        private final Integer result;
    }
}

It should be noted that the ApiOperation annotation uses the client class name that generates the string specified by tags and the string specified by nickname as the method name. Also, nickname is treated as an OperationId of OpenAPI Spec, and it seems to be useless unless it is unique as a whole.

2. Web front end client code generation

Perform Gradle tasks and generate client code.

$ cd backend
$ ./gradlew openApiGenerate

The test is executed and the API specifications output by SpringFox are output to a file. OpenAPI Generator reads the file and generates the client code.

Dependence on SpringFox is only for testing and does not increase the size of the application at runtime.

3. Creating a web front end

Web frontends are created in Angular. Create a Component class that uses the generated client code. CalculatorService is an automatically generated class.

import { Component } from '@angular/core';
import { CalculatorService } from './client/api/calculator.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  arg1: number;
  arg2: number;
  result: number;

  constructor(private  calculatorService: CalculatorService) {
  }

  add() {
    if (this.arg1 || this.arg2) {
      this.calculatorService
        .add({arg1: this.arg1, arg2: this.arg2})
        .subscribe(data => this.result = data.result);
    }
  }
}

Summary

OpenAPI Generator Good. The generated Angular code is also good. As mentioned above, please enjoy a comfortable type safe life.

The OpenAPI Generator e-book is now on sale! (Added on 2019-09-19)

The OpenAPI Generator e-book is now on sale. If you are interested, why not purchase it?

Introduction to Code Generation for REST API (OpenAPI Generator)

Recommended Posts

Connect Spring Boot and Angular type-safely with OpenAPI Generator
Connect to database with spring boot + spring jpa and CRUD operation
HTTPS with Spring Boot and Let's Encrypt
Download with Spring Boot
Try using DI container with Laravel and Spring Boot
Switch environment with Spring Boot application.properties and @Profile annotation
Try using OpenID Connect with Keycloak (Spring Boot application)
Spring Security usage memo: Cooperation with Spring MVC and Boot
Spring Boot with Spring Security Filter settings and addictive points
Attempt to SSR Vue.js with Spring Boot and GraalJS
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Create microservices with Spring Boot
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
Implement REST API with Spring Boot and JPA (domain layer)
Domain Driven Development with Java and Spring Boot ~ Layers and Modules ~
Easily develop web applications with STS and Spring Boot. In 10 minutes.
Use Basic Authentication with Spring Boot
Introduction to Spring Boot x OpenAPI ~ OpenAPI made with Generation gap pattern ~
gRPC on Spring Boot with grpc-spring-boot-starter
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Spring Boot programming with VS Code
Inquiry application creation with Spring Boot
Get validation results with Spring Boot
Compare Hello, world! In Spring Boot with Java, Kotlin and Groovy
(Intellij) Hello World with Spring Boot
Create an app with Spring Boot
Spring profile function, and Spring Boot application.properties
Google Cloud Platform with Spring Boot 2.0.0
[Java] LINE integration with Spring Boot
Image Spring Boot app using jib-maven-plugin and start it with Docker
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Implementation method for multi-data source with Spring boot (Mybatis and Spring Data JPA)
I introduced OpenAPI (Swagger) to Spring Boot (gradle) and tried various settings
Processing at application startup with Spring Boot
Spring with Kotorin --2 RestController and Data Class
Hello World with Eclipse + Spring Boot + Maven
Send regular notifications with LineNotify + Spring Boot
Perform transaction confirmation test with Spring Boot
Try using Spring Boot with VS Code
Launch Nginx + Spring Boot application with docker-compose
I tried Lazy Initialization with Spring Boot 2.2.0