Saturday, May 8, 2021

Swagger Implementation to Web-services API Spring Boot Project - Java


Spring Boot Web API Swagger Addition to Demo Project:

Note : For full access of code. kindly follow the below link. you can see the working code.

GitHub:

https://github.com/Abhinaw/RestAPiDemoWithDb/tree/master/src/main/java/com/abhi/restapidemodb

application.properties:
For example

server.port=8080
logging.level.org.springframework=info
server.servlet.context-path=/demo
spring.datasource.url=jdbc:mysql://localhost:3306/DB
spring.datasource.username=root
spring.datasource.password=
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update

Add Swagger Dependencies to POM.XML

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger2</artifactId>

    <version>2.9.2</version>

</dependency>

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-core</artifactId>

    <version>2.9.2</version>

</dependency>

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger-ui</artifactId>

    <version>2.9.2</version>

</dependency>

Create @Configuration File

The next step will be to create a configuration file. This configuration file aims to configure the base package and selectors of your project and make the configured Docket bean available in your application. Once you create this configuration file, there is a lot that will be done by the framework behind the scenes.

Below is an example of a very simple configuration file:

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration

@EnableSwagger2

public class SwaggerConfig {

   @Bean

   public Docket apiDocket() {

       Docket docket =  new Docket(DocumentationType.SWAGGER_2)

                .select()

                .apis(RequestHandlerSelectors.basePackage("com.appsdeveloperblog.app.ws"))

                .paths(PathSelectors.any())

                .build();

       return docket;

    } 

}

There are a couple of very important details to note in the above code snippet:

APIs() – here you specify classes that need to be included in Swagger. I provided the base package of my project and thus delegate the job of finding the needed classes to the framework. The base package will be scanned by the framework and needed classes will be included based on the annotations they have,

paths() – here we specify the methods(which are annotated with @Path annotation) from the Controller classes which should be included. Since I want all methods to be included in my documentation created with Swagger, I provide the PathSelectors.any()

Swagger and Spring Security

If your RESTful Web Service application is using Spring Security, you will need to do a little configuration in your Java class, which extends the WebSecurityConfigurerAdapter and annotated with @EnableWebSecurity annotation.

Open the Java class in your Spring Boot project which extends the WebSecurityConfigurerAdapter and which is annotated with @EnableWebSecurity annotation.

Generate Swagger API Documentation JSON

If we run our application now we can get the generated by Swagger JSON documentation of our REST API by opening the following URL in the browser window. I assume you are running your Spring Boot application locally, if so the try this URL:

http://localhost:8080/<CONTEXT PATH HERE>/v2/API-docs








Please note: 

In the URL above you will need to make sure that you provide a correct port number and the Context Path if you have provided one in your application. properties file. If you do not have the context path configured in your application. properties file, then do not provide any context path in the URL above.

For example, if your application properties file has the following entry:

server. servlet.context-path=/demo

server.port=8080

eg: 

http://localhost:8888/demo/v2/api-docs

Swagger UI

API Docs:
localhost:8080/demo/v2/api-docs

For Example:

{"swagger":"2.0","info":{"description":"Api Documentation","version":"1.0","title":"Api Documentation","termsOfService":"urn:tos","contact":{},"license":{"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0"}},"host":"localhost:8080","basePath":"/demo","tags":[{"name":"user-controller","description":"User Controller"}],"paths":{"/users":{"get":{"tags":["user-controller"],"summary":"list","operationId":"listUsingGET","produces":["*/*"],"responses":{"200":{"description":"OK","schema":{"type":"array","items":{"$ref":"#/definitions/User"}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":false}},"/users/register":{"post":{"tags":["user-controller"],"summary":"add","operationId":"addUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"user","description":"user","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"200":{"description":"OK"},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":false}},"/users/{id}":{"get":{"tags":["user-controller"],"summary":"get","operationId":"getUsingGET","produces":["*/*"],"parameters":[{"name":"id","in":"path","description":"id","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/User"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":false},"put":{"tags":["user-controller"],"summary":"update","operationId":"updateUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"name":"id","in":"path","description":"id","required":true,"type":"integer","format":"int32"},{"in":"body","name":"user","description":"user","required":true,"schema":{"$ref":"#/definitions/User"}}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":false},"delete":{"tags":["user-controller"],"summary":"delete","operationId":"deleteUsingDELETE","produces":["*/*"],"parameters":[{"name":"id","in":"path","description":"id","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"OK"},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}},"deprecated":false}}},"definitions":{"User":{"type":"object","properties":{"active":{"type":"integer","format":"int32"},"address":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"id":{"type":"integer","format":"int32"},"lastName":{"type":"string"},"password":{"type":"string"},"phone":{"type":"string"},"photo":{"type":"string"}},"title":"User"}}}




 

2 comments:

Anonymous said...


Indeed Easy to implement. Thanks sir.

Abhinaw Tripathi said...

Thank you.