Spring Boot Engineering / SPRING MVC & REST API / SPR-006
Suggested study path · Step 2 of 2 · G1
Transfer API
Explore concept graphMateri
Target: implementasikan
POST /transfersyang menghasilkan HTTP 201 + ID, danGET /transfers/{id}yang menghasilkan 200 atau 404, tanpa business logic dalam controller.
Mulai: sebelum menulis kode, tulis tabel kasus: create sukses → 201, get ditemukan → 200, get tidak ditemukan → 404, request tidak valid → 400 (bila validasi dikonfigurasi).
HTTP client
|
+-- POST /transfers + JSON body
| -> @PostMapping + @Valid @RequestBody
| -> TransferService.create(...)
| -> 201 Created + Location + id
|
+-- GET /transfers/{id}
-> @GetMapping + @PathVariable
-> TransferService.findById(...)
+-- found -> 200 OK + DTO
+-- absent -> 404 Not FoundPeta annotation Spring MVC
@RestController: controller yang mengembalikan response body sebagai representasi data.@RequestMapping("/transfers"): prefix route;@PostMappingdan@GetMapping("/{id}")memisahkan HTTP method.@PathVariable: bagian dari path;@RequestParam: parameter query/form;@RequestHeader: metadata HTTP.@Valid @RequestBody: binding dan validasi DTO jika ada field constraint serta Bean Validation provider yang terkonfigurasi.ResponseEntity: status, header (mis. Location) dan response body.
Contoh controller tipis (ilustrasi Spring MVC)
@RestController
@RequestMapping("/transfers")
class TransferController {
private final TransferService service;
TransferController(TransferService service) { this.service = service; }
@PostMapping
ResponseEntity<TransferResponse> create(
@Valid @RequestBody CreateTransferRequest input) {
Transfer saved = service.create(input);
var body = new TransferResponse(saved.id());
return ResponseEntity.created(URI.create("/transfers/" + saved.id())).body(body);
}
@GetMapping("/{id}")
ResponseEntity<TransferResponse> find(@PathVariable String id) {
return service.findById(id)
.map(found -> ResponseEntity.ok(new TransferResponse(found.id())))
.orElseGet(() -> ResponseEntity.notFound().build());
}
}CreateTransferRequest, TransferResponse, Transfer, dan TransferService adalah tipe aplikasi yang harus kamu implementasikan. Tambahkan constraint misalnya @NotBlank dan @Positive serta dependency spring-boot-starter-validation jika ingin validasi DTO. Contoh ini tidak menyertakan database, authorization, atau transaksi dana.
Konsep 1 / 3
Map Spring MVC controller methods to the correct path, verb, query parameter and header.
A service can work internally yet expose the wrong route or HTTP method, giving clients unexpected 404/405 responses.
Write @RequestMapping("/transfers") and predict which suffix belongs to GET versus POST.
Intuisi utama
The controller owns HTTP boundary translation. @RequestMapping supplies the base path; @PostMapping or @GetMapping selects the verb; @PathVariable identifies a resource; query and header bind metadata, not service business rules.
A Spring MVC @RestController under @RequestMapping("/transfers") can declare @PostMapping for resource creation and @GetMapping("/{id}") for lookup. A resource path id and an optional filter query have distinct semantics. @RequestHeader resolves metadata such as X-Request-Id; do not treat that header as an authenticated identity without verification.
Contoh bertahap
Map the API request GET /transfers/tr-001?verbose=true with X-Request-Id: req-7.
- Put @RequestMapping("/transfers") on the controller class.
Mengapa: This forms the shared route prefix for both handlers.
Hasil yang diharapkan: Both handlers start under /transfers.
- Add @GetMapping("/{id}") and @PathVariable String id.
Mengapa: The path variable captures one resource identifier.
Hasil yang diharapkan: id is tr-001, not the query parameter.
- Read optional @RequestParam boolean verbose and @RequestHeader(name="X-Request-Id",required=false).
Mengapa: Query options and request tracing metadata are independent of resource identity.
Hasil yang diharapkan: verbose is true; the optional request-id is req-7.
Konsep 2 / 3
Design a POST endpoint with validated input that returns 201, a resource ID and Location header.
A money-movement API must distinguish syntactically invalid input from a successfully created resource and make the resource address explicit.
Write the expected POST response status and Location before implementing the controller.
Intuisi utama
Binding converts the request body to a DTO; Bean Validation checks declared constraints; the service performs the operation; ResponseEntity builds the HTTP result. A 201 response requires explicit controller mapping, not a consequence of using POST alone.
@Valid @RequestBody CreateTransferRequest requires field constraints such as @NotBlank and @Positive and a configured Bean Validation implementation. ResponseEntity.created(URI.create("/transfers/"+id)).body(response) represents a design choice: 201 Created, Location and an ID in the body. Default validation failures return 400 when MVC validation is configured, but malformed JSON and other exception handling may have different pathways. Do not claim transactional safety, ledger integrity or idempotency from this HTTP controller alone.
Contoh bertahap
Accept POST /transfers with a valid sender and a positive amount, returning a stable transfer ID.
- Declare a CreateTransferRequest DTO with @NotBlank sender and @Positive amount.
Mengapa: Field-level constraints give @Valid concrete rules to evaluate.
Hasil yang diharapkan: A blank sender or non-positive amount fails validation when configured.
- Delegate to service.create(request) and obtain tr-001.
Mengapa: Domain creation and persistence belong in the service, not the HTTP adapter.
Hasil yang diharapkan: The controller only receives the resulting resource ID.
- Build ResponseEntity.created(URI.create("/transfers/tr-001")).body(response).
Mengapa: ResponseEntity controls status, headers and body.
Hasil yang diharapkan: HTTP 201 plus Location: /transfers/tr-001 and a response containing id tr-001.
Konsep 3 / 3
Implement GET 200/404 and keep controller logic limited to HTTP translation.
Putting transfer execution, retries or transaction handling inside a controller makes boundary tests misleading and couples domain policy to HTTP.
Write the 200 and 404 cases for GET /transfers/{id} before implementing the controller method.
Intuisi utama
The service returns an Optional transfer. The controller turns present into 200 + DTO and absent into 404, without exposing internal storage or deciding payment policy.
Spring MVC @GetMapping("/{id}") reads an ID through @PathVariable; a controller may use ResponseEntity.ok(...) for found and ResponseEntity.notFound().build() for absent. This is an explicit API contract choice. Service creation, authorization, idempotency, transaction and persistence are separate responsibilities; this lesson demonstrates boundary separation but does not implement production finance safety. A Java 21 JDK HttpServer fixture proves the observable 201/Location/200/404/400 protocol mapping, not Spring annotation wiring.
Contoh bertahap
Fetch tr-001 after creation and request tr-missing for an absent resource.
- Call service.findById("tr-001").
Mengapa: The service owns lookup and exposes the domain result.
Hasil yang diharapkan: Optional containing one transfer.
- Map that transfer to ResponseEntity.ok(response).
Mengapa: An existing resource is represented as 200.
Hasil yang diharapkan: GET /transfers/tr-001 returns HTTP 200.
- Map Optional.empty() to ResponseEntity.notFound().build().
Mengapa: A missing ID should not be disguised as a successful empty response.
Hasil yang diharapkan: GET /transfers/unknown returns HTTP 404.
Referensi resmi
Sumber
Cross-domain connections
Curated relationships for this unit at G1. Proposed edges are suggestions, not prerequisites.
Dashed = proposed relationship; solid = reviewed connection. Only reviewed prerequisites constrain a learning path. Keyboard and text links remain available.