拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 使用OpenAPI Generator实现Open API Server

使用OpenAPI Generator实现Open API Server

白鹭 - 2021-11-24 1511 0 0

1.概述

顾名思义, OpenAPI Generator会根据OpenAPI规范生成代码。它可以为客户端库,服务器存根,文档和配置创建代码。

它支持各种语言和框架。值得注意的是,它支持C ++,C#,Java,PHP,Python,Ruby,Scala –几乎所有广泛使用的工具。

在本教程中,我们将学习如何通过OpenAPI Generator的maven插件实现基于Spring的服务器存根。使用生成器的其他方式是通过其CLI在线工具

2. YAML文件

首先,我们需要一个指定API的YAML文件。我们将其作为生成器的输入,以生成服务器存根。

这是我们的petstore.yml的片段:

openapi: "3.0.0"

 paths:

 /pets:

 get:

 summary: List all pets

 operationId: listPets

 tags:

 - pets

 parameters:

 - name: limit

 in: query

 ...

 responses:

 ...

 post:

 summary: Create a pet

 operationId: createPets

 ...

 /pets/{petId}:

 get:

 summary: Info for a specific pet

 operationId: showPetById

 ...

 components:

 schemas:

 Pet:

 type: object

 required:

 - id

 - name

 properties:

 id:

 type: integer

 format: int64

 name:

 type: string

 tag:

 type: string

 Error:

 type: object

 required:

 - code

 - message

 properties:

 code:

 type: integer

 format: int32

 message:

 type: string

3. Maven依赖

3.1 OpenAPI Generator的插件

接下来,让我们为生成器插件添加Maven依赖项:

<plugin>

 <groupId>org.openapitools</groupId>

 <artifactId>openapi-generator-maven-plugin</artifactId>

 <version>5.1.0</version>

 <executions>

 <execution>

 <goals>

 <goal>generate</goal>

 </goals>

 <configuration>

 <inputSpec>

 ${project.basedir}/src/main/resources/petstore.yml

 </inputSpec>

 <generatorName>spring</generatorName>

 <apiPackage>com.baeldung.openapi.api</apiPackage>

 <modelPackage>com.baeldung.openapi.model</modelPackage>

 <supportingFilesToGenerate>

 ApiUtil.java

 </supportingFilesToGenerate>

 <configOptions>

 <delegatePattern>true</delegatePattern>

 </configOptions>

 </configuration>

 </execution>

 </executions>

 </plugin>

如我们所见,我们传入YAML文件作为inputSpec 。之后,由于需要基于Spring的服务器,因此将generatorName用作spring

然后apiPackage指定将在其中生成API的程序包名称。接下来,我们在生成器放置数据模型的地方放置了modelPackagedelegatePattern设置为true ,我们要求创建一个可以实现为自定义@Service类的接口。

重要的**是,无论您使用的是CLI,Maven / Gradle插件还是在线生成选项,OpenAPI Generator的选项**都相同。

3.2 Spring依赖

在生成Spring服务器时,我们还需要其依赖项( Spring Boot Starter WebSpring Data JPA ),以便生成的代码可以按预期进行编译和运行

<dependencies>

 <dependency>

 <groupId>org.springframework.boot</groupId>

 <artifactId>spring-boot-starter-web</artifactId>

 <version>2.4.4</version>

 </dependency>

 <dependency>

 <groupId>org.springframework.data</groupId>

 <artifactId>spring-data-jpa</artifactId>

 <version>2.4.6</version>

 </dependency>

 </dependencies>

4.代码生成

要生成服务器存根,我们只需要运行:

mvn clean install

结果,我们得到:

使用OpenAPI

现在让我们看一下代码,从apiPackage的内容开始。

首先,**我们获得一个名为PetsApi**的API接口,其中包含YAML规范中定义的所有请求映射。这是代码段:

