Saturday, February 28, 2015

10 Steps To Creating Bootiful RESTful API Documentation Using Swagger

It's been a while since I posted, so here goes the ten steps on how to set up a SpringBoot RESTful service with Swagger-UI.

1. Go to start.spring.io and download a 'web' starter project or use SpringSTS ide.

2. Add the swagger-springmvc dependency.

 <dependency>  
   <groupId>com.mangofactory</groupId>  
   <artifactId>swagger-springmvc</artifactId>  
   <version>0.8.8</version>  
 </dependency>  


3. Download the swagger-ui from https://github.com/swagger-api/swagger-ui and copy the files in the
/dist
folder to your
{application}\src\main\resources\public\docs


4. Modify the swagger-ui index.html script (thanks to http://raibledesigns.com/rd/entry/documenting_your_spring_api_with)

       $(function () {  
         var url = window.location.protocol + "//" + window.location.host;  
         if (window.location.pathname.indexOf('/api') > 0) {  
           url += window.location.pathname.substring(0, window.location.pathname.indexOf('/api'))  
         }  
         url += "/api-docs";  
         log('API URL: ' + url  


5. Add a RestController
 package demo.swagger;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.springframework.http.HttpStatus;  
 import org.springframework.http.MediaType;  
 import org.springframework.http.ResponseEntity;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.bind.annotation.RequestMethod;  
 import org.springframework.web.bind.annotation.RestController;  
 @RestController  
 @RequestMapping("/api")  
 public class MainController{  
   @RequestMapping(value ="/users",   
       consumes=MediaType.APPLICATION_JSON_VALUE,  
       method=RequestMethod.GET)  
   public ResponseEntity<List<User>> getUser(){  
     User user = new User();  
     user.setName("all the swag I got");  
     user.setId(12312);  
     List<User> users = new ArrayList<>();  
     users.add(user);  
     return new ResponseEntity<>(users, HttpStatus.OK);  
   }  
 }  


6. Add a domain class

 public class User {  
   private String name;  
   private Integer id;  
   @Override  
   public String toString() {  
     return "User{" + "name=" + name + ", id=" + id + '}';  
   }  
   /**  
    * @return the name  
    */  
   public String getName() {  
     return name;  
   }  
   /**  
    * @param name the name to set  
    */  
   public void setName(String name) {  
     this.name = name;  
   }  
   /**  
    * @return the id  
    */  
   public Integer getId() {  
     return id;  
   }  
   /**  
    * @param id the id to set  
    */  
   public void setId(Integer id) {  
     this.id = id;  
   }  
 }  


7. Add the SwaggerConfiguration.
 package demo.swagger;  
 import com.mangofactory.swagger.configuration.SpringSwaggerConfig;  
 import com.mangofactory.swagger.plugin.EnableSwagger;  
 import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;  
 import com.wordnik.swagger.model.ApiInfo;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
 import org.springframework.boot.bind.RelaxedPropertyResolver;  
 import org.springframework.context.EnvironmentAware;  
 import org.springframework.context.annotation.Bean;  
 import org.springframework.context.annotation.Configuration;  
 import org.springframework.core.env.Environment;  
 import org.springframework.http.ResponseEntity;  
 import org.springframework.util.StopWatch;  
 @Configuration  
 @EnableSwagger  
 public class SwaggerConfiguration implements EnvironmentAware {  
   private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);  
   public static final String DEFAULT_INCLUDE_PATTERN = "/api/.*";  
   private RelaxedPropertyResolver propertyResolver;  
   @Override  
   public void setEnvironment(Environment environment) {  
     this.propertyResolver = new RelaxedPropertyResolver(environment, "swagger.");  
   }  
   /**  
    * Swagger Spring MVC configuration.  
    */  
   @Bean  
   public SwaggerSpringMvcPlugin swaggerSpringMvcPlugin(SpringSwaggerConfig springSwaggerConfig) {  
     log.debug("Starting Swagger");  
     StopWatch watch = new StopWatch();  
     watch.start();  
     SwaggerSpringMvcPlugin swaggerSpringMvcPlugin = new SwaggerSpringMvcPlugin(springSwaggerConfig)  
       .apiInfo(apiInfo())  
       .genericModelSubstitutes(ResponseEntity.class)  
       .includePatterns(DEFAULT_INCLUDE_PATTERN);  
     swaggerSpringMvcPlugin.build();  
     watch.stop();  
     log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());  
     return swaggerSpringMvcPlugin;  
   }  
   /**  
    * API Info as it appears on the swagger-ui page.  
    */  
   private ApiInfo apiInfo() {  
     return new ApiInfo(  
         propertyResolver.getProperty("title"),  
         propertyResolver.getProperty("description"),  
         propertyResolver.getProperty("termsOfServiceUrl"),  
         propertyResolver.getProperty("contact"),  
         propertyResolver.getProperty("license"),  
         propertyResolver.getProperty("licenseUrl"));  
   }  
 }  


8. run from ide or commandline
mvn clean install

9. run
mvn spring-boot:run

10. Access your application api documentation at http://localhost:8080/docs/index.html

Monday, January 26, 2015

Interesting Reads lately

Interesting reads;


The speakers provide insight into design and architectural challenges for creating REST services with Spring Integration with RabbitMQ.
http://www.infoq.com/presentations/rest-rabbitmq-spring-nodejs


I am also going to post some tutorials of some new materials soon.