在线api接口文档生成(api接口文档是干什么的)

网友投稿 229 2023-02-19


本篇文章给大家谈谈在线api接口文档生成,以及api接口文档是干什么的对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。 今天给各位分享在线api接口文档生成的知识,其中也会对api接口文档是干什么的进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

如何使 WebAPI 自动生成漂亮又实用在线API文档

1.1 SwaggerUI
SwaggerUI 是一个简单在线api接口文档生成的Restful API 测试和文档工具。简单、漂亮、易用(官方demo)。通过读取JSON 配置显示API. 项目本身仅仅也只依赖一些 html,css.js静态文件. 你可以几乎放在任何Web容器上使用。
1.2 Swashbuckle
Swashbuckle 是.NET类库,可以将WebAPI所有开放的控制器方法生成对应SwaggerUI的JSON配置。再通过SwaggerUI 显示出来。类库中已经包含SwaggerUI 。所以不需要额外安装。
2.快速开始
创建项目 OnlineAPI来封装百度音乐服务(示例下载) ,通过API可以搜索、获取音乐的信息和播放连接。
我尽量删除一些我们demo中不会用到的一些文件,使其看上去比较简洁。
WebAPI 安装 Swashbuckle
Install-Package Swashbuckle
代码注释生成文档说明。
Swashbuckle 是通过生成的XML文件来读取注释的,生成 SwaggerUI,JSON 配置中的说明的。
安装时会在项目目录 App_Start 文件夹下生成一个 SwaggerConfig.cs 配置文件,用于配置 SwaggerUI 相关展示行为的。如图在线api接口文档生成
将配置文件大概99行注释去掉并修改为
c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name));
并在当前类中添加一个方法
/// <summary
/// </summary
/// <param name="name"</param
/// <returns</returns
protected static string GetXmlCommentsPath(string name)
{
return string.Format(@"{0}\bin\{1}.XML", AppDomain.CurrentDomain.BaseDirectory, name);
}
紧接着你在此Web项目属性生成选卡中勾选 “XML 文档文件”,编译过程中生成类库的注释文件
添加百度音乐 3个API
访问 lt;youhost/swagger/ui/index,最终显示效果
我们通过API 测试API 是否成功运行
3.添加自定义HTTP Header
在开发移动端 API时常常需要验证权限,验证参数放在Http请求头中是再好不过在线api接口文档生成了。WebAPI配合过滤器验证权限即可
首先我们需要创建一个 IOperationFilter 接口的类。IOperationFilter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Filters;
using Swashbuckle.Swagger;
namespace OnlineAPI.Utility
{
public class HttpHeaderFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry
schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null) operation.parameters = new
List<Parameter();
var filterPipeline =
apiDescription.ActionDescriptor.GetFilterPipeline();
//判断是否添加权限过滤器
var isAuthorized = filterPipeline.Select(filterInfo =
filterInfo.Instance).Any(filter = filter is IAuthorizationFilter);
//判断是否允许匿名方法
var allowAnonymous =
apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute().Any();
if (isAuthorized !allowAnonymous)
{
operation.parameters.Add(new Parameter
{
name = "access-key",
@in = "header",
description = "用户访问Key",
required = false,
type = "string"
});
}
}
}
}
在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法类添加一行注册代码
c.OperationFilter<HttpHeaderFilter();
添加Web权限过滤器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Newtonsoft.Json;
namespace OnlineAPI.Utility
{
/// <summary
///
/// </summary
public class AccessKeyAttribute : AuthorizeAttribute
{
/// <summary
/// 权限验证
/// </summary
/// <param name="actionContext"</param
/// <returns</returns
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var request = actionContext.Request;
if (request.Headers.Contains("access-key"))
{
var accessKey = request.Headers.GetValues("access-key").SingleOrDefault();
//TODO 验证Key
return accessKey == "123456789";
}
return false;
}
/// <summary
/// 处理未授权的请求
/// </summary
/// <param name="actionContext"</param
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var content = JsonConvert.SerializeObject(new {State = HttpStatusCode.Unauthorized});
actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
}
在你想要的ApiController 或者是 Action 添加过滤器
[AccessKey]
最终显示效果
4.显示上传文件参数
SwaggerUI 有上传文件的功能和添加自定义HTTP Header 做法类似,只是我们通过特殊的设置来标示API具有上传文件的功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Description;
using Swashbuckle.Swagger;
namespace OnlineAPI.Utility
{
/// <summary
///
/// </summary
public class UploadFilter : IOperationFilter
{
/// <summary
/// 文件上传
/// </summary
/// <param name="operation"</param
/// <param name="schemaRegistry"</param
/// <param name="apiDescription"</param
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (!string.IsNullOrWhiteSpace(operation.summary) operation.summary.Contains("upload"))
{
operation.consumes.Add("application/form-data");
operation.parameters.Add(new Parameter
{
name = "file",
@in = "formData",
required = true,
type = "file"
});
}
}
}
}
在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法类添加一行注册代码
c.OperationFilter<UploadFilter();
API 文档展示效果

