Endpoint: GET /greeting
Relevant source files
The following files were used as context for generating this wiki page:- complete/src/main/java/com/example/restservice/GreetingController.java
- complete/src/main/java/com/example/restservice/Greeting.java
- complete/src/main/java/com/example/restservice/RestServiceApplication.java
- complete/src/test/java/com/example/restservice/GreetingControllerTests.java
- README.adoc
- complete/pom.xml
Introduction
The GET /greeting endpoint provides a simple, RESTful "Hello, World" web service. It is designed to accept HTTP GET requests and respond with a JSON representation of a greeting. The service can be run on http://localhost:8080/greeting.
The response content can be customized by providing an optional name parameter in the query string (e.g., /greeting?name=User). If the name parameter is not provided, it defaults to "World". The endpoint also includes a unique, incrementing ID for each greeting generated. This functionality serves as a basic example of building a RESTful web service using the Spring Framework.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java
Architecture and Components
The service is built around three primary Java classes within a standard Spring Boot application structure. The spring-boot-starter-web dependency provides all necessary components for web development, including an embedded Tomcat server and the Jackson library for JSON conversion.
Sources: complete/pom.xml:21-24
Core Components
| Class | Role | Annotation | Source File |
|---|---|---|---|
RestServiceApplication | The main class that bootstraps and runs the Spring Boot application. | @SpringBootApplication | complete/src/main/java/com/example/restservice/RestServiceApplication.java |
GreetingController | A REST controller that handles incoming HTTP requests to the /greeting path. | @RestController | complete/src/main/java/com/example/restservice/GreetingController.java |
Greeting | A Java record class that models the data structure for the JSON response. It contains the id and content of the greeting. | record | complete/src/main/java/com/example/restservice/Greeting.java |
Component Diagram
This diagram illustrates the relationship between the main application class, the controller, and the data model.
Request Handling Flow
When a client sends a GET request to /greeting, the Spring Framework routes it to the greeting() method in the GreetingController class. The controller then processes the request and returns a Greeting object, which Spring automatically serializes into a JSON response.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java:14-17
Sequence of Events
The following sequence diagram shows the interaction between a client, the Spring application, and the GreetingController.
Controller Logic
The GreetingController class contains the core logic for handling the request.
// complete/src/main/java/com/example/restservice/GreetingController.java
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:8-18
@RestController: This annotation marks the class as a controller where every method returns a domain object instead of a view. It's a shorthand for@Controllerand@ResponseBody.@GetMapping("/greeting"): This maps HTTP GET requests for/greetingto thegreeting()method.@RequestParam: This annotation binds the value of thenamequery parameter to thenamemethod parameter. If the parameter is absent, it uses thedefaultValueof "World".AtomicLong counter: A thread-safe counter is used to generate a uniqueidfor each request.- Return Value: The method creates and returns a new
Greetingobject. Spring'sMappingJackson2HttpMessageConverterautomatically converts this object to a JSON string for the HTTP response body.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java:8-18
API Specification
Endpoint Details
| Property | Value - |
|---|---|
| Method | GET - |
- Path |
/greeting- | - Parameters|
name(optional, string, default: "World") - | - Response |
200 OKwith a JSON body representing theGreetingobject. - |
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:15-16, README.adoc
Response Body
The response is a JSON object with two fields: id and content.
| Field | Type | Description |
|---|---|---|
id | long | A unique identifier for the greeting. |
content | String | The textual representation of the greeting. |
Sources: complete/src/main/java/com/example/restservice/Greeting.java:3, README.adoc
Example Responses
Request: GET /greeting
{
"id": 1,
"content": "Hello, World!"
}
Request: GET /greeting?name=User
{
"id": 2,
"content": "Hello, User!"
}
Sources: README.adoc
Testing
The project includes unit tests for the GreetingController to ensure it behaves as expected. The tests use Spring's MockMvc to perform mock HTTP requests and validate the responses without needing to run a full server.
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java
Test Cases
The GreetingControllerTests class contains two primary test cases:
noParamGreetingShouldReturnDefaultMessage(): This test sends a GET request to/greetingwithout any parameters. It asserts that the HTTP status is200 OKand that thecontentfield in the JSON response is "Hello, World!".paramGreetingShouldReturnTailoredMessage(): This test sends a GET request to/greetingwith the parametername=Spring Community. It asserts that the status is200 OKand thecontentfield is "Hello, Spring Community!".
// complete/src/test/java/com/example/restservice/GreetingControllerTests.java
@SpringBootTest
@AutoConfigureMockMvc
public class GreetingControllerTests {
@Autowired
private MockMvc mockMvc;
@Test
public void noParamGreetingShouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.content").value("Hello, World!"));
}
@Test
public void paramGreetingShouldReturnTailoredMessage() throws Exception {
this.mockMvc.perform(get("/greeting").param("name", "Spring Community"))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.content").value("Hello, Spring Community!"));
}
}
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java:29-47
Summary
The GET /greeting endpoint is a fundamental demonstration of creating a RESTful web service using Spring Boot. It effectively showcases key features such as request mapping with @GetMapping, parameter binding with @RequestParam, automatic JSON serialization of POJOs (or Java Records), and a stateful, thread-safe counter. The simplicity of the implementation, combined with the power of the Spring framework, makes it an excellent starting point for understanding REST API development.