@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen",

 date = "2021-03-22T23:26:32.308871+05:30[Asia/Kolkata]")

 @Validated

 @Api(value = "pets", description = "the pets API")

 public interface PetsApi {

 /**

 * GET /pets : List all pets

 *

 * @param limit How many items to return at one time (max 100) (optional)

 * @return A paged array of pets (status code 200)

 * or unexpected error (status code 200)

 */

 @ApiOperation(value = "List all pets", nickname = "listPets", notes = "",

 response = Pet.class, responseContainer = "List", tags={ "pets", })

 @ApiResponses(value = { @ApiResponse(code = 200, message = "A paged array of pets",

 response = Pet.class, responseContainer = "List"),

 @ApiResponse(code = 200, message = "unexpected error", response = Error.class) })

 @GetMapping(value = "/pets", produces = { "application/json" })

 default ResponseEntity<List> listPets(@ApiParam(

 value = "How many items to return at one time (max 100)")

 @Valid @RequestParam(value = "limit", required = false) Integer limit) {

 return getDelegate().listPets(limit);

 }



 // other generated methods

 }

其次,由于我们使用委托模式,因此OpenAPI还会为我们PetsApiDelegate特别是,在此接口中声明的方法返回的HTTP状态默认为501未实现

@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen",

 date = "2021-03-22T23:26:32.308871+05:30[Asia/Kolkata]")

 public interface PetsApiDelegate {

 /**

 * GET /pets : List all pets

 *

 * @param limit How many items to return at one time (max 100) (optional)

 * @return A paged array of pets (status code 200)

 * or unexpected error (status code 200)

 * @see PetsApi#listPets

 */

 default ResponseEntity<List<Pet>> listPets(Integer limit) {

 getRequest().ifPresent(request -> {

 for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {

 if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {

 String exampleString = "{ \"name\" : \"name\", \"id\" : 0, \"tag\" : \"tag\" }";

 ApiUtil.setExampleResponse(request, "application/json", exampleString);

 break;

 }

 }

 });

 return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

 }



 // other generated method declarations

 }

在那之后,我们看到有一个PetsApiController类,它简单地连接了委托者

@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen",

 date = "2021-03-22T23:26:32.308871+05:30[Asia/Kolkata]")

 @Controller

 @RequestMapping("${openapi.swaggerPetstore.base-path:}")

 public class PetsApiController implements PetsApi {



 private final PetsApiDelegate delegate;



 public PetsApiController(

 @org.springframework.beans.factory.annotation.Autowired(required = false) PetsApiDelegate delegate) {

 this.delegate = Optional.ofNullable(delegate).orElse(new PetsApiDelegate() {});

 }



 @Override

 public PetsApiDelegate getDelegate() {

 return delegate;

 }

 }

modelPackage ,基于YAML输入中定义schemas ,生成ErrorPet的数据模型POJO。

让我们看看其中一个– Pet

@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen",

 date = "2021-03-22T23:26:32.308871+05:30[Asia/Kolkata]")

 public class Pet {

 @JsonProperty("id")

 private Long id;



 @JsonProperty("name")

 private String name;



 @JsonProperty("tag")

 private String tag;



 // constructor



 @ApiModelProperty(required = true, value = "")

 @NotNull

 public Long getId() {

 return id;

 }



 // other getters and setters



 // equals, hashcode, and toString methods

 }

5.测试服务器

现在,要使服务器存根作为服务器发挥作用,所需要做的就是添加委托者接口的实现。

为了简单起见,在这里我们不会这样做,而仅测试存根。此外,在此之前,我们需要一个Spring Application

@SpringBootApplication

 public class Application {

 public static void main(String[] args) {

 SpringApplication.run(Application.class, args);

 }

 }

5.1 使用curl

启动应用程序后,我们只需运行以下命令:

curl -I http://localhost:8080/pets/

这是预期的结果:

HTTP/1.1 501

 Content-Length: 0

 Date: Fri, 26 Mar 2021 17:29:25 GMT

 Connection: close

5.2 整合测试

另外,我们可以为它编写一个简单的集成测试:

@RunWith(SpringRunner.class)

 @SpringBootTest

 @AutoConfigureMockMvc

 public class OpenApiPetsIntegrationTest {

 private static final String PETS_PATH = "/pets/";



 @Autowired

 private MockMvc mockMvc;



 @Test

 public void whenReadAll_thenStatusIsNotImplemented() throws Exception {

 this.mockMvc.perform(get(PETS_PATH)).andExpect(status().isNotImplemented());

 }



 @Test

 public void whenReadOne_thenStatusIsNotImplemented() throws Exception {

 this.mockMvc.perform(get(PETS_PATH + 1)).andExpect(status().isNotImplemented());

 }

 }

六,结论

在本教程中,我们看到了如何使用OpenAPI生成器的maven插件根据YAML规范生成基于Spring的服务器存根

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *