swagger配置的一个demo

swagger的DEMO配置@TOC

认识swagger

Swagger 是一款RESTFUL接口的、基于YAML、JSON语言的文档在线自动生成、代码自动生成的工具。
官方网址:https://swagger.io/

作用:

作用:
1. 接口的文档在线自动生成。
2. 功能测试。

配置步骤

1.需要一个有一个文件:SwaggerConfig.class

package cn.itrip.auth.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@ComponentScan(basePackages = {"cn.itrip.auth.controller"})
@Configuration
public class SwaggerConfig extends WebMvcConfigurationSupport {
    public SwaggerConfig() { }

    @Bean
    public Docket createRestApi() {
        return (new Docket(DocumentationType.SWAGGER_2)).apiInfo(this.apiInfo()).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return (new ApiInfoBuilder()).title("主业务模块API").termsOfServiceUrl("http://www.itrip.com/biz").contact("0101项目组").version("1.0").build();
    }

}

2.在资源配置文件application.xml加入相关代码

<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

在头部需要加入http://www.springframework.org/schema/task/spring-task.xsd这一句
底下还需要写这么一句
<mvc:default-servlet-handler />
3.在自己的corttller层的方法前面需要加入相应的swagger注解

/**
     * 检查用户是否已注册
     * @param name
     * @return
     */
    @ApiOperation(value="用户名验证",httpMethod = "GET",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class,notes="验证是否已存在该用户名")
    @RequestMapping(value="/ckusrPhone",method=RequestMethod.GET,produces= "application/json")
    public @ResponseBody
    Dto checkUser(
            @ApiParam(name="name",value="被检查的用户名",defaultValue="15717396714")
            @RequestParam String name) {
        System.out.println("用户名注册名是否唯一!");
        try {
            if(!validPhone(name))
                return  DtoUtil.returnFail("请使用正确的手机注册",ErrorCode.AUTH_ILLEGAL_USERCODE);
            if (null == userService.findByUsername(name)) {
                return DtoUtil.returnSuccess("手机号码可用");
            } else {
                return DtoUtil.returnFail("手机号码已存在,注册失败", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }

4.运行自己的项目
在自己的项目名后面加上/swagger-ui.html
就会出现页面
显示的相应的接口,在里面可以写参数发送请求,返回的参数值

常用注解解析

这里没有的注解可以参考API文档
https://github.com/springfox/springfox/blob/master/docs/transitioning-to-v2.md

@Api()用于类;
表示标识这个类是swagger的资源

  • @ApiOperation()用于方法;
    表示一个http请求的操作
  • @ApiParam()用于方法,参数,字段说明;
    表示对参数的添加元数据(说明或是否必填等)
  • @ApiModel()用于类
    表示对类进行说明,用于参数用实体类接收
  • @ApiModelProperty()用于方法,字段
    表示对model属性的说明或者数据操作更改
  • @ApiImplicitParam() 用于方法
    表示单独的请求参数
  • @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
好的,下面是一个使用 Django、Django REST framework 和 Swagger 的后端框架 demo。 首先,需要安装 Django、Django REST framework 和 Swagger: ``` pip install Django pip install djangorestframework pip install django-rest-swagger ``` 接着,创建一个 Django 项目: ``` django-admin startproject demo ``` 然后,在项目根目录下创建一个名为 `api` 的 Django app: ``` cd demo python manage.py startapp api ``` 接下来,修改 `demo/settings.py` 文件,将 `api` app 添加到 `INSTALLED_APPS` 列表中: ```python INSTALLED_APPS = [ # ... 'rest_framework', 'rest_framework_swagger', 'api', ] ``` 然后,在 `api` app 下创建一个名为 `views.py` 的文件,用于编写 API 视图函数: ```python from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def hello(request): """ 返回一个简单的字符串 """ return Response("Hello, world!") ``` 接着,在 `api` app 下创建一个名为 `urls.py` 的文件,用于配置 API 路由: ```python from django.urls import path from rest_framework_swagger.views import get_swagger_view from . import views schema_view = get_swagger_view(title='API文档') urlpatterns = [ path('', schema_view), path('hello/', views.hello), ] ``` 最后,修改 `demo/settings.py` 文件,设置 REST framework 和 Swagger配置: ```python REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Basic': { 'type': 'basic' } }, } ``` 现在,运行 Django 项目: ``` python manage.py runserver ``` 在浏览器中访问 `http://127.0.0.1:8000/api/`,即可看到 Swagger 的 API 文档界面。在其中可以看到一个名为 `hello` 的 API,点击该 API 可以进行测试,测试结果将会返回一个字符串 "Hello, world!"。 这就是使用 Django、Django REST framework 和 Swagger 编写的一个后端框架 demo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值