一个简单的 OpenAPI3.0 实例,使用 SpringBoot 和 Prism 测试

Swagger 在线编辑器:http://editor.swagger.io/

一、API 代码

  1. openapi: 3.0.0
  2. info:
  3.   description: <p>Springboot 整合swagger demo,使用swagger2构建restful api . <p>
  4.   version: 1.0.1
  5.   title: 'Swagger editor demo '
  6.   contact:
  7.     name: 联系开发人员
  8.     email: 847064370@qq.com
  9. servers:
  10.   - url: 'http://{domain}:{port}/{basePath}'
  11.     description: http请求
  12.     variables:
  13.       domain:
  14.         default: localhost
  15.         description: HTTP API请求域名
  16.       port:
  17.         enum:
  18.           - '8080'
  19.           - '8081'
  20.         default: '8080'
  21.       basePath:
  22.         default''
  23.   - url: 'https://{domain}:{port}/{basePath}'
  24.     description: https请求
  25.     variables:
  26.       domain:
  27.         default: localhost
  28.         description: HTTPs API请求域名
  29.       port:
  30.         enum:
  31.           - '8080'
  32.           - '8081'
  33.         default: '8080'
  34.       basePath:
  35.         default''
  36. tags:
  37.   - name: user
  38.     description: 用户相关操作
  39. components:
  40.   schemas:
  41.     ErrorCode:
  42.       type: integer
  43.       format: int64
  44.       enum:
  45.         - 0
  46.         - 10001
  47.         - 10002
  48.       description: |
  49.         用户请求返回的信息码
  50.           * 0:请求成功
  51.           * 10001:用户名不存在
  52.           * 10002:用户密码错误
  53.           * 10003:内部错误
  54.     ResultMessage:
  55.       type: object
  56.       properties:
  57.         code:
  58.           $ref: '#/components/schemas/ErrorCode'
  59.         message:
  60.           description: 错误信息描述
  61.           type: string
  62.         data:
  63.           type: object
  64.           description: 请求返回的内容(JSON类型)
  65.     User:
  66.       type: object
  67.       properties:
  68.         id:
  69.           description: 主键ID
  70.           type: string
  71.           format: uuid
  72.         username:
  73.           description: 用户登录名
  74.           type: string
  75.         password:
  76.           description: 密码
  77.           type: string
  78. paths:
  79.   /user:
  80.     post:
  81.       tags:
  82.         - user
  83.       summary: add user
  84.       description: 新增用户信息
  85.       operationId: addUser
  86.       requestBody:
  87.         content:
  88.           application/json:
  89.             schema:
  90.               $ref: '#/components/schemas/User'
  91.       responses:
  92.         default:
  93.           description: 请求成功后返回的内容
  94.           content:
  95.             application/json:
  96.               schema:
  97.                 type: object
  98.                 properties:
  99.                   code:
  100.                     $ref: '#/components/schemas/ErrorCode'
  101.                   message:
  102.                     description: 错误信息描述
  103.                     type: string
  104.                   data:
  105.                     type: object
  106.                     description: 请求返回的内容(JSON类型)
  107.                 example:
  108.                   code: 0
  109.                   message: 请求成功
  110.                   data:
  111.                     id: 创建的用户的主键ID
  112.     get:
  113.       tags:
  114.         - user
  115.       summary: 批量获取用户信息
  116.       responses:
  117.         default:
  118.           description: 请求成功后返回的内容
  119.           content:
  120.             application/json:
  121.               schema:
  122.                 type: array
  123.                 items:
  124.                   $ref: '#/components/schemas/User'
  125.   '/user/{userId}':
  126.     get:
  127.       tags:
  128.         - user
  129.       summary: find user by id
  130.       description: 根据ID获取用户信息
  131.       operationId: findUserById
  132.       parameters:
  133.         - name: userId
  134.           in: path
  135.           description: 用ID
  136.           required: true
  137.           schema:
  138.             type: string
  139.       responses:
  140.         '400':
  141.           description: 请求失败
  142.         default:
  143.           description: 请求成功后返回的内容
  144.           content:
  145.             application/json:
  146.               schema:
  147.                 type: object
  148.                 properties:
  149.                   code:
  150.                     $ref: '#/components/schemas/ErrorCode'
  151.                   message:
  152.                     description: 错误信息描述
  153.                     type: string
  154.                   data:
  155.                     type: object
  156.                     description: 请求返回的内容(JSON类型)
  157.                 example:
  158.                   code: 0
  159.                   message: 操作成功
  160.                   data:
  161.                     user:
  162.                       id: uuid
  163.                       username: 用户登录名
  164.                       password: 用户密码
  165.     put:
  166.       tags:
  167.         - user
  168.       summary: update user
  169.       description: 修改用户信息
  170.       operationId: updateUser
  171.       parameters:
  172.         - name: userId
  173.           in: path
  174.           description: 用ID
  175.           required: true
  176.           schema:
  177.             type: integer
  178.       requestBody:
  179.         content:
  180.           application/json:
  181.             schema:
  182.               $ref: '#/components/schemas/User'
  183.       responses:
  184.         default:
  185.           description: 操作请求成功
  186.           content:
  187.             application/json:
  188.               schema:
  189.                 type: object
  190.                 properties:
  191.                   code:
  192.                     $ref: '#/components/schemas/ErrorCode'
  193.                   message:
  194.                     description: 错误信息描述
  195.                     type: string
  196.                   data:
  197.                     type: object
  198.                     description: 请求返回的内容(JSON类型)
  199.                 example:
  200.                   code: 0
  201.                   message: 操作成功
  202.                   data:
  203.                     user:
  204.                       id: uuid
  205.                       username: 用户登录名
  206.                       password: 用户密码
  207.     delete:
  208.       tags:
  209.         - user
  210.       summary: delete user
  211.       description: 删除用户信息
  212.       operationId: deleteUser
  213.       parameters:
  214.         - name: userId
  215.           in: path
  216.           description: 用ID
  217.           required: true
  218.           schema:
  219.             type: string
  220.       responses:
  221.         default:
  222.           description: 操作请求成功
  223.           content:
  224.             application/json:
  225.               schema:
  226.                 type: object
  227.                 properties:
  228.                   code:
  229.                     $ref: '#/components/schemas/ErrorCode'
  230.                   message:
  231.                     description: 错误信息描述
  232.                     type: string
  233.                   data:
  234.                     type: object
  235.                     description: 请求返回的内容(JSON类型)
  236.                 example:
  237.                   code: 0
  238.                   message: 请求成功
  239.                   data:
  240.                     id: 删除的ID
  241. externalDocs:
  242.   url: 'https:/liuyanzhao.com'
  243.   description: '@言小曌'

