👏

How to create a simple API in Spring boot

2025/03/06に公開

Environment

  • Windows11
  • maven: 3.9.9
  • Java 21

Create a Spring Boot Project

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