Springboot Project uses swagger RESTAPI best documentation

Source: Internet
Author: User
Tags dateformat documentation json
Springboot Project uses swagger restapi Best documentation

When we develop various rest services, we need to give an introduction to the rest API. Without the use of documentation for the rest API introduction, few people know how to use it except to look at the source code. So how do you write the documentation for the rest API? Of course, we can write a tool like Javadoc ourselves, and then generate the corresponding HTML each time we build it, or byte development annotations, and then generate the rest doc document according to some rules, then there is an open source, unified and handy rest documentation tool. Of course, that's swagger.

Let's take a look at how Swagger's official website describes the project.
Swagger–the World's Most popular API tooling, one of the most popular API tools on the planet.

Here we go directly to the topic of how to use swagger in the Springboot project. Total divided into three parts
The first step is to introduce swagger dependency
Part II, configuring the Swagger-ui interface in Spring-boot
The third step is to provide basic information about the API document page
Step fourth, write documentation for the REST API
Project in Https://github.com/yqbjtu/springbootJpa/tree/2.0swagger. Welcome to download and attention, thank you. The first step is to introduce swagger dependency

Add the following dependencies in the Pom file

        <!--use swagger for rest API-->
        <dependency>
        <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        <version>2.8.0</version>
        </ dependency>
        <dependency>
           <groupId>io.springfox</groupId>
           <artifactId> springfox-swagger-ui</artifactid>
           <version>2.8.0</version>
        </dependency>
The second step is to configure the Swagger-ui interface in Spring-boot

Add a class Webmvcconfig to our project.

Package com.yq.demo.config;

Import org.springframework.context.annotation.Configuration;
Import Org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
Import Org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration public
class Webmvcconfig extends Webmvcconfigureradapter {

    @Override public
    Void Addresourcehandlers (Resourcehandlerregistry registry) {
        Registry.addresourcehandler ("/js/**"). Addresourcelocations ("classpath:/js/");
        Registry.addresourcehandler ("swagger-ui.html")
                . Addresourcelocations ("classpath:/meta-inf/resources/");
        Registry.addresourcehandler ("/webjars/**")
                . Addresourcelocations ("classpath:/meta-inf/resources/webjars/") );
    }

}
The Third Step provides basic information about the API document page

Also add a new class
Package Com.yq.demo;

Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;

Import Springfox.documentation.service.Contact;
Import Springfox.documentation.builders.ApiInfoBuilder;
Import springfox.documentation.builders.PathSelectors;
Import springfox.documentation.builders.RequestHandlerSelectors;
Import Springfox.documentation.service.ApiInfo;
Import Springfox.documentation.spi.DocumentationType;
Import Springfox.documentation.spring.web.plugins.Docket;
Import Springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
Swagger2 configuration file, you can configure some basic content of swagger2, such as scanned packets, etc.
@Bean
Public Docket Createrestapi () {
return new Docket (documentationtype.swagger_2)
. Apiinfo (Apiinfo ())
. Select ()
is the current package path
. APIs (Requesthandlerselectors.basepackage ("Com.yq.demo.controller"))
. Paths (Pathselectors.any ())
. build ();
}
Build the detailed information function for the API document, and note which of the annotations is referenced here
Private Apiinfo Apiinfo () {
return new Apiinfobuilder ()
. Title ("The Spring Boot test builds the restful API using Swagger2")
. Contacts (New Contact ("Ericyang", "Https://github.com/yqbjtu/springbootJpa.git", "test@163.com"))
. Version ("1.0")
. Description ("User API description")
. build ();
}

step Fourth, write documentation for the rest API

This step is our main job, where we write API documentation for two controller
The first one is Helloworldcontroller, which has a get REST API that shows Hello World

    @ApiOperation (value = "Hello demo", notes = "Just for demo")
    @GetMapping (value = "/hello", produces = "Text/plain;char Set=utf-8 ") Public
    String Hello () {return
        ' Hello World ';
    }

You can see @getmapping (value = "/hello", produces = "text/plain;charset=utf-8")
where the value = "/hello" is our rest path, because we are returning a string, so use "Text/plain;charset=utf-8"
Here is another usercontroller, the API is more, we choose 2 of them, project class can see the source code

    @ApiOperation (value = "Add New user", notes = "Add new user to System") @ApiImplicitParams ({@ApiImplicitP Aram (name = "UserName", value = "UserName", required = true, DataType = "String", Paramtype = "Query"), @ApiImplic Itparam (name = "Password", value = "password", required = true, DataType = "String", Paramtype = "Query"), @ApiImplicitP Aram (name = "FullName", value = "FullName", required = true, DataType = "String", Paramtype = "Query"), @ApiImplic Itparam (name = "Email", value = "email", required = true, DataType = "String", Paramtype = "Query"), @ApiImplicitP Aram (name = "Usertype", allowablevalues= "1,2,3", required = false, DataType = "int", Paramtype = "Query"), @ApiImp
        Licitparam (name = "DateFormat", value = "DateFormat", required = false, DataType = "String", Paramtype = "Query"), 
        @ApiImplicitParam (name = "Timeforamt", value = "Timeforamt", required = false, DataType = "String", Paramtype = "Query"), @ApiImplicitParAM (name = "TimeZone", value = "timezone", required = false, DataType = "String", Paramtype = "Query"), @ApiImplici Tparam (name = "Language", value = "language", required = false, DataType = "String", Paramtype = "Query")}) @Pos
            Tmapping (value = "/add", produces = "application/json;charset=utf-8") public @ResponseBody User Addnewuser (
            @RequestParam string userName, @RequestParam string password, @RequestParam string fullName, @RequestParam String Email, @RequestParam Integer usertype, @RequestParam (value = "Datef Ormat ", defaultvalue =" Yyyy-mm-dd ") String DateFormat, @RequestParam (value =" Timeforamt ", defaultvalue =" HH
            : Mm:ss ") string Timeforamt, @RequestParam (value =" TimeZone ", defaultvalue =" gmt+8 ") string timezone,
        @RequestParam (value = "Language", DefaultValue = "ZH_CN") String language) {User user = new user (); User.setusername (UsernaME);
        User.setfullname (FullName);
        User.setemail (email);
        User.setlanguage (language);
        User.setpassword (password);
        User.setactive (1);
        User.setusertype (usertype);
        User.setcan_delete (1);
        User.settimezone (timezone);
        User.settimeformat (Timeforamt);
        User.setdateformat (DateFormat);

        Userrepository.save (user);
    return user; }

The following is an example of a query based on FullName. which has only one path parameter fullname

    @ApiOperation (value = "Findbyfullname", notes = "Find by FullName")
    @ApiImplicitParam (name = "FullName", value = ' full Name ", required = true, DataType =" String ", Paramtype =" path ")
    @GetMapping (value ="/findbyfullname/{fullname} ", pro duces = "Application/json;charset=utf-8")
    @ResponseBody public
    User getuserbyfullname (@PathVariable String FullName) {
        User user = Userrepository.getbyfullname (fullname);
        return user;
    }

Finally run our project, open the http://127.0.0.1:8080/swagger-ui.html in the browser

Example Figure 1

Select Run Findbyfullname

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.