Sub topic 1
From Hand-Written Calls to an Interface
Prerequisites
Assume Java 17 or later, basic Spring Boot bean configuration and dependency injection, HTTP methods and status codes, JSON, and Spring MVC annotations.
From Hand-Written Calls to an Interface
A hand-written RestClient call mixes two concerns: describing the remote endpoint and executing an HTTP request. Each call repeats URLs, headers, serialization, and response handling.
Spring HTTP interfaces separate the description from the execution. An HTTP interface is a Java interface whose annotations describe a remote API. Spring later creates a proxy, which is an object that implements the interface and performs the HTTP calls.
Describing Endpoints with `@HttpExchange`
@HttpExchange can define a shared path and HTTP settings. Method-specific annotations such as @GetExchange and @PostExchange describe individual operations.
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
@HttpExchange("/todos")
public interface TodoClient {
@GetExchange("/{id}")
Todo get(@PathVariable("id") long id,
@RequestHeader("X-Trace-Id") String traceId);
@GetExchange
List<Todo> list(@RequestParam("userId") long userId);
@PostExchange
ResponseEntity<Todo> create(@RequestBody Todo todo);
}
record Todo(Long id, Long userId, String title, boolean completed) {}Binding Arguments: Path, Query, Headers, and Body
Spring maps method arguments to request parts:
@PathVariablereplaces{id}in the path.@RequestParamadds a query parameter such as?userId=1.@RequestHeaderadds a named HTTP header.@RequestBodyserializes an object as JSON.
Choosing Return Types
Use a body type such as Todo when the response body is the main result. Use ResponseEntity<Todo> when status codes or response headers matter. Use void when the endpoint has no useful response body, such as a successful delete.
Exercise
Which annotation should bind a method argument to ?userId=1?
Show answer
Use @RequestParam("userId").