The external interface documents have always been relatively primitive, and basically handwritten documents are passed around. Recently, I discovered a new toy, which can save a lot of trouble on the interface.
swagger is a convenient API documentation framework. It can display the interface type to the other developer in the most comprehensive way, avoiding the one-sided and error behavior of handwritten documents.
There are currently two types of swagger and swagger2. 1 is more troublesome, so you don't consider using it. This article mainly records two ways I use swagger2 as an external interface. Please check it later.
1. Use traditional springmvc to integrate swagger2
1. Maven dependency
<!--springfox dependencies--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency>
2. Add a static mapping configuration in spring-mvc.xml (actually, I can remove this in my project, I don’t know what the situation is):
<!-- swagger static file path--> <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/> <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
Note: I won't post the basic springmvc configuration. It should be noted that if you see the swagger-ui.html interface coming out, but it's blank, please check the configuration of the interceptor in your web.xml. You must intercept springmvc first, and then the interface will display.
3. Then there is the configuration class of swagger2:
@Configuration@EnableSwagger2public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("net.laoyeyey.yyblog")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("yyblog project RESTful APIs") .description("yyblog project api interface documentation") .version("1.0") .build(); }}Note: If paths can be adjusted to PathSelectors.none() in production, it does not display all interface information;
4. Interface information configuration
That is, configure relevant interface information in SpringMvc Controller
@Controller@RequestMapping(value = "aitou")@Api(description = "Test Service-Account Information Query")public class DailyOperationDataController { Logger logger = Logger.getLogger(DailyOperationDataController.class); @Autowired private DailyOperationDataService DailyOperationDataService; /* * @ApiOperation(value = "Interface Description", httpMethod ="Interface Request Method", response ="Interface Return Parameter Type", notes ="Interface Release Notes" * @ApiParam(required = "Is the parameter required", name ="parameter name", value ="parameter specific description" */ @ApiOperation(value = "Account information query interface") @RequestMapping(method ={RequestMethod.POST,RequestMethod.GET}, value="/query/dailydata/{dataDate}") @ResponseBody public DailyOperationDataDto getDailyReportByDataDate(@PathVariable("dataDate") String dataDate) { try { return DailyOperationDataService.getDailyReportByDataDate(dataDate); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; }}Note: Usually, swagger2 will display all interfaces under the scan package. Here I am the external interface to be a separate package to avoid displaying too many interfaces. Of course, the interface method can also prevent it from displaying. You can see the relevant annotations below.
Some commonly used notes
@Api: Used on a class to illustrate the function of the class
@ApiOperation: Used in methods to illustrate the function of methods
@ApiImplicitParams: Used to include a set of parameter descriptions on the method
@ApiImplicitParam: Used in the @ApiImplicitParams annotation, specify various aspects of a request parameter paramType: Where to place the parameter ・ header --> Get request parameter: @RequestHeader
・ query --> Request parameter acquisition: @RequestParam
・ path (for restful interface) --> Getting request parameters: @PathVariable
・ Body (not commonly used)
・ form (not commonly used)
name: parameter name dataType: parameter type required: whether the parameter must be passed value: parameter meaning defaultValue: parameter default value
@ApiResponses: used to represent a set of responses
@ApiResponse: Used in @ApiResponses, it is generally used to express an error response code: a number, such as 400
message: message, such as "the request parameter is not filled out"
response: class that throws exception
@ApiParam: Single parameter description
@ApiModel: Describe the information of a Model and uses objects to receive parameters (this is usually used when creating posts, using @RequestBody scenarios, and when requesting parameters cannot be described using @ApiImplicitParam annotation)
@ApiModelProperty: Describe the properties of a model
@ApiProperty: When using an object to receive parameters, describe a field of the object
@ApiIgnore: Use this annotation to ignore this API
Basically, it's all the above. Isn't it very easy? Let's see the effect picture below
2. Use springboot to integrate swagger2
The above mentioned using traditional springmvc to integrate swagger2. Let’s talk about the recent popular springboot method. In fact, the principles are the same.
1. Maven dependency
<!--springfox dependency--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
This is the internal use of my personal project I wrote recently using springboot, and the version used 2.7.0 is used in the version.
2. Add static resource configuration
@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter {/** * Configure the static resource path and the path to upload the file* * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("/upload/**").addResourceLocations(environment.getProperty("spring.resources.static-locations")); /*swagger-ui*/ registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); }}In fact, it is just the last two sentences. If you don’t configure this, you will see an error of 500 or 404 when you visit swagger-ui.html. If you can’t remember it, it should be 404.
3. Swagger2 configuration class
Like the above, there is basically no difference
@Configuration@EnableSwagger2@EnableWebMvcpublic class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("net.laoyeye.yyblog.web.frontend")) .paths(PathSelectors.none()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("yyblog project RESTful APIs") .description("yyblog project api interface document") .version("1.0") .build(); }}Note that I have a problem with path above. The copy directly does not display the API (#^.^#)
4. Interface configuration
/** * Front Desk Article Controller * @author Grandpa in the convenience store* @date May 5, 2018* @website www.laoyeye.net */@Api(description="Article Query")@Controller@RequestMapping("/article")public class ArticleController { @Autowired private ArticleService articleService; @Autowired private SettingService settingService; @Autowired private CateService cateService; @Autowired private TagReferService tagReferService; @Autowired private UserService userService; @Autowired private ArticleMapper articleMapper; @Autowired private CommentService commentService; @ApiOperation(value="Article query interface") @ApiImplicitParam(name = "id", value = "Article ID", required = true, dataType = "Long") @GetMapping("/{id}") public String index(Model model, @PathVariable("id") Long id) { try { articleService.updateViewsById(id); } catch (Exception ignore) { } List<Setting> settings = settingService.listAll(); Map<String,Object> map = new HashMap<String,Object>(); for (Setting setting: settings) { map.put(setting.getCode(), setting.getValue()); } Article article = articleService.getArticleById(id); model.addAttribute("settings", map); model.addAttribute("cateList", categoryService.listAllCate()); model.addAttribute("article", article); model.addAttribute("tags", tagReferService.listNameByArticleId(article.getId())); model.addAttribute("author", userService.getNicknameById(article.getAuthorId())); //Change model.addAttribute("articles", articleMapper.listArticleByTitle(null)); model.addAttribute("similars", articleMapper.listArticleByTitle(null)); CommentQuery query = new CommentQuery(); query.setLimit(10); query.setPage(1); query.setArticleId(id); model.addAttribute("comments", commentService.listCommentByArticleId(query)); return "frontend/article"; } @ApiOperation(value="ArticleComment Query Interface") @PostMapping("/comments") @ResponseBody public DataGridResult comments(CommentQuery query) { //Set the default 10 query.setLimit(10); return commentService.listCommentByArticleId(query); } @ApiOperation(value="ArticleLid") @ApiImplicitParam(name = "articleId", value = "ArticleID", required = true, dataType = "Long") @PostMapping("/approve") @ResponseBody public YYBlogResult approve(@RequestParam Long articleId) { return articleService.updateApproveCntById(articleId); }}Finally, there is a rendering, the same as above.
When PathSelectors.none() is
When PathSelectors.any() is
It is clear at a glance whether the interface content is the rendering, and it is very concise and clear.
Finally, it seems that I forgot to say the path to the swagger document
If your project is in the root directory: http://localhost:8080/swagger-ui.html
If it is not the root directory, it is: http://localhost:8080/Your project name/swagger-ui.html
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.