使用Swagger和OpenAPI 3规范定义API接口并集成到SpringBoot

1. OpenAPI 3 规范介绍及属性定义

参考官方定义:https://swagger.io/specification/

2. 使用OpenAPI 3规范定义API接口

官方样例参考:https://editor.swagger.io/

可以在此页面进行编辑,编辑后的效果所见即所得

 

3. SwaggerUI展示及调试

左侧的接口定义好后,在右侧会出现相应的接口定义及响应参考相关信息,所见即所得,并且可以调试。

 

4. 接口定义集成到SpringBoot项目自动生成接口

1)pom.xml文件引入swagger-codegen-maven-plugin用于基于swagger定义的接口yaml文件生成对应的接口Java代码。

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>8</java.version>
    </properties>

    <groupId>com.learning.java</groupId>
    <artifactId>snippet</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>2.1.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>io.swagger.codegen.v3</groupId>
                <artifactId>swagger-codegen-maven-plugin</artifactId>
                <version>3.0.29</version>
                <!--https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen-maven-plugin/README.md#general-configuration-parameters-->
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <inputSpec>${project.basedir}/src/main/resources/yaml/student.yaml</inputSpec>
                            <language>spring</language>
                            <apiPackage>com.learning.java.api</apiPackage>
                            <modelPackage>com.learning.java.model</modelPackage>
                            <configOptions>
                                <delegatePattern>true</delegatePattern>
                                <interfaceOnly>true</interfaceOnly>
                                <java8>true</java8>
                                <useTags>true</useTags>
                            </configOptions>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
复制代码

2)项目的src/main/resources/yaml/student.yaml文件为接口定义文件

复制代码
openapi: 3.0.3
info:
  title: Swagger Student
  version: 1.0.0
  description: "学生服务,可对学生信息进行增删改查操作"
  termsOfService: http://swagger.io/terms/
  contact:
    email: apiteam@swagger.io
  license:
    name: Apache 2.0
    url: http://www.apache.org/licenses/LICENSE-2.0.html
externalDocs:
  description: Find out more about Swagger
  url: http://swagger.io
servers:
  - url: https://student.swagger.io/v2
  - url: http://student.swagger.io/v2
tags:
  - name: StudentServer
    description: "学生服务"
    externalDocs:
      description: Find out more
      url: http://swagger.io
paths:
  /v1/students:
    post:
      tags:
        - StudentServer
      summary: "新增一个学生"
      operationId: AddStudent
      requestBody:
        description: "学生信息"
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Student'
            example:
              id: 0
              name: "张三"
              age: 18
              sex: "boy"
      responses:
        201:
          description: Created
        400:
          description: Bad Request
        401:
          description: Unauthorized
        403:
          description: Forbidden
      x-request-examples-description-1: "新增学生请求示例"
      x-request-examples-url-1: "POST https://{endpoint}/v1/students"
      x-request-examples-1:
        id: 0
        name: "张三"
        age: 18
        sex: "boy"
    put:
      tags:
        - StudentServer
      summary: "更新学生信息"
      operationId: UpdateStudent
      requestBody:
        description: "学生信息"
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Student'
            example:
              id: 0
              name: "张三"
              age: 18
              sex: "boy"
      responses:
        200:
          description: OK
        400:
          description: Bad Request
        401:
          description: Unauthorized
        403:
          description: Forbidden
      x-request-examples-description-1: "更新学生请求示例"
      x-request-examples-url-1: "PUT https://{endpoint}/v1/students"
      x-request-examples-1:
        id: 0
        name: "张三"
        age: 18
        sex: "boy"
  /v1/students/{id}:
    get:
      tags:
        - StudentServer
      summary: "通过学号查询学生信息"
      operationId: ShowStudentById
      parameters:
        - name: id
          in: path
          description: "学号"
          required: true
          schema:
            type: integer
            format: int32
            minimum: 0
            maximum: 100
            example: 0
      responses:
        200:
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Student'
              example:
                id: 0
                name: "张三"
                age: 18
                sex: "boy"
        400:
          description: Bad Request
        401:
          description: Unauthorized
        403:
          description: Forbidden
        404:
          description: Not Found
      x-request-examples-description-1: "查询学生信息请求示例"
      x-request-examples-url-1: "GET https://{endpoint}/v1/students/0"
    delete:
      tags:
        - StudentServer
      summary: "删除学生信息"
      operationId: DeleteStudentById
      parameters:
        - name: id
          in: path
          description: "学号"
          required: true
          schema:
            type: integer
            format: int32
            minimum: 0
            maximum: 100
            example: 0
      responses:
        204:
          description: No Content
        400:
          description: Bad Request
        401:
          description: Unauthorized
        403:
          description: Forbidden
        404:
          description: Not Found
      x-request-examples-description-1: "删除学生请求示例"
      x-request-examples-url-1: "DELETE https://{endpoint}/v1/students/0"
components:
  schemas:
    Student:
      description: "学生信息"
      required:
        - id
        - name
        - age
        - sex
      properties:
        id:
          description: "学号"
          type: integer
          format: int32
          minimum: 0
          maximum: 100
          example: 0
        name:
          description: "姓名"
          type: string
          minLength: 0
          maxLength: 10
          example: "张三"
        age:
          description: "年龄"
          type: integer
          format: int32
          minimum: 6
          maximum: 30
          example: 18
        sex:
          description: "性别"
          type: string
          enum:
            - boy
            - girl
          minLength: 3
          maxLength: 4
          example: boy
复制代码

 3)Spring程序main入口

复制代码
package com.learning.java;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
复制代码

4) Controller 层

复制代码
package com.learning.java.controller;

import com.learning.java.api.StudentServerApi;
import com.learning.java.model.Student;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;

@RestController
public class StudentServerController implements StudentServerApi {
    @Override
    public ResponseEntity<Void> addStudent(Student body) {
        return ResponseEntity.created(URI.create("/v1/students" + body.getName())).build();
    }
}
复制代码

5. 编译自动生成接口文件及model文件

 

 

 6. 集成spring文档能力

参考文档 https://www.baeldung.com/spring-rest-openapi-documentation

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.6.4</version>
        </dependency>

7. 启动服务

 

 

8.  访问服务接口文档及调试

本地启动地址 http://localhost:8080/swagger-ui.html

该页面与yaml接口定义时展示的界面基本一致,只不过这个页面是基于RestController层的接口生成的swaggerui界面,而前面是基于OpenAPI 3规范定义的接口生成的swaggerui页面

 

可在此页面发起调试,找到对应接口Try it out,输入对应参数,发起调试,会给我们生成curl命令,同时可以收到Server response

 

 

 

 

 

 

 

posted on   相思羽  阅读(3111)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示