Java 如何使用Swagger codegen开发一个简单的REST客户端?
我正在学习Swagger以及如何使用Swagger codegen生成REST客户端。我知道如何使用Swagger编写文档,也知道如何使用Swagger生成简单的REST服务器,但我不知道如何使用Swagger codegen生成简单的REST客户端 例如,我有一个简单的应用程序,它是一个REST服务器,我想生成REST客户端。我能和斯威格·科德根一起做吗 REST服务器的控制器:Java 如何使用Swagger codegen开发一个简单的REST客户端?,java,spring-boot,swagger,rest-client,swagger-codegen,Java,Spring Boot,Swagger,Rest Client,Swagger Codegen,我正在学习Swagger以及如何使用Swagger codegen生成REST客户端。我知道如何使用Swagger编写文档,也知道如何使用Swagger生成简单的REST服务器,但我不知道如何使用Swagger codegen生成简单的REST客户端 例如,我有一个简单的应用程序,它是一个REST服务器,我想生成REST客户端。我能和斯威格·科德根一起做吗 REST服务器的控制器: package com.dgs.spring.springbootswagger.controller; imp
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;
}
}
雇主客户:
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插件吗?我听说添加了这个插件和一个yml文件,Swagger将创建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支持以下客户端实现:
swagger-codegen-maven-plugin
只能从本规范中编写的文件生成REST客户端
其他答案假设您需要手动编写规范,而我的解决方案进一步从REST控制器源代码自动生成规范
最新的OpenAPI版本是3.0。但是根据您导入的swagger注释包,您使用的是2.0版(或之前的版本)。因此,我的解决方案假设您使用的是OpenAPI 2.0
生成开放式API规范
首先,可以使用从RestController源代码生成OpenAPI规范。它主要分析
中指定的@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>
生成Rest客户端
生成swagger.json
后,您可以将其复制并粘贴到客户端项目(例如/src/main/resources/swagger.json)。然后,我们可以使用swagger-codegen-maven-plugin
生成HTTP客户端
默认情况下,它将生成包含测试用例和其他文档内容的。但是我想要的只是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客户端,请执行以下操作:
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);
注:
- 如果在使用java8+生成时遇到
异常,可能需要参考javax/xml/bind/annotation/XmlRootElement
java -jar swagger-codegen-cli.jar -i <json_file> -l python -o my_client
Swagger Codegen是一个开源项目,它允许生成
API客户端库(SDK生成)、服务器存根和文档
从OpenAPI规范自动生成。斯威格·科德根是
可在GitHub存储库中下载,也可以生成
对于集成API中定义的任何新的或现有的OpenAPI
昂首阔步的枢纽平台。SwaggerHub提供了Swagger编辑器、UI和
Codegen工具以集成API设计和
文档,为使用Swagger(OpenAPI)的API团队构建
规格
有Maven和Gradle等构建工具的插件,因为已经给出了一些答案,所以这里没有添加
employee
的组)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文档的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
...
REST客户端项目
一旦代码生成
-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
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
[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
...
__ 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
<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>
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
}