ÔõÑùʹÓÃSwaggerÌìÉúAPIÎĵµ£¿
Ëæ×ÅwebÓ¦ÓóÌÐòµÄ¿ìËÙÉú³¤£¬apiÎĵµÔ½À´Ô½Ö÷Òª¡£apiÎĵµÖ¼ÔÚ×ÊÖú¿ª·¢Ö°Ô±Ã÷È·apiµÄʹÓÃÒªÁìºÍ²ÎÊý£¬ïÔÌʱ¼äºÍ×ÊÔ´ÆÌÕÅ¡£È»¶ø£¬ÊÖ¶¯±àдapiÎĵµ¿ÉÄÜ»áºÜƶÀ§ÇÒ·Ñʱ£¬Õâʱ¼äswaggerÔò³ÉΪÁË¿ª·¢Ö°Ô±µÄÀûÆ÷¡£swaggerÊÇÒ»ÖÖÊ¢ÐеÄapiÎĵµ¹¤¾ß£¬¿ÉÒÔ×Ô¶¯»¯ÌìÉú¿É¶ÁÐÔÇ¿£¬½»»¥ÐÔµÄapiÎĵµ¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùʹÓÃswaggerÀ´×Ô¶¯ÌìÉúapiÎĵµ¡£
ʲôÊÇSwagger£¿
SwaggerÊÇÒ»×鿪Դ¹¤¾ß£¬¿É×ÊÖú¿ª·¢Ö°Ô±¹¹½¨£¬Éè¼Æ£¬ÐÎòºÍʹÓÃRESTful WebЧÀÍ¡£ SwaggerÔÊÐíÄúʹÓÃÓÃÓÚÐÎòAPI²Ù×÷µÄYAML»òJSONÃûÌñàдAPIÎĵµ£¬²¢ÌìÉúÒ×ÓÚÔĶÁºÍ½»»¥µÄ½Ó¿ÚÎĵµ¡£
SwaggerÖ§³Ö¶àÖÖ±à³ÌÓïÑԺͿò¼Ü£¬ÀýÈçJava£¬C£££¬PythonºÍRuby¡£Ëü»¹¿ÉÒÔÓëÐí¶àÏÖÓеÄAPI¿ò¼Ü¾ÙÐм¯³É£¬°üÀ¨Spring£¬ExpressºÍDjangoµÈ¡£
ʹÓÃSwaggerÌìÉúAPIÎĵµÐèÒªÏÈ×°ÖÃSwagger UI¡£Swagger UIÊÇÒ»¸ö½»»¥Ê½APIÎĵµÍøÕ¾£¬×ÔÁ¦ÓÚAPI£¬²¢×·ËæSwagger¹æ·¶¡£ËüÌṩÁËAPIÎĵµ¿ÉÊÓ»¯µÄƯÁÁ½çÃ棬²¢Ö§³Ö×Ô¶¯»¯ÊµÑéAPIŲÓá£
°ì·¨1£ºÉèÖÃSwagger
ҪʹÓÃSwagger£¬ÐèÒªÏÈÏÂÔØSwagger°ü£¬¿ÉÒÔ´ÓSwaggerÍøÕ¾»ñÈ¡»òʹÓÃÒÀÀµÖÎÀíÆ÷¾ÙÐÐÏÂÔØ¡£
ÔÚJava Spring BootÏîÄ¿ÖÐÉèÖÃSwagger API£¬ÐèÒªÔÚmavenÒÀÀµÖÐÌí¼ÓÒÔÏÂSwaggerÒÀÀµ£º
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox-swagger2.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox-swagger-ui.version}</version> </dependency>
µÇ¼ºó¸´ÖÆ
ÆäÖÐ${springfox-swagger2.version}ºÍ${springfox-swagger-ui.version}´ú±íSwagger°æ±¾ºÅ¡£ ÉèÖÃÎļþapplication.propertiesÖпªÆôswagger£º
#¿ªÆôswagger swagger.enabled = true
µÇ¼ºó¸´ÖÆ
°ì·¨2£º±àдSwagger×¢½â
SwaggerʹÓÃ×¢½âÀ´ÐÎòAPIÖеIJÙ×÷ºÍ²ÎÊý¡£ÔÚAPI¿ØÖÆÆ÷ÀàºÍÆäÒªÁìµÄ¶¥²¿Ìí¼ÓSwagger×¢½â£¬ÒÔ±ãSwaggerÄܹ»×¼È·µØÆÊÎöºÍÌìÉúÎĵµ²¢ÔÚSwagger UIÉÏÏÔʾ¡£
ÒÔÏÂÊÇһЩʾÀý×¢½â£º
@Api£ºÓÃÓÚÌí¼ÓAPIµÄÐÎòÐÅÏ¢
@Api(value="User",tags={"User ²Ù×÷½Ó¿Ú"}) @Controller @RequestMapping("/users") public class UserController { // ... }
µÇ¼ºó¸´ÖÆ
@ApiOperation£ºÓÃÓÚÌí¼ÓAPI²Ù×÷µÄÐÎòÐÅÏ¢
@ApiOperation(value = "»ñÈ¡Óû§Áбí", notes = "") @GetMapping(value = "/list") public Result getUserList() { List<User> userList = userService.listUser(); return Result.success(userList); }
µÇ¼ºó¸´ÖÆ
@ApiParam£ºÓÃÓÚÌí¼ÓAPI²Ù×÷²ÎÊýµÄÐÎòÐÅÏ¢
@ApiOperation(value = "»ñÈ¡Óû§ÐÅÏ¢", notes = "ƾ֤urlµÄidÀ´»ñÈ¡Óû§ÏêϸÐÅÏ¢") @GetMapping(value = "/{id}") public Result getUserById(@ApiParam(value = "Óû§ID", required = true) @PathVariable Long id) { User user = userService.getUserById(id); return Result.success(user); }
µÇ¼ºó¸´ÖÆ
°ì·¨3£ºÆô¶¯Ó¦ÓóÌÐò²¢»á¼ûSwagger UI
ÔÚÍê³ÉSwagger×¢½â±àдºó£¬Ê¹ÓÃä¯ÀÀÆ÷·¿ªSwagger UIµÄµØµã¡£Ëü»áƾ֤ÄúµÄAPI×Ô¶¯¹¹½¨¿ÉÊÓ»¯APIÎĵµ¡£
Swagger UIµÄĬÈϵصãΪ£ºhttp://localhost:8080/swagger-ui.html
ÔÚSwagger UI½çÃæÉÏ£¬¿ÉÒÔ¿´µ½APIµÄÒ»·Ý¸ÅÊö¡¢ÖÖÖÖAPI½Ó¿ÚµÄÐÎò¡¢ÇëÇóºÍÏìÓ¦²ÎÊýÒÔ¼°Ò»Ð©²âÊÔ´úÂëµÈ¡£Õâ¿ÉÒÔ×ÊÖú¿ª·¢Ö°Ô±¸üºÃµÄÃ÷È·ºÍʹÓÃAPI¡£
×ܽá
SwaggerÊÇÒ»¸öÇ¿Ê¢µÄAPIÎĵµ¹¤¾ß£¬¿ÉÒÔ×Ô¶¯ÌìÉúÒ×ÓÚÔĶÁºÍ½»»¥µÄAPIÎĵµ¡£Ê¹ÓÃSwaggerÄܹ»Ìá¸ßAPI¿ª·¢µÄЧÂʺÍÖÊÁ¿, ²¢ïÔÌÊÖ¶¯±àдAPIÎĵµËùÐèµÄʱ¼äºÍ×ÊÔ´¡£Í¨¹ý×ñÕÕÉÏÊö°ì·¨£¬Äú¿ÉÒÔÇáËɵØ×îÏÈʹÓÃSwaggerÀ´×Ô¶¯ÌìÉúAPIÎĵµ¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃSwaggerÌìÉúAPIÎĵµ£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