REST APIs are the backbone of modern web and microservice architectures.
Spring Boot makes building REST APIs straightforward, but to use them in real systems, you must understand not just what to annotate — but why and how it works end-to-end.
This guide explains REST APIs in Spring Boot with production-grade clarity, covering request routing, status handling, data serialization, validation, and common patterns used in real applications.
What Is a REST API?
REST (Representational State Transfer) is an architectural style that allows clients — like web and mobile applications — to interact with a backend service using stateless HTTP requests.
In Spring Boot, REST APIs are typically:
- JSON-based
- Resource oriented
- Controlled via HTTP methods
REST is not a Spring-specific model — it’s a standard architectural approach for building web services.
Why Spring Boot for REST APIs?
Spring Boot simplifies REST API development by providing:
✔ Embedded server (Tomcat/Jetty)
✔ Annotation-based routing
✔ Automatic JSON (De)Serialization
✔ Validation support
✔ Exception handling
✔ Profile-specific behavior
Most production microservices use Spring Boot for these reasons.
Core REST Annotations
Spring Boot maps HTTP requests using simple annotations.
@RestController
@RestController
@RequestMapping("/api/users")
public class UserController { … }
- Combines
@Controller+@ResponseBody - Automatically serializes responses as JSON
@GetMapping
Handles GET requests:
@GetMapping("/{id}")
public UserDto getUser(@PathVariable Long id) { … }
@PostMapping
Handles POST requests:
@PostMapping
public UserDto createUser(@RequestBody @Valid UserDto user) { … }
Other common mappings:
@PutMapping@PatchMapping@DeleteMapping
These correspond to HTTP methods.
Request Parameters and Path Variables
Path Variables
Used for identifying resources:
@GetMapping("/orders/{orderId}")
public OrderDto getOrder(@PathVariable Long orderId) { … }
Query Parameters
Used for filtering, sorting, paging:
@GetMapping
public List<UserDto> listUsers(@RequestParam String role) { … }
Request Body Handling
@RequestBody converts JSON into Java objects automatically using Jackson.
Example
@PostMapping
public UserDto createUser(@RequestBody @Valid UserDto user) { … }
Validation
Spring Boot supports validation using:
@NotBlank
@Email
private String email;
Combine with:
@PostMapping
public ResponseEntity<UserDto> create(@Valid @RequestBody UserDto user) { … }
This ensures incoming data is checked before business logic runs.
Response Status Codes
Using correct HTTP status codes is critical for REST semantics.
Common responses:
| Status | Meaning |
|---|---|
| 200 OK | Successful GET/PUT |
| 201 Created | Successful POST |
| 204 No Content | DELETE success |
| 400 Bad Request | Validation error |
| 404 Not Found | Resource missing |
| 500 Internal Server Error | Unhandled exception |
Example of returning a 201:
@PostMapping
public ResponseEntity<UserDto> create(@Valid @RequestBody UserDto user) {
UserDto created = userService.create(user);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
JSON (De)Serialization
Spring Boot uses Jackson by default. It:
- Converts Java objects to JSON in responses
- Parses JSON into Java objects for requests
Proper DTO design and naming conventions help create clean, stable API contracts.
Error Handling in REST APIs
Without explicit handling, Spring Boot returns default error responses — which aren’t always suitable for clients.
Use @ControllerAdvice for global error handling:
@ControllerAdvice
public class ApiExceptionHandler { … }
This lets you:
- Standardize API error structure
- Return custom messages with HTTP codes
- Log errors consistently
Logging and Production Readiness
Logs are essential for diagnosing issues.
Enable structured logging:
- Include request IDs
- Log request/response payloads at DEBUG only when needed
- Avoid logging sensitive data
See how to enable debug logging here:
https://springbootfixes.com/how-to-enable-debug-logging-in-spring-boot-for-production-issues/
Security and CORS
REST APIs often get called from client apps (Angular, React).
CORS (Cross Origin Resource Sharing) must be configured correctly:
For production CORS, see:
https://springbootfixes.com/how-to-fix-spring-boot-cors-error-angular-react-frontend/
Pagination and Sorting
Most production APIs include pagination:
@GetMapping
public Page<UserDto> list(
Pageable pageable
) { … }
Spring Boot integrates with Spring Data for paging and sorting — important for large datasets.
API Versioning
Versioning protects clients when APIs evolve.
Two common patterns:
URL Versioning
/api/v1/users
Header Versioning
Accept: application/vnd.app.v1+json
Choose one consistently across services.
HATEOAS & Hypermedia (Optional)
For advanced REST APIs, HATEOAS adds links to responses:
userModel.add(linkTo(methodOn(UserController.class).getUser(id)).withSelfRel());
This builds discoverable APIs — useful in complex ecosystems.
Internal API Docs with Swagger
Use Springdoc/OpenAPI for interactive API documentation:
Add dependency:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
</dependency>
You get:
- Web UI for API definitions
- Easy testing and documentation
- Better client collaboration
Related Spring Boot Guides
- Spring Boot Startup Flow Explained
https://springbootfixes.com/how-spring-boot-application-starts-startup-flow-explained/ - Dependency Injection in Spring Boot
https://springbootfixes.com/dependency-injection-in-spring-boot-production-grade-explanation/ - Configuration & Profiles in Spring Boot
https://springbootfixes.com/spring-boot-configuration-and-profiles-explained-beginner-to-production-guide/ - Logging Best Practices (Debug, Trace, etc)
https://springbootfixes.com/how-to-enable-debug-logging-in-spring-boot-for-production-issues/
Summary — Production REST API Checklist
✔ Use correct HTTP methods
✔ Clear URL design
✔ Proper status codes
✔ Validation rules
✔ Error standardization
✔ Logging and diagnostics
✔ Security & CORS
✔ Versioning & docs
