KUSAMAKURA

智に働けば角が立つ。情に棹させば流される。意地を通せば窮屈だ。とかくに人の世は住みにくい。

VS Code + Spring Boot + Maven + JPA + H2 で最速 Web API 環境の構築(Step4)

f:id:kusamakura22:20190129155153p:plain

このステップでは、Web API を作成し実際に実行するまでを実装します。このステップが完了すると、表題通り、VS Code + Srping Boot + Maven + JPA + H2 で、Web API 環境構築が完了したことになります。

Swagger の導入

The Best APIs are Built with Swagger Tools | Swagger をプロジェクトに追加します。Swagger の導入に付いては、SwaggerでRESTful APIの管理を楽にする - Qiitaこちらのサイトを参考にしました。先に一読して頂くと、進めやすいと思います。

前提条件

依存関係の追加

  1. pom.xml を開き、下記の依存関係を追加します。
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
  </dependency>
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.5.0</version>
  </dependency>
  1. 右クリックから「Update project configuration」を選択し、依存関係を更新します。

SwaggerConfig の作成

SwaggerConfig を作成します。API を作成することが主題なので、簡単な作りにしましょう。ID、名前、価格を保持する商品テーブルを作成します。

package com.example.sandbox.config;

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;


@Configuration
@EnableSwagger2
public class Swagger2Config {

  private static final ApiInfo API_INFO = new ApiInfo(
    "Web API", 
    "This is Web API", 
    "1.0.0",
    "http://localhost:8080/api", 
    new Contact("smd101", "https://github.com/smd101", null),
    "Apache License, Version 2.0", 
    "http://www.apache.org/licenses/LICENSE-2.0");

  @Bean
  public Docket swaggerSpringMvcPlugin() {
    return new Docket(DocumentationType.SWAGGER_2)
          .groupName("product-api")
          .select()
          .build()
          .apiInfo(API_INFO);
  }

}

API の作成

作成した Entity に対する CRUDAPI で提供しましょう。Service,Controller を作成します。

Service の作成

package com.example.sandbox.service;
import com.example.sandbox.entity.Product;
import com.example.sandbox.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;


@Service
@Transactional
public class ProductService {
  @Autowired
  private ProductRepository productRepository;

  public Optional<Product> findProduct(Long id){
    return productRepository.findById(id);
  }

  public List<Product> findProducts(){
    return productRepository.findAll();
  }

  public Product save(Product product) {
    return productRepository.save(product);
  }

  public void delete(Long id) {
    productRepository.deleteById(id);
  }
}

Controller の作成

package com.example.sandbox.controller;

import com.example.sandbox.entity.Product;
import com.example.sandbox.service.ProductService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {

  @Autowired
    private ProductService productService;

    @RequestMapping(method = RequestMethod.GET)
    public List<Product> getProducts() {
        return productService.findProducts();
    }

    @RequestMapping(method=RequestMethod.GET, value="/{id}")
    public Product getProduct(@PathVariable("id") Long id) {
        return productService.findProduct(id).orElseGet(null);
    }

    @RequestMapping(method=RequestMethod.POST)
    public Product createProduct(@Validated @RequestBody Product product) {
        return productService.save(product);
    }

    @RequestMapping(method=RequestMethod.PUT, value="/{id}")
    public Product updateProduct(@PathVariable("id") Long id, @RequestBody Product product) {
        product.setId(id);
        return productService.save(product);
    }

    @RequestMapping(method=RequestMethod.DELETE, value="/{id}")
    public void deleteProduct(@PathVariable("id") Long id) {
        productService.delete(id);
    }
}

動作確認

Swagger を起動し、APIが動作することを確認します。F5(デバッグの開始)で、Tomcat を起動し、Swagger UI を開きます。作成した API の一覧が表示されれば動作確認は完了です。

ここまでのコードを公開してます。 github.com

参考