使用Spring Boot + MySQL实现简单的Web REST API服务器
提纲
使用Spring Boot从零开始实现REST API服务器。
YutaKase6/spring-api-sample
目标
入口

桌子
物理名論理名idユーザIDvalueユーザ情報
步骤…
首先创建项目。

关于Gradle的确认

在实施之前,需要考虑架构和类设计。

逐步实施
在Qiita上进行Spring Boot和JPA实现REST API(领域层)的编写。
在Qiita上进行Spring Boot和JPA实现REST API(基础层)的编写。
在Qiita上进行Spring Boot和JPA实现REST API(应用层)的编写。
MySQL配置
MySQL准备中
安装并启动
% brew install mysql
% mysql.server start
创建表格
CREATE TABLE test_users (
id VARCHAR(18) PRIMARY KEY
, value TEXT DEFAULT NULL
, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8
;
mysql> desc test_users;
+------------+-------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+-------------------+-----------------------------+
| id | varchar(18) | NO | PRI | NULL | |
| value | text | YES | | NULL | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
| updated_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+------------+-------------+------+-----+-------------------+-----------------------------+
4 rows in set (0.00 sec)
Spring Boot配置

编写与MySQL的连接设置。
spring:
datasource:
url: jdbc:mysql://localhost:3306/<SchemaName>
username: root
password:
jpa:
hibernate:
ddl-auto: none
确认行动
执行


使用Gradle执行
% ./gradlew bootRun
使用Java来执行
% ./gradlew build
% java -jar build/libs/spring-api-0.0.1-SNAPSHOT.jar
正常确认
- 登録
% curl -X POST "http://localhost:8080/v1/users" -H "Content-Type: application/json" -d "{ \"id\": \"id\", \"value\": \"value\"}" -s -w '\nstatus code: %{http_code}\n'
{"id":"id","value":"value"}
status code: 201
- 参照
% curl "http://localhost:8080/v1/users/id" -s -w '\nstatus code: %{http_code}\n'
{"id":"id","value":"value"}
status code: 200
- 削除
% curl -X DELETE "http://localhost:8080/v1/users/id" -s -w '\nstatus code: %{http_code}\n'
status code: 204
异常确认(Spring Boot 默认)
- 存在しないユーザ
% curl "http://localhost:8080/v1/users/hoge" -s -w '\nstatus code: %{http_code}\n'
{"timestamp":"2018-07-20T12:11:51.131+0000","status":500,"error":"Internal Server Error","message":"No message available","path":"/v1/users/hoge"}
status code: 500
- 定義していないメソッド
% curl "http://localhost:8080/v1/users" -s -w '\nstatus code: %{http_code}\n'
{"timestamp":"2018-07-20T12:14:08.013+0000","status":405,"error":"Method Not Allowed","message":"Request method 'GET' not supported","path":"/v1/users"}
status code: 405
- 定義していないパス
% curl "http://localhost:8080/v1/user" -s -w '\nstatus code: %{http_code}\n'
{"timestamp":"2018-07-20T12:14:14.668+0000","status":404,"error":"Not Found","message":"No message available","path":"/v1/user"}
status code: 404
还有许多其他的选择。
自定义异常情况下的响应
自定义用Spring Boot创建的REST API的错误响应 – Qiita
引入Swagger
创建单元测试


创建功能测试

引入记录器

测量覆盖率
待定…