swagger文档转换为WebApiClient声明式代码

 

1 swagger简介

Swagger是一个规范且完整的框架,提供描述、生产、消费和可视化RESTful Web Service。其核心是使用json来规范描述RESTful接口,另外有提供UI来查看接口说明,并有一套生成不同语言的客户端调用代码生成器。

1.1 对Api提供者

自顶向下

使用Swagger编辑器创建Swagger定义,然后使用Swagger代码生成工具生成服务器实现。

自底向上

为已有的REST API创建Swagger定义。一般的,Api提供者都会选择这种方式,比如在asp.net里集成swagger的支持,在写好接口代码之后,访问对应的swagger的访问Uri地址,就可以得到swagger.json。例如:http://petstore.swagger.io/v2/swagger.json

{   "swagger": "2.0",   "info": {     "tags": null,     "description": "This is a sample server Petstore server.  You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).  For this sample, you can use the api key `special-key` to test the authorization filters.",     "version": "1.0.0",     "title": "Swagger Petstore",     "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"     }   },   "host": "petstore.swagger.io",   "basePath": "/v2",   "tags": [   ...

1.2 对Api使用者

使用swagger UI

一些提供者的站点会提供swagger ui来查看其swagger.json,例如:http://petstore.swagger.io/ 有了这些UI,自己手工编写客户端调用代码也非常简单了。

使用Swagger Codegen

可以Swagger Codegen的将swagger.json逆向生成你需要的客户端调用接口代码,本质上是使用了代码模板结合swagger.json描述来生成代码。在.net里,有一个Nswag项目,可以将swagger.json生成使用HttpClient来请求接口的c#代码。但是这些代码的质量也比较差,比如以下代码的HttpClient的生命周期也就无法很好的维护。

/// <summary>Add a new pet to the store</summary> /// <param name="body">Pet object that needs to be added to the store</param> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task AddPetAsync(Pet body, System.Threading.CancellationToken cancellationToken) {     var urlBuilder_ = new System.Text.StringBuilder();     urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/pet");      var client_ = new System.Net.Http.HttpClient();     try     {         using (var request_ = new System.Net.Http.HttpRequestMessage())         {             var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value));             content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");             request_.Content = content_;             request_.Method = 
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信