Generating Swagger representation of Spring boot Api
Posted By : Ranjan Mondal | 24-Sep-2017
Introduction :
Swagger is description format of Rest Apis. It allows user to know about ur apis endpoints and type of endpoints (GET, POST).
It allows to know input parameters and output parameters and its authentication methods.
Its format very readable to people and machine. It can be written in YAML or json.
Step 1. Add dependencies in pom.xml
io.springfox springfox-swagger2 2.6.1 compile io.springfox springfox-swagger-ui 2.6.1 compile
Step 2. In main class file add following code. @EnableSwagger2 , Docket and Api Info are things to added.
@SpringBootApplication
@EnableSwagger2
@ComponentScan({ "com.example" })
public class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
@Bean
public Docket petApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("CRUD_SWAGGER").apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("CRUD Zone").description("Spring REST API's for CRUD zone")
// .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
.contact("Self technologies").version("2.0").build();
}
}
Step 3: In Controller Class, Add@RestController on class and @ApiOperation on method
@RestController
@Component
public class AdminController {
private static final Logger LOGGER = LoggerFactory.getLogger(AdminController.class);
@Autowired
private UserService userService;
@Autowired
private AdminService adminService;
@Autowired
MessageLocaleService messageLocaleService;
@ApiOperation(value = "Add a user")
@RequestMapping(value="/api/v1/addUser", method=RequestMethod.POST, produces = "application/json")
ResponseEntity
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ranjan Mondal
Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.