1个概述
在本文中,我们考虑使用OpenAPI规范使用代码生成的示例。这是API-First建筑服务的方法。 Code generator将用于在Java-Spring应用程序中生成代码。 GitHub上的示例项目的完整源代码
2规格
让我们从编写简单的OpenAPI规范开始。在这里,我们使用一个示例,其中包括某些客户的“ get”和“创建”操作。
openapi: 3.0.3
info:
title: client-api
description: 'Client API'
version: 1.0.0
paths:
/client:
get:
parameters:
- name: id
in: query
required: true
schema:
type: string
format: uuid
description: Client id
responses:
200:
description: Success response with client
content:
application/json:
schema:
$ref: "#/components/schemas/ClientResponse"
post:
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Client'
required: true
responses:
200:
description: Success response with client
content:
application/json:
schema:
$ref: "#/components/schemas/ClientResponse"
components:
schemas:
ClientResponse:
type: object
properties:
success:
type: boolean
description: Operation success flag
message:
type: string
description: Error description
client:
$ref: "#/components/schemas/Client"
required:
- success
- message
- object
Client:
type: object
description: Client data
properties:
id:
type: string
format: uuid
description: Client unique id
name:
type: string
description: Client name
maximum: 32
minimum: 2
dateOfBirth:
type: string
format: date
createdAt:
type: string
description: Date of client registration
format: date-time
banned:
type: boolean
description: Ban flag
countAccounts:
type: integer
description: Count of client accounts
minimum: 0
serviceRate:
type: string
description: Service rate
enum:
- "FREE"
- "STANDARD"
- "VIP"
3个设置依赖性
让我们设置OpenAPI generator maven plugin
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>6.2.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/specs/client-api.yaml</inputSpec>
<generatorName>spring</generatorName>
<apiPackage>dev.toliyansky.openapi.api</apiPackage>
<modelPackage>dev.toliyansky.openapi.model</modelPackage>
</configuration>
</execution>
</executions>
</plugin>
4个代码示例
在运行mvn clean install
生成的类后,将放置在目标目录中。
要实现HTTP路由,我们应该创建一个延长生成控制器的类。
@RestController
@RequestMapping("/api")
public class ClientController extends ClientApiController {
private final RandomExceptionService randomExceptionService;
public ClientController(NativeWebRequest request, RandomExceptionService randomExceptionService) {
super(request);
this.randomExceptionService = randomExceptionService;
}
@Override
public ResponseEntity<ClientResponse> clientGet(UUID id) {
var clientResponse = new ClientResponse();
try {
var client = new Client(); // Stub. But in real project get client from service level.
clientResponse.setSuccess(true);
clientResponse.setClient(client);
randomExceptionService.generateException50percentChance();
return ResponseEntity.ok(clientResponse);
} catch (Exception e) {
e.printStackTrace();
clientResponse.setSuccess(false);
clientResponse.setMessage(e.getMessage());
clientResponse.setClient(null);
return ResponseEntity.internalServerError().body(clientResponse);
}
}
@Override
public ResponseEntity<ClientResponse> clientPost(Client client) {
var clientResponse = new ClientResponse();
try {
// Do some actions with client in service level.
client.id(UUID.randomUUID());
clientResponse.setSuccess(true);
clientResponse.setClient(client);
randomExceptionService.generateException50percentChance();
return ResponseEntity.ok(clientResponse);
} catch (Exception e) {
e.printStackTrace();
clientResponse.setSuccess(false);
clientResponse.setMessage(e.getMessage());
clientResponse.setClient(null);
return ResponseEntity.internalServerError().body(clientResponse);
}
}
}
现在我们可以使用HTTP请求进行测试
### Get client by id
GET http://localhost:8080/api/client?id=00c4c92b-09d5-460e-a938-83d00238c6e9
Accept: application/json
------
HTTP/1.1 200
Content-Type: application/json
{
"success": true,
"message": null,
"client": {
"id": null,
"name": null,
"dateOfBirth": null,
"createdAt": null,
"banned": null,
"countAccounts": null,
"serviceRate": null
}
}
### Create client
POST http://localhost:8080/api/client
Content-Type: application/json
------
HTTP/1.1 200
Content-Type: application/json
{
"success": true,
"message": null,
"client": {
"id": "6796a90a-314a-4667-a7cc-dfbe592b27e5",
"name": "Anatoliy",
"dateOfBirth": "2020-01-01",
"createdAt": "2020-01-01T00:00:00Z",
"banned": false,
"countAccounts": 3,
"serviceRate": "VIP"
}
}
5结论
在本文中,我们看到了如何使用OpenAPI YAML规范和OpenAPI Generator Maven插件生成Java-Spring服务。
GitHub上的示例项目的完整源代码