11th: Springboot Integrated Swagger2 to build an elegant restful API

Source: Internet
Author: User

 Statement: This part of the content is transferred from Fang Zhiming bo Friends Blog, because I like his blog, so has been learning, reproduced only records and share, if there are people like, you can go to his blog Home View: http://blog.csdn.net/forezp/article/ details/71023536

  

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 using swagger to build API documentation"). 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.

Iii. annotations of sketching into documents

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

(1)@Api: Modify the entire class to describe the role of the controller

(2)@ApiOperation: Describe a method of a class, or an interface

(3)@ApiParam: single parameter description

(4)@ApiModel: use object to receive parameters

(5)@ApiProperty: A field that describes an object when it receives parameters with an object

(6)@ApiResponse:HTTP response 1 of which are described

(7)@ApiResponses:HTTP Response Overall description

(8)@ApiIgnore: ignore this API with this note

(9)@ApiError: The information returned by the error occurred

(Ten)@ApiParamImplicitL: One request parameter

(one)@ApiParamsImplicit: Multiple request parameters

Now through a Li Zilai description:

 PackageCom.forezp.controller;ImportCom.forezp.entity.Book;ImportIo.swagger.annotations.ApiImplicitParam;ImportIo.swagger.annotations.ApiImplicitParams;Importio.swagger.annotations.ApiOperation;ImportOrg.springframework.ui.ModelMap;Importorg.springframework.web.bind.annotation.*;ImportSpringfox.documentation.annotations.ApiIgnore;ImportJava.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 * User gets a book Get/books/:id * Created by Fangzhipeng on 2017/4/17. * Official documents:http://swagger.io/docs/specification/api-host-and-base-path/ */@RestController @requestmapping (value= "/books") Public classBookcontrller {Map<long, book> books = Collections.synchronizedmap (NewHashmap<long, book>()); @ApiOperation (Value= "Get book list", notes= "Get book list") @RequestMapping (value={""}, method=requestmethod.get) PublicList<book>GetBook () {List<Book> book =NewArraylist<>(Books.values ()); returnBook ; } @ApiOperation (Value= "Create book", notes= "create book") @ApiImplicitParam (name= "book", value = "Books detail entity", required =true, DataType = "book") @RequestMapping (value= "", method=requestmethod.post) PublicString Postbook (@RequestBody book book) {Books.put (Book.getid (), book); return"Success"; }
@ApiOperation (Value= "Receive book details", notes= "Get details based on URL id") @ApiImplicitParam (name= "id", value = "id", required =true, DataType = "Long", Paramtype = "path") @RequestMapping (value= "/{id}", method=requestmethod.get) PublicBook GetBook (@PathVariable Long id) {returnbooks.get (ID); } @ApiOperation (Value= "Update Information", notes= "Specify update book information based on URL id") @ApiImplicitParams ({@ApiImplicitParam (name= "id", value = "Book id", required =true, DataType = "Long", Paramtype = "path"), @ApiImplicitParam (name= "book", value = "books entity", required =true, DataType = "book") })
@RequestMapping (Value= "/{id}", method=requestmethod.put) PublicString 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 =true, DataType = "Long", Paramtype = "path") @RequestMapping (value= "/{id}", method=requestmethod.delete) PublicString deleteuser (@PathVariable Long id) {books.remove (ID); return"Success"; } @ApiIgnore//ignore this API with this note@RequestMapping (value = "/hi", method =requestmethod.get) PublicString 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:

Iv. References

Swagger.io

Use Swagger2 to build robust RESTful API documentation in Spring boot

11th: Springboot Integrated 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.