如何优雅的“编写”api接口文档

一些刚开始写接口文档的服务端同学,很容易按着代码的思路去编写接口文档,这让客户端同学或者是服务对接方技术人员经常吐槽,看不懂接口文档。这篇文章提供一个常规接口文档的编写方法,给大家参考。


推荐使用的是docway 写接口文档,方便保存和共享,支持导出PDF MARKDOWN,支持团队项目管理。

一、请求参数

1. 请求方法

GET

用于获取数据

POST

用于更新数据,可与PUT互换,语义上PUT支持幂等

PUT

用于新增数据,可与POST互换,语义上PUT支持幂等

DELETE

用于删除数据

其他

其他的请求方法在一般的接口中很少使用。如:PATCH HEAD OPTIONS

2. URL

url表示了接口的请求路径。路径中可以包含参数,称为地址参数,如**/user/{id}**,其中id作为一个参数。

3. HTTP Header

HTTP Header用于此次请求的基础信息,在接口文档中以K-V方式展示,其中Content-Type则是一个非常必要的header,它描述的请求体的数据类型。

常用的content-type:

application/x-www-form-urlencoded

请求参数使用“”符号连接。

application/json

内容为json格式

application/xml

内容为xml格式

multipart/form-data

内容为多个数据组成,有分隔符隔开

4. HTTP Body

描述http body,依赖于body中具体的数据类型。如果body中的数据是对象类型。则需要描述对象中字段的名称、类型、长度、不能为空、默认值、说明。以表格的方式来表达最好。

示例:

二、响应参数

1. 响应 HTTP Body

响应body同请求body一样,需要描述请清除数据的类型。

另外,如果服务会根据不同的http status code 返回不同的数据结构, 也需要针对不同的http status code对内容进行描述。

三、接口说明

说明接口的应用场景,特别的注意点,比如,接口是否幂等、处理是同步方式还是异步方式等。

四、示例

上个示例(重点都用红笔圈出来,记牢了):

五、接口工具

推荐使用的是http://docway.net(以前叫小幺鸡) 写接口文档,方便保存和共享,支持导出PDF MARKDOWN,支持团队项目管理。

神器 SpringDoc 横空出世!最适合 SpringBoot 的API文档工具来了

之前在SpringBoot项目中一直使用的是SpringFox提供的Swagger库在线api接口文档生成,上了下官网发现已经有接近两年没出新版本了!前几天升级了SpringBoot 2.6.x 版本,发现这个库的兼容性也越来越不好了,有的常用注解属性被废弃了居然都没提供替代!无意中发现了另一款Swagger库SpringDoc,试用了一下非常不错,推荐给大家!

SpringDoc简介

SpringDoc是一款可以结合SpringBoot使用的API文档生成工具,基于OpenAPI 3,目前在Github上已有1.7K+Star,更新发版还是挺勤快的,是一款更好用的Swagger库!值得一提的是SpringDoc不仅支持Spring WebMvc项目,还可以支持Spring WebFlux项目,甚至Spring Rest和Spring Native项目,总之非常强大,下面是一张SpringDoc的架构图。

使用

接下来我们介绍下SpringDoc的使用,使用的是之前集成SpringFox的mall-tiny-swagger项目,我将把它改造成使用SpringDoc。

集成

首先我们得集成SpringDoc,在pom.xml中添加它的依赖即可,开箱即用,无需任何配置。

<!--springdoc 官方Starter--org.springdocspringdoc-openapi-ui1.6.6

从SpringFox迁移

我们先来看下经常使用的Swagger注解,看看SpringFox的和SpringDoc的有啥区别,毕竟对比已学过的技术能该快掌握新技术;

