Swagger 在线编辑器:http://editor.swagger.io/
在 Swagger 编辑器中粘贴上面代码,如下图
备注:一定要加 @CrossOrigin(origins = "*", allowedHeaders = "*") 解决跨域问题。
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
然后就可以在 swagger 里测试各种请求方式啦
备注:一定要开启跨域(即加--cors),否则获取不到数据
一、API 代码
- openapi: 3.0.0
- info:
- description: <p>Springboot 整合swagger demo,使用swagger2构建restful api . <p>
- version: 1.0.1
- title: 'Swagger editor demo '
- contact:
- name: 联系开发人员
- email: 847064370@qq.com
- servers:
- - url: 'http://{domain}:{port}/{basePath}'
- description: http请求
- variables:
- domain:
- default: localhost
- description: HTTP API请求域名
- port:
- enum:
- - '8080'
- - '8081'
- default: '8080'
- basePath:
- default: ''
- - url: 'https://{domain}:{port}/{basePath}'
- description: https请求
- variables:
- domain:
- default: localhost
- description: HTTPs API请求域名
- port:
- enum:
- - '8080'
- - '8081'
- default: '8080'
- basePath:
- default: ''
- tags:
- - name: user
- description: 用户相关操作
- components:
- schemas:
- ErrorCode:
- type: integer
- format: int64
- enum:
- - 0
- - 10001
- - 10002
- description: |
- 用户请求返回的信息码
- * 0:请求成功
- * 10001:用户名不存在
- * 10002:用户密码错误
- * 10003:内部错误
- ResultMessage:
- type: object
- properties:
- code:
- $ref: '#/components/schemas/ErrorCode'
- message:
- description: 错误信息描述
- type: string
- data:
- type: object
- description: 请求返回的内容(JSON类型)
- User:
- type: object
- properties:
- id:
- description: 主键ID
- type: string
- format: uuid
- username:
- description: 用户登录名
- type: string
- password:
- description: 密码
- type: string
- paths:
- /user:
- post:
- tags:
- - user
- summary: add user
- description: 新增用户信息
- operationId: addUser
- requestBody:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/User'
- responses:
- default:
- description: 请求成功后返回的内容
- content:
- application/json:
- schema:
- type: object
- properties:
- code:
- $ref: '#/components/schemas/ErrorCode'
- message:
- description: 错误信息描述
- type: string
- data:
- type: object
- description: 请求返回的内容(JSON类型)
- example:
- code: 0
- message: 请求成功
- data:
- id: 创建的用户的主键ID
- get:
- tags:
- - user
- summary: 批量获取用户信息
- responses:
- default:
- description: 请求成功后返回的内容
- content:
- application/json:
- schema:
- type: array
- items:
- $ref: '#/components/schemas/User'
- '/user/{userId}':
- get:
- tags:
- - user
- summary: find user by id
- description: 根据ID获取用户信息
- operationId: findUserById
- parameters:
- - name: userId
- in: path
- description: 用ID
- required: true
- schema:
- type: string
- responses:
- '400':
- description: 请求失败
- default:
- description: 请求成功后返回的内容
- content:
- application/json:
- schema:
- type: object
- properties:
- code:
- $ref: '#/components/schemas/ErrorCode'
- message:
- description: 错误信息描述
- type: string
- data:
- type: object
- description: 请求返回的内容(JSON类型)
- example:
- code: 0
- message: 操作成功
- data:
- user:
- id: uuid
- username: 用户登录名
- password: 用户密码
- put:
- tags:
- - user
- summary: update user
- description: 修改用户信息
- operationId: updateUser
- parameters:
- - name: userId
- in: path
- description: 用ID
- required: true
- schema:
- type: integer
- requestBody:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/User'
- responses:
- default:
- description: 操作请求成功
- content:
- application/json:
- schema:
- type: object
- properties:
- code:
- $ref: '#/components/schemas/ErrorCode'
- message:
- description: 错误信息描述
- type: string
- data:
- type: object
- description: 请求返回的内容(JSON类型)
- example:
- code: 0
- message: 操作成功
- data:
- user:
- id: uuid
- username: 用户登录名
- password: 用户密码
- delete:
- tags:
- - user
- summary: delete user
- description: 删除用户信息
- operationId: deleteUser
- parameters:
- - name: userId
- in: path
- description: 用ID
- required: true
- schema:
- type: string
- responses:
- default:
- description: 操作请求成功
- content:
- application/json:
- schema:
- type: object
- properties:
- code:
- $ref: '#/components/schemas/ErrorCode'
- message:
- description: 错误信息描述
- type: string
- data:
- type: object
- description: 请求返回的内容(JSON类型)
- example:
- code: 0
- message: 请求成功
- data:
- id: 删除的ID
- externalDocs:
- url: 'https:/liuyanzhao.com'
- description: '@言小曌'
在 Swagger 编辑器中粘贴上面代码,如下图
二、通过 SpringBoot 测试,验证
- package com.liuyanzhao.cloud.controller;
- import com.alibaba.fastjson.JSON;
- import com.liuyanzhao.cloud.entity.User;
- import com.liuyanzhao.cloud.repository.UserRepository;
- import com.liuyanzhao.cloud.vo.ResultVO;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.ResponseEntity;
- import org.springframework.web.bind.annotation.*;
- import javax.servlet.http.HttpServletResponse;
- import java.util.HashMap;
- import java.util.List;
- /**
- * @author 言曌
- * @date 2018/7/16 10:31
- */
- @CrossOrigin(origins = "*", allowedHeaders = "*")
- @RestController
- public class UserController {
- @Autowired
- private UserRepository userRepository;
- /**
- * 获得用户列表
- *
- * @return
- */
- @GetMapping("/user")
- public List<User> getUserList() {
- return userRepository.findAll();
- }
- /**
- * 根据ID查询用户
- *
- * @param id
- * @param response
- * @return
- */
- @GetMapping("/user/{id}")
- public ResponseEntity<ResultVO> getUser(@PathVariable("id") Integer id, HttpServletResponse response) {
- User user = userRepository.findOne(id);
- if (user != null) {
- HashMap<String,User> map = new HashMap<>();
- map.put("user",user);
- return ResponseEntity.ok().body(new ResultVO(0, "操作成功", map));
- } else {
- response.setStatus(404);
- return ResponseEntity.ok().body(new ResultVO(10001, "用户不存在"));
- }
- }
- /**
- * 添加新用户
- *
- * @param user
- * @param response
- * @return
- */
- @PostMapping("/user")
- public ResponseEntity<ResultVO> saveUser(@RequestBody User user, HttpServletResponse response) {
- User result = null;
- try {
- result = userRepository.save(user);
- } catch (Exception e) {
- response.setStatus(500);
- ResponseEntity.ok().body(new ResultVO(10003, "添加失败!"));
- }
- HashMap<String,User> map = new HashMap<>();
- map.put("user",result);
- return ResponseEntity.ok().body(new ResultVO(0, "操作成功!", map));
- }
- /**
- * 修改用户
- *
- * @param user
- * @return
- */
- @PutMapping("/user/{id}")
- public ResponseEntity<ResultVO> updateUser(@PathVariable("id") Integer id, @RequestBody User user, HttpServletResponse response) {
- User originalUser = userRepository.findOne(id);
- if(originalUser == null) {
- response.setStatus(404);
- return ResponseEntity.ok().body(new ResultVO(10001, "用户不存在"));
- }
- User result = null;
- try {
- originalUser.setUsername(user.getUsername());
- originalUser.setPassword(user.getPassword());
- result = userRepository.save(user);
- } catch (Exception e) {
- response.setStatus(500);
- ResponseEntity.ok().body(new ResultVO(10003, "更新失败!"));
- }
- HashMap<String,User> map = new HashMap<>();
- map.put("user",result);
- return ResponseEntity.ok().body(new ResultVO(0, "操作成功!", map));
- }
- /**
- * 删除用户
- *
- * @param id
- * @param response
- * @return
- */
- @DeleteMapping("/user/{id}")
- public ResponseEntity<ResultVO> deleteUser(@PathVariable("id") Integer id, HttpServletResponse response) {
- try {
- userRepository.delete(id);
- } catch (Exception e) {
- response.setStatus(404);
- return ResponseEntity.ok().body(new ResultVO(10001,"用户不存在!"));
- }
- HashMap<String,Integer> map = new HashMap<>();
- map.put("id",id);
- return ResponseEntity.ok().body(new ResultVO(0,"请求成功",map));
- }
- }
备注:一定要加 @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
然后就可以在 swagger 里测试各种请求方式啦
备注:一定要开启跨域(即加--cors),否则获取不到数据
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