Enterprise Distribution Micro Service Cloud Springcloud springboot MyBatis (25) Integrated Swagger2 building restful APIs

Source: Internet
Author: User

First, the introduction of dependency

<dependency>            <groupId>io.springfox</groupId>            <artifactid>springfox-swagger2 </artifactId>            <version>2.6.1</version>        </dependency>        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger-ui</artifactId>            <version>2.6.1</version>        </dependency>

  

Second, write the configuration class

@Configuration @enableswagger2public class Swagger2 {    @Bean public    Docket Createrestapi () {        return new Docket (documentationtype.swagger_2).                apiinfo (Apiinfo ()).                Select ()                . APIs ( Requesthandlerselectors.basepackage ("Com.forezp.controller"))                . Paths (Pathselectors.any ())                . Build ();    }    Private Apiinfo Apiinfo () {        return new Apiinfobuilder ()                . Title ("Springboot build API documentation using swagger")                . Description ("Simple and elegant restfun style, Http://blog.csdn.net/forezp")                . Termsofserviceurl ("Http://blog.csdn.net/forezp ")                . Version (" 1.0 ")                . Build ();    }}

  

The @configuration annotation indicates that it is a configuration class that @EnableSwagger2 turn on Swagger2. Apiinfo () configures some basic information. APIs () specifies that the scanned package generates a document.

Third, write the notes of the production document

Swagger annotations indicate that the interface generates documents, including interface names, request methods, parameters, return information, and so on.

    • @Api: Modify the entire class to describe the role of the controller
    • @ApiOperation: Describes a method of a class, or an interface
    • @ApiParam: Single parameter description
    • @ApiModel: Using objects to receive parameters
    • @ApiProperty: A field that describes an object when it receives parameters with an object
    • @ApiResponse: HTTP response with 1 descriptions
    • @ApiResponses: HTTP Response Overall description
    • @ApiIgnore: Ignore this API with this note
    • @ApiError: The information returned by the error occurred
    • @ApiParamImplicitL: a request parameter
    • @ApiParamsImplicit Multiple Request parameters

Now through a Li Zilai description:

Package Com.forezp.controller;import Com.forezp.entity.book;import Io.swagger.annotations.apiimplicitparam;import Io.swagger.annotations.apiimplicitparams;import Io.swagger.annotations.apioperation;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.*;import Springfox.documentation.annotations.apiignore;import java.util.*;/** * User created a book post/books/* user modified to a book put/books/ : ID/* User deleted to a book Delete/books/:id/* users get all the books Get/books * Users get a book Get/books/:id * Created by Fangzhipeng on 201 7/4/17. * Official Documentation: http://swagger.io/docs/specification/api-host-and-base-path/*/@RestController @requestmapping (value = "/ Books ") public class Bookcontrller {map<long, book> books = Collections.synchronizedmap (new Hashmap<long, book    > ()); @ApiOperation (value= "Get book list", notes= "get book List") @RequestMapping (value={""}, method= requestmethod.get) public list< Book> GetBook () {list<book> book = new Arraylist<> (Books.values ());    return book; } @ApiOperation (value= "Create book", notes= "Create Books") @ApiImplicitParam (name = "book", value = "Books detail entity", required = true, data         Type = "book") @RequestMapping (value= "", method=requestmethod.post) public String Postbook (@RequestBody book) {        Books.put (Book.getid (), book);    Return "Success"; } @ApiOperation (value= "Get book details", notes= "obtain details based on the ID of the URL") @ApiImplicitParam (name = "id", value = "id", required = Tru E, DataType = "Long", Paramtype = "path") @RequestMapping (value= "/{id}", Method=requestmethod.get) public book Getboo    K (@PathVariable Long ID) {return books.get (ID); } @ApiOperation (value= "Update Information", notes= "Specify update book information based on the ID of the URL") @ApiImplicitParams ({@ApiImplicitParam (name = "I D ", value =" Library id ", required = true, DataType =" Long ", Paramtype =" path "), @ApiImplicitParam (name =" book ", VA Lue = "Books entity book", "required = true, DataType =" ")}) @RequestMapping (value="/{id} ", method= Requestmethod.PUT) public String putuser (@PathVariable Long ID, @RequestBody book book) {Book Book1 = Books.get (ID);        Book1.setname (Book.getname ());        Book1.setprice (Book.getprice ());        Books.put (ID, BOOK1);    Return "Success"; } @ApiOperation (value= "delete book", notes= "specify delete book based on URL id") @ApiImplicitParam (name = "id", value = "Book id", Required = Tru E, DataType = "Long", Paramtype = "path") @RequestMapping (value= "/{id}", method=requestmethod.delete) public String D        Eleteuser (@PathVariable Long id) {books.remove (ID);    Return "Success";         } @ApiIgnore//Use this note to ignore this API @RequestMapping (value = "/hi", method = requestmethod.get) public String jsontest () {    Return "Hi you!"; }}

  

With the relevant annotations, you can have swagger2 generate the appropriate documentation. If you don't need an interface to generate a document, just add @apiignore annotations. It is necessary to note that if the request parameter is on the URL, the @ApiImplicitParam is added paramtype = "path".

Start Engineering, visit: http://localhost:8080/swagger-ui.html, see Swagger-ui:

The whole integration process is very simple, but I read the relevant information, swagger do not do security protection, it may be necessary for us to do the relevant work.

Source Source

Enterprise Distribution Micro Service Cloud Springcloud springboot MyBatis (25) Integrated Swagger2 building restful APIs

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.