接下来我们对之前Controller中使用的注解进行改造,对照上表即可,之前在@Api注解中被废弃了好久又没有替代的description属性终于被支持了!

/**

* 品牌管理Controller

* Created by macro on 2019/4/19.

*/@Tag(name ="PmsBrandController", description ="商品品牌管理")@Controller@RequestMapping("/brand")publicclassPmsBrandController{@AutowiredprivatePmsBrandService brandService;privatestaticfinalLogger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);@Operation(summary ="获取所有品牌列表",description ="需要登录后访问")@RequestMapping(value ="listAll", method = RequestMethod.GET)@ResponseBodypublicCommonResult getBrandList() {returnCommonResult.success(brandService.listAllBrand());    }@Operation(summary ="添加品牌")@RequestMapping(value ="/create", method = RequestMethod.POST)@ResponseBody@PreAuthorize("hasRole('ADMIN')")publicCommonResult createBrand(@RequestBodyPmsBrand pmsBrand) {        CommonResult commonResult;        int count = brandService.createBrand(pmsBrand);if(count ==1) {            commonResult = CommonResult.success(pmsBrand);            LOGGER.debug("createBrand success:{}", pmsBrand);        }else{            commonResult = CommonResult.failed("操作失败");            LOGGER.debug("createBrand failed:{}", pmsBrand);        }returncommonResult;    }@Operation(summary ="更新指定id品牌信息")@RequestMapping(value ="/update/{id}", method = RequestMethod.POST)@ResponseBody@PreAuthorize("hasRole('ADMIN')")publicCommonResult updateBrand(@PathVariable("id")Longid,@RequestBodyPmsBrand pmsBrandDto, BindingResult result) {        CommonResult commonResult;        int count = brandService.updateBrand(id, pmsBrandDto);if(count ==1) {            commonResult = CommonResult.success(pmsBrandDto);            LOGGER.debug("updateBrand success:{}", pmsBrandDto);        }else{            commonResult = CommonResult.failed("操作失败");            LOGGER.debug("updateBrand failed:{}", pmsBrandDto);        }returncommonResult;    }@Operation(summary ="删除指定id的品牌")@RequestMapping(value ="/delete/{id}", method = RequestMethod.GET)@ResponseBody@PreAuthorize("hasRole('ADMIN')")publicCommonResult deleteBrand(@PathVariable("id")Longid) {        int count = brandService.deleteBrand(id);if(count ==1) {            LOGGER.debug("deleteBrand success :id={}", id);returnCommonResult.success(null);        }else{            LOGGER.debug("deleteBrand failed :id={}", id);returnCommonResult.failed("操作失败");        }    }@Operation(summary ="分页查询品牌列表")@RequestMapping(value ="/list", method = RequestMethod.GET)@ResponseBody@PreAuthorize("hasRole('ADMIN')")publicCommonResult listBrand(@RequestParam(value ="pageNum", defaultValue ="1")@Parameter(description ="页码")Integer pageNum,@RequestParam(value ="pageSize", defaultValue ="3")@Parameter(description ="每页数量")Integer pageSize) {        List brandList = brandService.listBrand(pageNum, pageSize);returnCommonResult.success(CommonPage.restPage(brandList));    }@Operation(summary ="获取指定id的品牌详情")@RequestMapping(value ="/{id}", method = RequestMethod.GET)@ResponseBody@PreAuthorize("hasRole('ADMIN')")publicCommonResult brand(@PathVariable("id")Longid) {returnCommonResult.success(brandService.getBrand(id));    }}

接下来进行SpringDoc的配置,使用OpenAPI来配置基础的文档信息,通过GroupedOpenApi配置分组的API文档,SpringDoc支持直接使用接口路径进行配置。

/**

* SpringDoc API文档相关配置

* Created by macro on 2022/3/4.

*/@ConfigurationpublicclassSpringDocConfig{@BeanpublicOpenAPImallTinyOpenAPI(){returnnewOpenAPI()                .info(newInfo().title("Mall-Tiny API")                        .description("SpringDoc API 演示")                        .version("v1.0.0")                        .license(newLicense().name("Apache 2.0").url("https://github.com/macrozheng/mall-learning")))                .externalDocs(newExternalDocumentation()                        .description("SpringBoot实战电商项目mall(50K+Star)全套文档")                        .url("http://www.macrozheng.com"));    }@BeanpublicGroupedOpenApipublicApi(){returnGroupedOpenApi.builder()                .group("brand")                .pathsToMatch("/brand/**")                .build();    }@BeanpublicGroupedOpenApiadminApi(){returnGroupedOpenApi.builder()                .group("admin")                .pathsToMatch("/admin/**")                .build();    }}

