Pages

July 07, 2018

Swagger Questions and Answers

How can you document your RESTful API?
One of the outdated option is to maintain documentation manually. Or, you can generate documentation from code by using: WADL, RESTDocs or Swagger.

Swagger is one of the mostly used and popular REST API documentation standard.

What is Swagger?
Swagger is a specification for documenting REST API, which specifies the format (URL, method, and representation) to describe REST web services.

With Swagger, a service provider is enabled to update the service documentation in real time, so that client/ consumers and documentation systems are moving at the same pace as the server. The methods, parameters, and models description are tightly integrated into the server code, thereby maintaining the synchronization in APIs and its documentation.

What are the advantages of Swagger?


  • With the Swagger framework, the server, client and documentation team can be in synchronization simultaneously.
  • As Swagger is a language-agnostic specification, with its declarative resource specification, clients can easily understand and consume services without any prior knowledge of server implementation or access to the server code.
  • The Swagger UI framework allows both implementers and users to interact with the API. It gives clear insight into how the API responds to parameters and options.
  • Swagger responses are in JSON and XML, with additional formats in progress.
  • Swagger implementations are available for various technologies like Scala, Java, and HTML5.
  • Client generators are currently available for Scala, Java, JavaScript, Ruby, PHP, and Actionscript 3, with more client support underway.
What are the dependencies, we need to add in pom.xml to generate Swagger documentation?
We not only need to add a couple of dependencies related to Swagger in pom.xml, but also need to configure a Docket to generate Swagger Documentation.
Here are the two dependencies, which we need to add in pom.xml
 < dependency >
     < groupId > io.springfox < /groupId >
     < artifactId > springfox-swagger2 < /artifactId >
     < version > 2.4.0 < /version >
 < /dependency >

 < dependency >
     < groupId > io.springfox < /groupId >
     < artifactId > springfox-swagger-ui < /artifactId >
     < version > 2.4.0 < /version >
 < /dependency >


Then you need to create a SwaggerConfig class.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
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.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public static final Contact DEFAULT_CONTACT = new Contact("K Himaanshu Shuklaa",
            "https://scrutinybykhimaanshu.blogspot.com/", "acmehimanshu@gmail.com");

    public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Scrutiny API Title", "Scrutiny API Description", "1.0",
            "urn:tos", DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0");

    private static final Set < String >  DEFAULT_PRODUCES_AND_CONSUMES = new HashSet < String > (
            Arrays.asList("application/json", "application/xml"));

    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(DEFAULT_API_INFO)
                .produces(DEFAULT_PRODUCES_AND_CONSUMES)
                .consumes(DEFAULT_PRODUCES_AND_CONSUMES)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hpe.ngit.service.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

  • @Configuration: Indicates that a class is a configuration class that may contain bean definitions.
  • @EnableSwagger2: Annotation to Enable Swagger Documentation on the API
  • public static final Contact DEFAULT_CONTACT: Has the contact information of the API. This will be exposed as part of the Swagger Documentation.
  • public static final ApiInfo DEFAULT_API_INFO: Meta information about the API e.g: Description, Licensing etc. This will be exposed as part of the Swagger Documentation.
  • private static final Set < String >  DEFAULT_PRODUCES_AND_CONSUMES: What content types does your API support?  
  • productApi(): Based on this the Docket to decide what kind of APIs you would want to document.
Launching Swagger UI: This URL will show you list of all the services available http://localhost:8080/swagger-ui.html.

How can we customizing Swagger Documentation with Annotations?
  • @Api: Narrates the description about what in general is the responsibility of the controller. @Api annotation parameters:
    •     value – Short description of the Api
    •     description – general description of this class
    •     basePath – the base path that is prepended to all @Path elements
    •     position – optional explicit ordering of this Api in the resource listing
    •     produces – content type produced by this Api
    •     consumes – media type consumed by this Api
    •     protocols – protocols that this Api requires (i.e. https)
    •     authorizations – authorizations required by this Api
  • @ApiOperation: It provides detailed description of what certain method does, its response, HTTP method and other useful information. Annotation parameters:
    •     value – brief description of the operation
    •     notes – long description of the operation
    •     response – default response class from the operation
    •     responseContainer – if the response class is within a container, specify it here
    •     tags – currently not implemented in readers, reserved for future use
    •     httpMethod – the HTTP method, i.e GET, PUT, POST, DELETE, PATCH, OPTIONS
    •     position – allow explicit ordering of operations inside the Api declaration
    •     nickname – the nickname for the operation, to override what is detected by the annotation scanner
    •     produces – content type produced by this Api
    •     consumes – media type consumed by this Api
    •     protocols – protocols that this Api requires (i.e. https)
    •     authorizations – authorizations required by this Api
  • @ApiParam: Narrates the parameter the method is expecting and also tells whether it is mandatory or not.Annotation parameters:
    •     name – name of the parameter
    •     value – description of the parameter
    •     defaultValue – default value – if e.g. no JAX-RS @DefaultValue is given
    •     allowableValues – description of values this endpoint accepts
    •     required – specifies if the parameter is required or not
    •     access – specify an optional access value for filtering in a Filter implementation. This allows you to hide certain parameters if a user doesn’t have access to them
    •     allowMultiple – specifies whether or not the parameter can have multiple values provided
  • @ApiResponse: It represents a type of response from a server. This can be used to describe both success codes as well as errors. If your Api has different response classes, you can describe them here by associating a response class with a response code. Note, Swagger does not allow multiple response types for a single response code. Annotation parameters:
    •     code – response code to describe
    •     message – human-readable message to accompany the response
    •     response – optional response class to describe the payload of the message
e.g
@RestController
@Api(value = "empoperations", description = "Operations specific to Employee services")
public class EmployeeServiceController
{
@ApiOperation(value = "This web-service will return the Employee Details",
    notes="It also returns the link to retrieve, bank accounts of employees with red - get-Emp-Bank-Accs"
    response = EmployeeDetailsRequest.class)
@RequestMapping(method = RequestMethod.POST, value = "/getEmployeeDetails")
public EmployeeDetailsResponse getEmployeeDetails(EmployeeDetailsRequest employeeReq)
{
    //...perform operations
    return employeeRes;
}
}

-K Himaanshu Shuklaa..

No comments:

Post a Comment