Springboot integrates Swagger2 to build an elegant restful API

Source: Internet
Author: User

Swagger, Chinese "pull" means. It is a powerful API framework that integrates very simply, provides access to online documentation, and also provides testing of online documentation. In addition, swagger is easy to build a restful API, simple and elegant, just like its name.

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 @enableswagger2 Public classSwagger2 {@Bean PublicDocket Createrestapi () {return NewDocket (documentationtype.swagger_2). Apiinfo (Apiinfo ()).Select(). APIs (Requesthandlerselectors.basepackage ("Com.forezp.controller"). Paths (Pathselectors.any ()). build (); }    Privateapiinfo Apiinfo () {return NewApiinfobuilder (). Title ("springboot Building API documentation with swagger"). Description ("Simple and elegant restfun style, Http://blog.csdn.net/forezp"). Termsofserviceurl ("Http://blog.csdn.net/forezp"). Version ("1.0"). build (); }}


Swagger configuration File Description
    1. parameterbuilder tokenpar =  New parameterbuilder ();     
    2.          list<parameter> pars = new arraylist<parameter> ();     
    3.          Tokenpar.name ( "token"). Description ( "tokens")   
    4.         .modelref (new modelref ( Span class= "string"). ParameterType ( "query"). Required (false ). Build ();     
    5.          pars.add (Tokenpar.build ());
This code is the default parameter, after adding, all interfaces will have a common parameter, do not need to be configured separately on each interface
APIs (Requesthandlerselectors.basepackage ("Com.sst")) This is based on the location of the annotation-based scan, written to the outermost of the directory
  1. return new Apiinfobuilder ()
  2. . Title ("Personal test")
  3. . Description ("API for Personal testing")
  4. . Termsofserviceurl ("Http://blog.csdn.net/penyoudi1")
  5. . Contact ("test")
  6. . Version ("1.0")
  7. . build (); This is the configuration of some page display data, used for headings, group descriptions, etc.
Controller Note Description
      1. @Api (value="Test Interface Controller") This annotation is for the entire class, with a simple description of the list of interfaces in the entire class
      2. @ApiOperation (value="Test Interface", notes="Test Interface", httpmethod="POST")





Third, write the note of the production document swagger the annotations indicate that the interface generates the document, including the interface name, request method, parameters, return information, and so on.    @Api: Modifies the entire class to describe the role of the controller    @ApiOperation: A method that describes a class, or an interface    @ApiParam: A single parameter description    @ Apimodel: Use an object to receive    a parameter @ApiProperty: When you receive a parameter with an object, a field that describes the object    @ApiResponse: HTTP response 1 Description    @ Apiresponses:http Response Overall Description    @ApiIgnore: Use this note to ignore the API    @ApiError: The information returned by the error    @ApiParamImplicitL: a request parameter    @ApiParamsImplicit Multiple request parameters now pass 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.

Iv. references

Swagger.io

Use Swagger2 to build robust RESTful API documentation in Spring boot

Springboot integrates Swagger2 to build an elegant restful API

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.