Web

REST API Fundamentals

Controllers, validation, exception handling โ€” the annotations, the patterns, and the two things most people get wrong.

01
Controllers

Controller Basics

@RestController = @Controller + @ResponseBody. Every method return value is serialised to JSON (via Jackson) and written directly to the HTTP response body.

@RequestMapping at class level sets the base path. Constructor injection in controllers โ€” @Autowired on the field is wrong here too.

One-sentence mental model: the front controller that routes all HTTP requests to the correct @RestController method based on URL, HTTP method, and content type.

Request Routing Flow
HTTP Request
DispatcherServlet
HandlerMapping
Method Executes
MessageConverter
HTTP Response
02
Routing

Request Mapping

AnnotationHTTP VerbTypical Use
@GetMappingGETRead / list
@PostMappingPOSTCreate
@PutMappingPUTFull replace
@PatchMappingPATCHPartial update
@DeleteMappingDELETEDelete
  • @PathVariable โ€” identity: /users/{id}
  • @RequestParam โ€” filter/option: /users?status=active
  • Rule of thumb: identity โ†’ path, filter/option โ†’ query param
03
Input

Request Data

  • @RequestBody โ€” JSON โ†’ Java object via Jackson. Requires Content-Type: application/json.
  • @RequestHeader โ€” reading a specific header value
DTOs over entities: Never expose your JPA entity directly as the request/response body. Entity is a DB concern; DTO is an API concern. Change independently. One entity โ†’ multiple DTOs for different endpoints is normal.
04
Output

Responses

Return type choices: plain object (Spring picks 200 OK) vs ResponseEntity<T> when you need to control status code, headers, or conditional body.

ScenarioStatus
Successful GET / PUT200 OK
Successful POST (created)201 Created
Successful DELETE204 No Content
Validation failure400 Bad Request
Not authenticated401 Unauthorized
Authenticated, no permission403 Forbidden
Resource not found404 Not Found
05
Input Safety

Validation

@Valid on @RequestBody triggers Bean Validation. Put constraint annotations on the DTO fields, not the entity.

  • @NotNull / @NotBlank โ€” null vs empty string distinction
  • @Size(min, max) โ€” string length or collection size
  • @Min / @Max โ€” numeric bounds
  • @Email / @Pattern โ€” format validation

@Validated supports group validation and works on the service layer too. @Valid is the standard JSR-303 annotation โ€” works on @RequestBody params. Without a handler, validation failures return a noisy 400 โ€” you want to intercept this.

06
Errors

Exception Handling

Global exception handler โ€” applies to all controllers. @ExceptionHandler(SomeException.class) maps an exception type to a structured error response. Specific handlers win over general ones.

The pattern: timestamp, status, error, message, path. Spring Boot 3.x supports Problem Details (RFC 7807) natively via ProblemDetail.

Exception Handling Flow
Controller Throws
@ControllerAdvice
@ExceptionHandler
ErrorResponse DTO
JSON Response
Gotcha: If your @ControllerAdvice class is outside the component scan package, it is silently ignored. No error, no warning โ€” just no exception handling.