在 Swagger 编辑器中粘贴上面代码,如下图

一个简单的 OpenAPI3.0 实例,使用 SpringBoot 和 Prism 测试

 

二、通过 SpringBoot 测试,验证

  1. package com.liuyanzhao.cloud.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.liuyanzhao.cloud.entity.User;
  4. import com.liuyanzhao.cloud.repository.UserRepository;
  5. import com.liuyanzhao.cloud.vo.ResultVO;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.web.bind.annotation.*;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.util.HashMap;
  11. import java.util.List;
  12. /**
  13.  * @author 言曌
  14.  * @date 2018/7/16 10:31
  15.  */
  16. @CrossOrigin(origins = "*", allowedHeaders = "*")
  17. @RestController
  18. public class UserController {
  19.     @Autowired
  20.     private UserRepository userRepository;
  21.     /**
  22.      * 获得用户列表
  23.      *
  24.      * @return
  25.      */
  26.     @GetMapping("/user")
  27.     public List<User> getUserList() {
  28.         return userRepository.findAll();
  29.     }
  30.     /**
  31.      * 根据ID查询用户
  32.      *
  33.      * @param id
  34.      * @param response
  35.      * @return
  36.      */
  37.     @GetMapping("/user/{id}")
  38.     public ResponseEntity<ResultVO> getUser(@PathVariable("id") Integer id, HttpServletResponse response) {
  39.         User user = userRepository.findOne(id);
  40.         if (user != null) {
  41.             HashMap<String,User> map = new HashMap<>();
  42.             map.put("user",user);
  43.             return ResponseEntity.ok().body(new ResultVO(0"操作成功", map));
  44.         } else {
  45.             response.setStatus(404);
  46.             return ResponseEntity.ok().body(new ResultVO(10001"用户不存在"));
  47.         }
  48.     }
  49.     /**
  50.      * 添加新用户
  51.      *
  52.      * @param user
  53.      * @param response
  54.      * @return
  55.      */
  56.     @PostMapping("/user")
  57.     public ResponseEntity<ResultVO> saveUser(@RequestBody User user, HttpServletResponse response) {
  58.         User result = null;
  59.         try {
  60.             result = userRepository.save(user);
  61.         } catch (Exception e) {
  62.             response.setStatus(500);
  63.             ResponseEntity.ok().body(new ResultVO(10003"添加失败!"));
  64.         }
  65.         HashMap<String,User> map = new HashMap<>();
  66.         map.put("user",result);
  67.         return ResponseEntity.ok().body(new ResultVO(0"操作成功!", map));
  68.     }
  69.     /**
  70.      * 修改用户
  71.      *
  72.      * @param user
  73.      * @return
  74.      */
  75.     @PutMapping("/user/{id}")
  76.     public ResponseEntity<ResultVO> updateUser(@PathVariable("id") Integer id, @RequestBody User user, HttpServletResponse response) {
  77.         User originalUser = userRepository.findOne(id);
  78.         if(originalUser == null) {
  79.             response.setStatus(404);
  80.             return ResponseEntity.ok().body(new ResultVO(10001"用户不存在"));
  81.         }
  82.         User result = null;
  83.         try {
  84.             originalUser.setUsername(user.getUsername());
  85.             originalUser.setPassword(user.getPassword());
  86.             result = userRepository.save(user);
  87.         } catch (Exception e) {
  88.             response.setStatus(500);
  89.             ResponseEntity.ok().body(new ResultVO(10003"更新失败!"));
  90.         }
  91.         HashMap<String,User> map = new HashMap<>();
  92.         map.put("user",result);
  93.         return ResponseEntity.ok().body(new ResultVO(0"操作成功!", map));
  94.     }
  95.     /**
  96.      * 删除用户
  97.      *
  98.      * @param id
  99.      * @param response
  100.      * @return
  101.      */
  102.     @DeleteMapping("/user/{id}")
  103.     public ResponseEntity<ResultVO> deleteUser(@PathVariable("id") Integer id, HttpServletResponse response) {
  104.         try {
  105.             userRepository.delete(id);
  106.         } catch (Exception e) {
  107.             response.setStatus(404);
  108.             return ResponseEntity.ok().body(new ResultVO(10001,"用户不存在!"));
  109.         }
  110.         HashMap<String,Integer> map = new HashMap<>();
  111.         map.put("id",id);
  112.         return ResponseEntity.ok().body(new ResultVO(0,"请求成功",map));
  113.     }
  114. }

备注:一定要加 @CrossOrigin(origins = "*", allowedHeaders = "*")  解决跨域问题。

 

三、使用 Prism 测试

1、下载 prism

prism 下载地址:http://stoplight.io/platform/prism/

windows下 下载完成后是一个 prism_windows_amd64.exe 文件

 

2、保存 OpenAPI 代码到文件中

将上面的代码保存为一个 json 或 yaml 文件,比如我这里保存为 swagger.yaml

 

3、运行之

prism_windows_amd64.exe run --mock --list --cors --spec E:\桌面\swagger.yaml

一个简单的 OpenAPI3.0 实例,使用 SpringBoot 和 Prism 测试

 

然后就可以在 swagger 里测试各种请求方式啦

备注:一定要开启跨域(即加--cors),否则获取不到数据

 

 

 

 

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
言曌

发表评论

:?::razz::sad::evil::!::smile::oops::grin::eek::shock::???::cool::lol::mad::twisted::roll::wink::idea::arrow::neutral::cry::mrgreen: