[英]How to generate client code using with swagger-codegen-plugin (maven)?
[英]How to develop a simple REST Client using Swagger codegen?
我正在学习 Swagger 以及如何使用 Swagger codegen 生成 REST 客户端。 我知道如何用 Swagger 做文档,我也知道如何用 Swagger 生成一个简单的 REST 服务器,但我不知道如何用 Swagger codegen 生成一个简单的 REST 客户端。
例如,我有一个简单的应用程序,它是一个 REST 服务器,我想生成 REST 客户端。 我可以用 Swagger codegen 做到这一点吗?
REST 服务器的 controller:
package com.dgs.spring.springbootswagger.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping("/api/v1")
@Api(value = "Employee Management System", description = "Operations pertaining to employee in Employee Management System")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@ApiOperation(value = "View a list of available employees", response = List.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("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
@ApiOperation(value = "Get an employee by Id")
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(
@ApiParam(value = "Employee id from which employee object will retrieve", required = true) @PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@ApiOperation(value = "Add an employee")
@PostMapping("/employees")
public Employee createEmployee(
@ApiParam(value = "Employee object store in database table", required = true) @Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
@ApiOperation(value = "Update an employee")
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(
@ApiParam(value = "Employee Id to update employee object", required = true) @PathVariable(value = "id") Long employeeId,
@ApiParam(value = "Update employee object", required = true) @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmail(employeeDetails.getEmail());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@ApiOperation(value = "Delete an employee")
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(
@ApiParam(value = "Employee Id from which employee object will delete from database table", required = true) @PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
之后我开发了一个简单的 REST 客户端:
package com.dgs.restclient.controllers;
@Controller
public class UpdateController {
@Autowired
private EmployeeRestClient restClient;
@GetMapping("/showStartUpdate")
public String showStartCheckin() {
return "startUpdate";
}
@PostMapping("/startUpdate")
public String startCheckIn(@RequestParam("employeeId") Long employeeId, ModelMap modelMap) {
Employee employee = restClient.findEmployee(employeeId);
modelMap.addAttribute("employee", employee);
return "displayEmployeeDetails";
}
@PostMapping("/completeUpdate")
public String completeCheckIn(@RequestParam("employeeId") Long employeeId,
@RequestParam("employeeFirstName") String employeeFirstName,
@RequestParam("employeeLastName") String employeeLastName,
@RequestParam("employeeEmail") String employeeEmail) {
EmployeeUpdateRequest employeeUpdateRequest = new EmployeeUpdateRequest();
employeeUpdateRequest.setId(employeeId);
employeeUpdateRequest.setFirstName(employeeFirstName);
employeeUpdateRequest.setLastName(employeeLastName);
employeeUpdateRequest.setEmail(employeeEmail);
restClient.updateEmployee(employeeUpdateRequest);
return "updateConfirmation";
}
}
EmployeeRestClient:
package com.dgs.restclient.integration;
@Component
public class EmployeeRestClientImpl implements EmployeeRestClient {
private static final String EMPLOYEE_REST_URL =
"http://localhost:8080/api/v1/employees/";
@Override
public Employee findEmployee(Long id) {
RestTemplate restTemplate = new RestTemplate();
Employee employee = restTemplate
.getForObject(EMPLOYEE_REST_URL + id, Employee.class);
return employee;
}
@Override
public Employee updateEmployee(EmployeeUpdateRequest request) {
RestTemplate restTemplate = new RestTemplate();
restTemplate
.put(EMPLOYEE_REST_URL + request.getId(), request, Employee.class);
Employee employee = restTemplate
.getForObject(EMPLOYEE_REST_URL + request.getId(), Employee.class);
return employee;
}
}
这个 REST 客户端是我开发的,我想知道我是否可以用 Swagger codegen 做这个 REST 客户端开发,怎么做? 我是否只需要在 pom.xml 中添加 swagger-codegen-maven-plugin? 我听说过添加这个插件和一个 yml 文件,Swagger 将创建 REST 客户端。 任何反馈将不胜感激!
更新:
您的问题已在另一篇文章中得到解答 看看: 相关帖子
...
baeldung有一个很好的教程: 如何使用swagger codegen 创建rest客户端
例如执行命令:
java -jar swagger-codegen-cli.jar generate \
-i http://mydomain/v2/swagger.json \
--api-package com.mypackage.api \
--model-package com.mypackage.model \
--invoker-package com.mypackage.invoker \
--group-id com.mygroup \
--artifact-id spring-swagger-codegen-api-client \
--artifact-version 0.0.1-SNAPSHOT \
-l java \
--library resttemplate \
-o spring-swagger-codegen-api-client
Swagger Codegen支持以下客户端实现:
PS正如您所看到的,其余客户端是通过swagger规范定义生成的,并且使用“-i”参数进行定义。
是。 您可以使用swagger-codegen-maven-plugin
生成REST客户端。 但在此之前,您需要在OpenAPI Specification
描述YAML或JSON中的REST API,主要是因为swagger-codegen-maven-plugin
只能从本规范中编写的文件生成REST客户端。
其他答案假设您需要手动编写规范,而我的解决方案更进一步从REST控制器源代码自动生成规范。
最新的OpenAPI版本是3.0。但是基于导入的swagger注释的包,您使用的是2.0版(或之前版本)。 所以我的解决方案假设您正在使用OpenAPI 2.0。
生成开放API规范
首先,您可以使用swagger-maven-plugin从RestController源代码生成OpenAPI规范。 它基本上分析了在<locations>
中指定的@RestController
类中注释的Swagger注释,并将OpenAPI规范转储到/src/main/resources/swagger.json
:
<plugin>
<groupId>com.github.kongchen</groupId>
<artifactId>swagger-maven-plugin</artifactId>
<version>3.1.5</version>
<configuration>
<apiSources>
<apiSource>
<springmvc>true</springmvc>
<locations>
<location>com.dgs.spring.springbootswagger.controller.EmployeeController</location>
<location>com.dgs.spring.springbootswagger.controller.FooController</location>
</locations>
<schemes>
<scheme>http</scheme>
</schemes>
<host>127.0.0.1:8080</host>
<basePath>/</basePath>
<info>
<title>My API</title>
<version>1.1.1</version>
</info>
<swaggerDirectory>${basedir}/src/main/resources/</swaggerDirectory>
</apiSource>
</apiSources>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
执行以下maven命令开始生成:
mvn clean compile
生成Rest客户端
生成swagger.json
后,您可以将其复制并粘贴到客户端项目中(例如/src/main/resources/swagger.json)。 然后我们可以使用swagger-codegen-maven-plugin
来生成HTTP客户端。
默认情况下,它将生成整个maven项目 ,其中包括测试用例和其他文档内容。 但我想要的只是HttpClient的源代码而没有其他东西。 经过多次反复试验,我确定了以下配置:
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.4.7</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${basedir}/src/main/resources/swagger.json</inputSpec>
<language>java</language>
<library>resttemplate</library>
<output>${project.basedir}/target/generated-sources/</output>
<apiPackage>com.example.demo.restclient.api</apiPackage>
<modelPackage>com.example.demo.restclient.model</modelPackage>
<invokerPackage>com.example.demo.restclient</invokerPackage>
<generateApiTests>false</generateApiTests>
<generateModelTests>false</generateModelTests>
<generateApiDocumentation>false</generateApiDocumentation>
<generateModelDocumentation>false</generateModelDocumentation>
<configOptions>
<dateLibrary>java8</dateLibrary>
<sourceFolder>restclient</sourceFolder>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
生成的HTTP客户端基于RestTemplate,将生成到文件夹target/generated-sources/restclient
。 您可能必须配置IDE以导入生成的客户端才能使用它。 (在Eclipse的情况下,您可以在项目属性中配置➡️JavaBuildPath➡️添加生成的rest客户端的文件夹)
要开始生成客户端,只需执行maven命令:
mvn clean compile
要使用生成的HTTP客户端:
ApiClient apiClient = new ApiClient();
//Override the default API base path configured in Maven
apiClient.setBasePath("http://api.example.com/api");
EmployeeManagementSystemApi api = new EmployeeManagementSystemApi(apiClient);
api.getEmployeeById(1l);
注意 :
javax/xml/bind/annotation/XmlRootElement
异常,则可能需要参考此内容 。 1)转到https://editor.swagger.io创建您的swagger文档,我使用“Swagger Petstore”作为示例
2)现在选择File,Import File并上传下载的swagger.json文件
3)打开https://swagger.io/tools/swagger-codegen/
4)使用以下步骤:
i)将存储库克隆到磁盘git clone https://github.com/swagger-api/swagger-codegen.git
ii)运行mvn clean包
iii)将swagger-codegen-cli.jar文件从目标文件夹复制到计算机上的本地驱动器。
iv)接下来执行以下命令以生成客户端:
java -jar swagger-codegen-cli.jar -i <json_file> -l python -o my_client
此命令有三个参数:
-i Specifies the path to the input file. This can be a URL
-l Specifies the programming language for the client
-o Specifies the output directory where the generate code should be located
Swagger Codegen是一个开源项目,它允许从OpenAPI规范自动生成API客户端库(SDK生成),服务器存根和文档。 Swagger Codegen可以在GitHub存储库中下载,也可以在集成的SwaggerHub平台中为任何新的或现有的OpenAPI定义的API生成。 SwaggerHub将Swagger编辑器,UI和Codegen工具集成到一个集成的API设计和文档中,为使用Swagger(OpenAPI)规范的API团队构建。
有一些用于构建工具的插件,如Maven和Gradle,因为已经给出了很少的答案,而不是在这里添加
假设您的应用程序的Swagger端点可以在以下位置访问:
测试Swagger 2.0 JSON API文档
HTTP://本地主机:8080 / V2 / API-文档组=雇员
http:// localhost:8080 / v2 / api-docs (如果您尚未设置名为employee
的组)
测试Swagger UI
您可以从Maven Central Repository下载swagger-codegen-cli-2.4.7.jar 。
现在您已经拥有了Swagger Codegen JAR,您可以通过执行以下命令来生成REST客户端:
java -jar swagger-codegen-cli-2.4.7.jar generate \
-i http://localhost:8080/v2/api-docs?group=employee \
-l java \
-o swagger-codegen-client
如果没有招摇的分组,
java -jar swagger-codegen-cli-2.4.7.jar generate \
-i http://localhost:8080/v2/api-docs \
-l java \
-o swagger-codegen-client
虽然Swagger Codegen CLI提供了许多选项,但我们使用的选项对于生成客户端代码是绝对必要的。
-i
指向应用程序的Swagger api docs
的URL。 -l
客户端的编程语言,在本例中是java
-o
生成的客户端代码的输出文件夹。 执行上一个生成代码的命令后,您应该注意到终端上的以下消息:
[main] INFO io.swagger.parser.Swagger20Parser - reading from http://localhost:8080/v2/api-docs?group=employee
[main] WARN io.swagger.codegen.ignore.CodegenIgnoreProcessor - Output directory does not exist, or is inaccessible. No file (.swagger-codegen-ignore) will be evaluated.
[main] INFO io.swagger.codegen.AbstractGenerator - writing file swagger-codegen-client/src/main/java/io/swagger/client/model/Employee.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file swagger-codegen-client/docs/Employee.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file swagger-codegen-client/src/main/java/io/swagger/client/api/EmployeeControllerApi.java
...
[main] INFO io.swagger.codegen.AbstractGenerator - writing file swagger-codegen-client/src/main/java/io/swagger/client/ApiClient.java
...
代码生成完成后,您应该注意到具有以下结构的gradle/maven
项目:
__ swagger-codegen-client
|__ README.md
|__ build.gradle
|__ build.sbt
|__ docs
|__ git_push.sh
|__ gradle
|__ gradle.properties
|__ gradlew
|__ gradlew.bat
|__ pom.xml
|__ settings.gradle
|__ src
|__ main
|__ java
|__ io.swagger.client.api
|__ EmployeeControllerApi.java
|__ test
|__ java
|__ io.swagger.client.api
|__ EmployeeControllerApiTest.java
可以在此处找到生成的客户端项目的示例。
客户端项目包含许多java类。 但是最重要的类是EmployeeControllerApi.java 。 这是包含用于创建REST客户端类的所有逻辑的类。
另一个重要的类是EmployeeControllerApiTest.java 。 它向您展示了如何使用EmployeeControllerApi.java 。 生成的客户端项目还提供了一个非常有用的README文件。
ApiClient类包含与建立HTTP客户端连接相关的信息。 请确保您的REST应用程序的basePath
正确无误。 在生成的示例中, basePath
具有https://localhost:8080
URL而不是http://localhost:8080
。
生成的项目适用于Java 8.如果您使用的是Java 12,则必须添加以下依赖项才能使项目编译:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
以下是通过进行REST POST方法方法调用来创建employee
的示例。
Employee employee = new Employee();
employee.setId(3L);
employee.setFirstName("Sam");
employee.setLastName("Fox");
employee.setEmail("sfox@gmail.com");
EmployeeControllerApi api = new EmployeeControllerApi();
Employee response = api.createEmployeeUsingPOST(employee);
System.out.println(response);
您应该回复类似于:
class Employee {
email: sfox@gmail.com
firstName: Sam
id: 3
lastName: Fox
}
你可以在这里找到一个完整的例子。
只需添加一个swagger插件不会生成休息客户端,您需要按照以下步骤操作。
以YAML格式记下规范。 基于规范结果,将生成。 将规范保存为YAML文件。 它将保存为swagger.yaml,请遵循以下教程: https ://howtodoinjava.com/swagger2/code-generation-for-rest-api/
我为此苦苦挣扎,最终制作了自己的工具。 它真的很小,只依赖于spring-web
。 我什至 提交了一份 PR ,看看它是否可以成为 Spring 的一部分。
我称它为Spring RestTemplate Client ,它可以完成Feign和其他工具的功能,但更轻巧,仅支持 Spring。
final MyApiInterface myClient = SpringRestTemplateClientBuilder
.create(MyApiInterface.class)
.setUrl(this.getMockUrl())
.setRestTemplate(restTemplate) // Optional
.setHeader("header-name", "the value") // Optional
.setHeaders(HttpHeaders) // Optional
.build();
使用 MyApiInterface 的注释,对myClient
的任何调用都将转换为MyApiInterface
调用:
final ResponseEntity<MyDTO> response = myClient.getMyDto();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.