Adding a New Endpoint
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/pom.xml
- complete/src/test/java/com/example/restservice/GreetingControllerTests.java
- README.adoc
This document outlines the process of creating a new RESTful web service endpoint within this Spring Boot project. The existing /greeting endpoint serves as the primary example. The process involves defining a data model for the response, creating a controller to handle HTTP requests, and configuring the necessary dependencies to enable web and JSON functionalities.
The fundamental architecture relies on Spring MVC. HTTP requests are received by the framework and routed to controller methods based on annotations. The controller processes the request, creates a response object, and returns it. Spring, with the help of the Jackson library, automatically serializes this object into a JSON string and writes it to the HTTP response body.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java
Core Components
The service is built upon a few key components that work together to handle web requests.
| Component | File | Description |
|---|---|---|
RestServiceApplication | RestServiceApplication.java | The main application class that bootstraps the Spring Boot application using @SpringBootApplication. |
GreetingController | GreetingController.java | A REST controller that handles incoming HTTP requests for the /greeting path. |
Greeting | Greeting.java | A Java record that serves as the data transfer object (DTO) for the JSON response. |
Sources: complete/src/main/java/com/example/restservice/RestServiceApplication.java:8, complete/src/main/java/com/example/restservice/GreetingController.java:8, complete/src/main/java/com/example/restservice/Greeting.java:3
The following diagram illustrates the relationship between the controller and the data model.
This diagram shows that GreetingController creates and returns an instance of the Greeting record.
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:14-16, complete/src/main/java/com/example/restservice/Greeting.java:3
Step 1: Define the Resource Representation
Before creating the endpoint, you must define the data structure of the response. In this project, this is achieved with a simple Java record class.
The Greeting class is a data carrier for the response payload. It is defined as a record for conciseness.
// complete/src/main/java/com/example/restservice/Greeting.java
package com.example.restservice;
public record Greeting(long id, String content) { }
Sources: complete/src/main/java/com/example/restservice/Greeting.java:3
| Field | Type | Description |
|---|---|---|
id | long | A unique identifier for the greeting. |
content | String | The textual representation of the greeting message. |
Sources: complete/src/main/java/com/example/restservice/Greeting.java:3, README.adoc
Instances of this class are automatically marshaled into JSON by the Jackson 2 library, which is included as part of the spring-boot-starter-web dependency.
Sources: README.adoc, complete/pom.xml:20-23
Step 2: Create the Resource Controller
The controller is responsible for handling HTTP requests. In Spring, a controller that handles REST requests is annotated with @RestController.
Controller Implementation
The GreetingController class defines the logic for the /greeting endpoint.
// 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
Key Annotations
| Annotation | Purpose |
|---|---|
@RestController | Marks the class as a controller where every method returns a domain object instead of a view. It's a shorthand for @Controller and @ResponseBody. |
@GetMapping("/greeting") | Maps HTTP GET requests for the /greeting path to the greeting() method. |
@RequestParam | Binds the value of a URL query string parameter to a method parameter. |
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java:8,14,15
Request Handling Flow
The following sequence diagram shows the flow of a typical request to the /greeting endpoint.
This diagram illustrates how a client request is processed by the Spring Framework, delegated to the GreetingController, and how the response is generated and returned as JSON.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java:14-16
Endpoint Parameters
The /greeting endpoint accepts one optional parameter.
| Parameter | Type | Required | Default Value | Description |
|---|---|---|---|---|
name | String | No | "World" | The name to include in the greeting message. |
Sources: complete/src/main/java/com/example/restservice/GreetingController.java:15, README.adoc
Step 3: Configure Project Dependencies
To enable web service capabilities, the project's pom.xml must include the spring-boot-starter-web dependency. This starter pulls in all necessary libraries, including Spring MVC for handling requests, an embedded Tomcat server to run the application, and Jackson for JSON serialization.
<!-- complete/pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Sources: complete/pom.xml:19-23
The project also requires a testing dependency, spring-boot-starter-test, to write and run unit and integration tests.
Sources: complete/pom.xml:25-29
Step 4: Test the Endpoint
Testing is a critical part of adding a new endpoint. The GreetingControllerTests class demonstrates how to test the controller using Spring's MockMvc.
The test class is annotated with @SpringBootTest and @AutoConfigureMockMvc to load the full application context and configure the MockMvc instance.
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java:29-30
Test Cases
-
No Parameter: A GET request to
/greetingshould return the default message.// complete/src/test/java/com/example/restservice/GreetingControllerTests.java @Test public void noParamGreetingShouldReturnDefaultMessage() throws Exception { this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk()) .andExpect(jsonPath("$.content").value("Hello, World!")); }This test verifies that the HTTP status is 200 OK and the
contentfield in the JSON response is "Hello, World!".
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java:36-41 -
With Parameter: A GET request to
/greeting?name=Spring%20Communityshould return a tailored message.// complete/src/test/java/com/example/restservice/GreetingControllerTests.java @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!")); }This test verifies the status is 200 OK and the
contentfield reflects the providednameparameter.
Sources: complete/src/test/java/com/example/restservice/GreetingControllerTests.java:44-49
Summary
Adding a new REST endpoint in this project follows a clear pattern:
- Define the Model: Create a plain Java object (or record) to represent the data in the response body.
- Create the Controller: Create a class annotated with
@RestControllerand add a public method to handle requests. - Map the Request: Use mapping annotations like
@GetMappingto link a URL path and HTTP method to your controller method. Use@RequestParamto access URL parameters. - Implement Logic: Inside the method, create and return an instance of your model. Spring handles the JSON conversion.
- Test: Write tests using
MockMvcto verify the endpoint's behavior, status codes, and response body.
This approach leverages the power of Spring Boot to create robust and testable REST APIs with minimal boilerplate code.
Sources: README.adoc, complete/src/main/java/com/example/restservice/GreetingController.java, complete/src/test/java/com/example/restservice/GreetingControllerTests.java