REST APIs with Spring
rest apis with spring a rest api exposes resources over http using verbs (get, post, put, delete). spring's annotation model makes mapping
Introduction
A REST API exposes resources over HTTP using verbs (GET, POST, PUT, DELETE). Spring's annotation model makes mapping trivial.
Informative example
A full CRUD controller:
@RestController@RequestMapping("/api/products")public class ProductController {private final ProductService svc;public ProductController(ProductService svc) { this.svc = svc; }@GetMappingpublic List<Product> list() { return svc.findAll(); }@GetMapping("/{id}")public Product get(@PathVariable long id) { return svc.findById(id); }@PostMapping@ResponseStatus(HttpStatus.CREATED)public Product create(@Valid @RequestBody ProductDto dto) {return svc.create(dto);}@PutMapping("/{id}")public Product update(@PathVariable long id, @Valid @RequestBody ProductDto dto) {return svc.update(id, dto);}@DeleteMapping("/{id}")@ResponseStatus(HttpStatus.NO_CONTENT)public void delete(@PathVariable long id) { svc.delete(id); }}
Best practices
- Use DTOs for request/response — never expose entities directly.
- Validate input with
@Valid+ Bean Validation annotations. - Return correct status codes: 201 Created, 204 No Content, 404 Not Found.
- Document with springdoc-openapi for free Swagger UI.
Purpose of this lesson
Master REST APIs with Spring so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind REST APIs with Spring.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when rest apis with spring is the right tool for the problem.
Useful template
REST controller
@RestController@RequestMapping("/api/users")public class UserController {@GetMapping("/{id}")public User get(@PathVariable Long id) { return service.find(id); }}
Debugging tips
404? Verify@RequestMappingbase path and HTTP method match exactly.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply REST APIs with Spring daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain REST APIs with Spring in one minute.
Q2When would you avoid REST APIs with Spring?
Summary
In this lesson you learned REST APIs with Spring — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.