Springboot project using swagger RESTAPI best Documentation

Source: Internet
Author: User
Tags dateformat documentation json
Springboot Project using swagger restapi best documentation

When we develop a variety of rest services, we need to give an introduction to the rest API. Without the introduction of the rest API, no one knows how to use the document except the source code. So how to write the documentation for the rest API. Of course we can write ourselves a tool like Javadoc, and then generate the corresponding HTML or byte development annotations each time we build it, 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 there is, that's swagger.

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

Below we go directly to the topic, how to use swagger in the Springboot project. Total divided into three departments
The first step is to introduce swagger dependency
Part II, configuring the Swagger-ui interface in Spring-boot
The third step, provide the API document page basic information
Fourth step, writing 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 introduces 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 the API Document page basic information

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, where you can configure some of the basic content of swagger2, such as scanned packets and so on
@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 documentation, and note which of the annotations here refer to which
Private Apiinfo Apiinfo () {
return new Apiinfobuilder ()
. Title ("Spring Boot test builds restful APIs using Swagger2")
. Contact (New Contact ("Ericyang", "Https://github.com/yqbjtu/springbootJpa.git", "test@163.com"))
. Version ("1.0")
. Description ("User API description")
. build ();
}

step Fourth, write a document to the rest API

This step is our main work, here we write API documentation for two controllers
The first one is Helloworldcontroller, and it 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 the path to our rest, because we are returning a string, so use "Text/plain;charset=utf-8"
Here is another Usercontroller, 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= "", "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 the 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. Where there is 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 in the browser to open http://127.0.0.1:8080/swagger-ui.html

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.