How is REST used in microservices and what are its trade-offs?
Topic: microservices, Communication. Level: Basic.
Answer
REST over HTTP/JSON is the default for synchronous service-to-service and client-to-service calls. It is ubiquitous, language-agnostic, cacheable, and human-readable. Trade-offs: JSON is verbose and slower to (de)serialize than binary formats, there is no built-in contract enforcement (needs OpenAPI), over-/under-fetching is common, and streaming is awkward. Good REST in microservices uses proper status codes, versioned URIs (`/v1/orders`), idempotency keys for retries, and pagination.
```java
@RestController
@RequestMapping("/v1/orders")
class OrderController {
@PostMapping
ResponseEntity<Order> create(@RequestBody @Valid OrderRequest req,
@RequestHeader("Idempotency-Key") String key) {
Order o = service.createIdempotent(key, req);
return ResponseEntity.status(HttpStatus.CREATED).body(o); // 201
}
@GetMapping("/{id}")
ResponseEntity<Order> get(@PathVariable String id) {
return service.find(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build()); // 404
}
}
```