How to create swagger documentation for rest API
What you will learn here about Swagger
- How to create swagger documentation for rest API
Overview
Swagger is commonly used in microservices for creating a documentation of APIs as well as testing the APIs. When we have swagger in our spring boot application we do not need a postman for testing because we can also test our APIs from the swagger itself. So here we will see how to make or create swagger in spring boot application from the beginning.
Please click on the below link to download sample swagger project.
Download Swagger UI sample project (119 downloads)How to create swagger documentation for rest API
Please click on the following steps to know how to create swagger documentation for rest api or to know how to do swagger documentation in spring boot
1)First create a simple maven project which has only spring boot starter web dependency
2)Now we have to add springfox swagger2 dependency in pom.xml which is shown below.
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency>
3)Now we have to add springfox swagger ui dependency in pom.xml which is shown below.
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
4)Now we need to enable swagger2. Please go to your spring application class and @EnableSwagger2 annotation which is shown below
5)Optional. If we want to show only our APIs on swagger and remove default APIs add following method in your spring application class which is shown below
@Bean public Docket swaggerConfiguration(){ return new Docket(DocumentationType.SWAGGER_2) .select() .paths(PathSelectors.ant("/api/*")) .apis(RequestHandlerSelectors.basePackage(("com.example"))) .build() .apiInfo(apiDetails()); }
6)Optional. If you have followed step 5 then please follow this step also. If you want to modify default text information on swagger then please follow this step.
public ApiInfo apiDetails(){ return new ApiInfo( "Sample swagger", "", "v1", "", new Contact("","",""), "", "", Collections.EMPTY_LIST ); }
7)Now create a java class in another package which we will use as response which is shown below
8)Now create a simple rest controller which is shown below
9)Now run your spring boot application
10)Now please go browser and enter following URL. You will see following kind of output in browser which is shown below
http://localhost:8080/swagger-ui.html
11)To test this please follow the following steps.
- Click on API end point
- Click on Try it out
- Enter input value
- Click on Execute
- Check the response