👏
How to create a simple API in Spring boot
Environment
- Windows11
- maven: 3.9.9
- Java 21
Create a Spring Boot Project
- Access: Spring Initializr
- Select each item
- Choose Spring Web
- Push GENERATE button
Open the Project
- Open the project your IDE
Create a simple REST Controller
src/main/java/myblog/myapi/controller/HelloController.java
package blog_spring.myblog.controller;
// Maps HTTP GET requests to methods
import org.springframework.web.bind.annotation.GetMapping;
// Defines the base URL path for the controller
import org.springframework.web.bind.annotation.RequestMapping;
// Marks the class as a REST controller, returning JSON or text responses.
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyFirstAPI {
@GetMapping("/hello")
public String SayHello() {
return "Hello, Spring Boot!";
}
}
Run the application
- Run:
mvn spring-boot:run
Test the api
- Access:
http://localhost:8080/api/hello
Discussion