HTTP verbs and status codes, building REST controllers, and consuming services with RestTemplate.
@RestController and ResponseEntity; and using
RestTemplate to call another service.
REST (Representational State Transfer) is an architectural style that uses HTTP as its protocol. Its hallmarks: stateless requests, resources identified by URIs, a uniform interface built on the standard HTTP verbs, and representations (usually JSON) exchanged in message bodies.
| Verb | Purpose | Safe? | Idempotent? |
|---|---|---|---|
GET | Read a resource | ✅ yes | ✅ yes |
POST | Create a resource | ❌ no | ❌ no |
PUT | Create/replace (full update) | ❌ no | ✅ yes |
PATCH | Partial update | ❌ no | ❌ no |
DELETE | Remove a resource | ❌ no | ✅ yes |
GET, HEAD). Idempotent = repeating it has the
same effect as doing it once (GET, PUT, DELETE). POST is
neither — two POSTs create two resources.
| Code | Meaning | Class |
|---|---|---|
200 | OK | 2xx success |
201 | Created (after a successful POST) | |
204 | No Content | |
400 | Bad Request | 4xx client error |
401 | Unauthorized (not authenticated) | |
403 | Forbidden (authenticated, not allowed) | |
404 | Not Found | |
500 | Internal Server Error | 5xx server error |
401 vs 403: 401 = "I don't know who you are" (not authenticated); 403 = "I know who you are, but you can't" (not authorised).
Use @RestController (Lesson 11) with the verb-mapping shortcuts. For full control of the status,
headers and body, return a ResponseEntity; for a fixed status, use
@ResponseStatus:
@PostMapping
public ResponseEntity<Account> create(@RequestBody Account a) {
Account saved = service.save(a);
return ResponseEntity.status(HttpStatus.CREATED).body(saved); // 201 + body
}
The @RestController, @RequestBody and @ResponseBody annotations live in the
spring-web module. A returned object is serialised to JSON by an
HttpMessageConverter — Jackson by default.
RestTemplateRestTemplate is Spring's synchronous client for calling REST services (it uses the
same HttpMessageConverters to (de)serialise). Common methods:
| Method | Does |
|---|---|
getForObject(url, Type.class) | GET → response body mapped to an object |
getForEntity(url, Type.class) | GET → a ResponseEntity (status + headers + body) |
postForObject(url, body, Type.class) | POST → response body as object |
exchange(url, method, entity, Type.class) | any verb, full request/response control |
(In newer Spring, WebClient is the recommended reactive alternative — but the exam tests RestTemplate.)
Read the "Handler Methods" return-value table (ResponseEntity) and the RestTemplate method summary.
The safe/idempotent verbs, the status codes, and the RestTemplate methods are the money questions. Covers your book's whole REST section. Options shuffle on every load.
RestTemplate call example?
Ask. Say "continue" to start Section 4 — Testing with Lesson 13.