结合SpringSecurity使用

由于我们的项目集成了SpringSecurity,需要通过JWT认证头进行访问,我们还需配置好SpringDoc的白名单路径,主要是Swagger的资源路径;

/**

* SpringSecurity的配置

* Created by macro on 2018/4/26.

*/@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf.disable().sessionManagement()// 基于token,所以不需要session.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers(HttpMethod.GET,// Swagger的资源路径需要允许访问"/","/swagger-ui.html","/swagger-ui/","/*.html","/favicon.ico","/**/*.html","/**/*.css","/**/*.js","/swagger-resources/**","/v3/api-docs/**").permitAll().antMatchers("/admin/login")// 对登录注册要允许匿名访问.permitAll().antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求.permitAll().anyRequest()// 除上面外的所有请求全部需要鉴权认证.authenticated();            }}

然后在OpenAPI对象中通过addSecurityItem方法和SecurityScheme对象,启用基于JWT的认证功能。

/**

* SpringDoc API文档相关配置

* Created by macro on 2022/3/4.

*/@ConfigurationpublicclassSpringDocConfig{privatestaticfinalString SECURITY_SCHEME_NAME ="BearerAuth";@BeanpublicOpenAPImallTinyOpenAPI(){returnnewOpenAPI()                .info(newInfo().title("Mall-Tiny API")                        .description("SpringDoc API 演示")                        .version("v1.0.0")                        .license(newLicense().name("Apache 2.0").url("https://github.com/macrozheng/mall-learning")))                .externalDocs(newExternalDocumentation()                        .description("SpringBoot实战电商项目mall(50K+Star)全套文档")                        .url("http://www.macrozheng.com"))                .addSecurityItem(newSecurityRequirement().addList(SECURITY_SCHEME_NAME))                .components(newComponents()                                .addSecuritySchemes(SECURITY_SCHEME_NAME,newSecurityScheme()                                                .name(SECURITY_SCHEME_NAME)                                                .type(SecurityScheme.Type.HTTP)                                                .scheme("bearer")                                                .bearerFormat("JWT")));    }}

测试

接下来启动项目就可以访问Swagger界面了,访问地址在线api接口文档生成:http://localhost:8088/swagger-ui.html

我们先通过登录接口进行登录,可以发现这个版本的Swagger返回结果是支持高亮显示的,版本明显比SpringFox来的新;

然后通过认证按钮输入获取到的认证头信息,注意这里不用加bearer前缀;

之后我们就可以愉快地访问需要登录认证的接口了;

看一眼请求参数的文档说明,还是熟悉的Swagger样式!

常用配置

SpringDoc还有一些常用的配置可以了解下,更多配置可以参考官方文档。

springdoc:swagger-ui:# 修改Swagger UI路径path:/swagger-ui.html# 开启Swagger UI界面enabled:trueapi-docs:# 修改api-docs路径path:/v3/api-docs# 开启api-docsenabled:true# 配置需要生成接口文档的扫描包packages-to-scan:com.macro.mall.tiny.controller# 配置需要生成接口文档的接口路径paths-to-match:/brand/**,/admin/**

总结

在SpringFox的Swagger库好久不出新版的情况下,迁移到SpringDoc确实是一个更好的选择。今天体验了一把SpringDoc,确实很好用,和之前熟悉的用法差不多,学习成本极低。而且SpringDoc能支持WebFlux之类的项目,功能也更加强大,使用SpringFox有点卡手的朋友可以迁移到它试试!

参考资料

项目地址:https://github.com/springdoc/springdoc-openapi

官方文档:https://springdoc.org/

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-springdoc

https://mp.weixin.qq.com/s/scityFhZp9BOJorZSdCG0w

关于在线api接口文档生成和api接口文档是干什么的的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。 在线api接口文档生成的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于api接口文档是干什么的、在线api接口文档生成的信息别忘了在本站进行查找喔。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:在 webpack 中使用 ECharts的实例详解
下一篇:java实现字符串的全排列
相关文章

 发表评论

暂时没有评论,来抢沙发吧~