I. Background of the problem
With the development of technology, now the development model has shifted more to the back-end separation of the model, in the process of front-end development, the way of contact has become an API interface, but the current project for the API management often still by hand to write documents, each time the need to change as long as the interface changes involved, Documents require additional maintenance, if there is a small partner forget maintenance, many times will cause a continuous problem, how can more easily solve the API communication problems? Swagger provides us with a way to use. NET core as an example because I am currently primarily involved in the development of. NET Core projects
Second, what is swagger
Swagger can generate API information from different code, based on annotations, Swagger has a strong community and is well-supported for all languages, and there are many tools that can generate API documentation from swagger generated files
Third,. NET Core Use
. NET Core uses the first to refer to Swashbuckle.aspnetcore with NuGet, adding the following code to the Startup.cs
This method gets called by the runtime. Use this method to add services to the container. public void Configureservices (Iservicecollection services) {services. Addmvc (); Services. Addswaggergen (c + = {C.swaggerdoc ("v1", new Info {Title = "Hello", Version = "V1"}); var basepath = PlatformServices.Default.Application.ApplicationBasePath; var Xmlpath = Path.Combine (BasePath, "webapplication2.xml"); C.includexmlcomments (Xmlpath); }); Services. Addmvccore (). Addapiexplorer (); }//This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure (Iapplicationbuilder app, ihostingenvironment env) {if (env. Isdevelopment ()) {app. Usedeveloperexceptionpage (); } app. Usemvcwithdefaultroute (); App. Useswagger (c= = {}); App. Useswaggerui (c + = {c.showextensions (); C.validatorurl (NULL); C.swaggerendpoint ("/swagger/v1/swagger.json", "Test V1"); }); }
The above section is the code to load the swagger, which is in Startup.cs, and the controller code:
Using system;using system.collections.generic;using system.linq;using system.threading.tasks;using Microsoft.aspnetcore.mvc;namespace webapplication2.controllers{//<summary>//test information//</summary> [Route ("api/[controller]/[action]")] public class Valuescontroller:controller {//<summary> Get all information///</summary>//<returns></returns> [HttpGet] public ienum Erable<string> Get () {return new string[] {"value1", "value2"}; }///<summary>///ID///</summary>//<param name= "id" ></param& Gt <returns></returns>//Get API/VALUES/5 [HttpGet ("{ID}")] public string get (int id) {return "value"; }///<summary>///Post a data message///</summary>//<param name= "value" ></ Param>//Post Api/values [httppost] public void POST ([frombody]string value) {}///<summa Ry>////</summary>//<param name= "id" ></param>//< param name= "value" ></param>//Put API/VALUES/5 [Httpput ("{ID}")] public void PUT (int id, [F Rombody]string value) {}///<summary>//delete data by ID//</summary> <param name= "id" ></param>//DELETE API/VALUES/5 [Httpdelete ("{ID}")] public void Del ETE (int id) {}//<summary>///complex data operation///</summary>//<para M name= "id" ></param>//DELETE API/VALUES/5 [httppost] public namevalue test (Namevalue _info ) {return _info; }} public class Namevalue {///<summary>///</sumMary> public String name {get; set;} <summary>//value information///</summary> public String value {get; set;} }}
Next we need to hook up the XML generation document in the build,
Next we can run up, debugging, browser input http://localhost:50510/swagger/, here port what according to the actual situation, the operation effect as shown:
You can see that swagger the comment on the method and the comment of the entity, and is displayed in Swaggerui, as a whole at a glance, and can be easily debugged through the try it button, but in a specific project there may be a need to bring some client information through the header to the service , such as token information, user information, etc. (we need to bring token to the backend in our project). Can look at the following practices
//This method gets called by the runtime. Use this method to add services to the container. public void Configureservices (Iservicecollection services) {services. Addmvc (); Services. Addswaggergen (c + = {C.swaggerdoc ("v1", new Info {Title = "Hello", Version = "V1"}); var basepath = PlatformServices.Default.Application.ApplicationBasePath; var Xmlpath = Path.Combine (BasePath, "webapplication2.xml"); C.includexmlcomments (Xmlpath); C.operationfilter <addauthtokenheaderparameter> (); }); Services. Addmvccore (). Addapiexplorer (); }
public class Addauthtokenheaderparameter:ioperationfilter {public void Apply (Operation operation, Operationfiltercontext context) { if (operation. Parameters = = null) { operation. Parameters = new list<iparameter> (); } Operation. Parameters.Add (New Nonbodyparameter () { Name = "token", in = "header", Type = "string" , Description = "Token authentication information", Required = True }); } }
We added operationfilter<addauthtokenheaderparameter> () in Configureservices, which allows us to show the header of the token in swagger, and debug (), Addauthtokenheaderparameter's Apply attribute context with the controller and the various information of the action, can be used in conjunction with the actual situation
Iv. integration with other API management tools
Swagger powerful features and the power of the community, many of the current API management tools support YAPI, currently we are using the open source Yapi, you can see Yapi support import swagger generated JSON file, in addition to the tool Outside Doclever (open source) is also a good API management tool, also support swagger file import (Specific tool usage, you can go to see their official website)
V. Summary
Swagger is a good tool, and in the development of the front and back end of the increasingly popular situation, in the subsequent development process, I think it will play a more and more important role, at present our company small project is ready to start using SWAGGER+YAPI API management method, And this article is also this period of time to organize the results of API management, hope can help everyone, here may have a lot of shortcomings, welcome to shoot bricks, but also hope that we can progress together
Demo Address
. NET core uses Swagger for API interface document management