Creating RESTful Services in Java
This guide walks through building a complete REST API with Spring Boot — from project setup to handling requests, validation, and structured error responses.
Project Setup
Use Spring Initializr (start.spring.io) with Spring Web dependency. JDK 17+, Maven or Gradle. The embedded Tomcat server runs your API on port 8080.
Controller Layer
@RestController
@RequestMapping("/api/v1/books")
@RequiredArgsConstructor
public class BookController {
private final BookService bookService;
@GetMapping
public List<BookDto> list(@RequestParam(defaultValue = "0") int page) {
return bookService.findAll(page);
}
@PostMapping
public ResponseEntity<BookDto> create(@Valid @RequestBody CreateBookRequest req) {
BookDto created = bookService.create(req);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
}Layered Architecture
- Controller — HTTP layer, request/response mapping.
- Service — Business logic, transactions.
- Repository — Data access (JPA, JDBC).
- DTO — Data transfer objects for API contracts.
- Entity — Database-mapped objects (keep separate from DTOs).
Frequently Asked Questions
Should I expose JPA entities directly?▼
No. Use DTOs to control the API contract, hide internal fields, and prevent lazy-loading serialization issues.
