Java - Spring Boot REST API
Spring Boot REST API
Controller
// src/main/java/com/example/demo/api/GreetController.java
package com.example.demo.api;
import org.springframework.web.bind.annotation.*;
record GreetResponse(String message) {}
@RestController
@RequestMapping("/api")
class GreetController {
@GetMapping("/greet")
GreetResponse greet(@RequestParam(defaultValue = "World") String name) {
return new GreetResponse("Hello, " + name + "!");
}
}
Run and Test
./mvnw spring-boot:run
# In another terminal
curl "http://localhost:8080/api/greet?name=Ada"
Simple Test
// src/test/java/com/example/demo/api/GreetControllerTest.java
package com.example.demo.api;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.beans.factory.annotation.Autowired;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
class GreetControllerTest {
@Autowired MockMvc mvc;
@Test void greet() throws Exception {
mvc.perform(get("/api/greet").param("name","Ada"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Ada!"));
}
}
Architect note: Add validation (spring-boot-starter-validation) and standardized error responses for production APIs.