Spring Boot Rest API Hello World Examples
Purpose: In this post, we will learn how we can enable swagger in spring boot and test API. The steps are given below.
1. Setup and Create Project: Visit here. Spring Boot Rest API Hello World Examples.
Next Step. Spring Boot Parent Dependencies.
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.0.M1</version><relativePath /> <!-- lookup parent from repository --></parent>
Next Step. Swagger Dependencies.
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency>
Next Step. Spring Boot main class.
Class: Application.java
Note: @SpringBootApplication=@Configuration+ @EnableAutoConfiguration+ @ComponentScan.
package com.bce;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;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;@SpringBootApplication@EnableSwagger2public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();}}
Next Step. Create Rest Controller.
package com.bce.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloWorldRestController {@GetMappingpublic String hello() {return "Hello World";}}
Next Step. Server Port: The default server port is 8080. Wish you want to change open application.properties and add the below line.
server.port=8081
Next Step. Run the application without swagger. See demo below.
Next Step: Test with swagger. Open given below URL on the browser.
Download Code from GitHub. Download
No comments:
Post a Comment