A Spring Boot API
Controllers, validation and JSON are enough to ship a useful endpoint.
What you will be able to do
- Use @RestController and @GetMapping for JSON endpoints.
- Validate request records with Bean Validation.
- Return 400 for invalid input and 404 for a missing resource.
In plain English
Spring Boot wires a servlet container and JSON serialization. A controller maps HTTP to a typed method. Validate input with annotations, return appropriate status codes and keep persistence in a service layer.
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/lessons")
public class LessonController {
private final LessonService service;
public LessonController(LessonService service) {
this.service = service;
}
@GetMapping
public List<Lesson> list() {
return service.published();
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Lesson create(@RequestBody LessonInput input) {
return service.create(input);
}
}Your turn
MediumAdd a GET endpoint
Create a controller with GET /api/health returning a map with ok = true.
JAVA · starter
@RestController
public class HealthController {}Check your understanding before moving on.
Knowledge checkQuestion 1
Which annotation marks a class whose methods return JSON data?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.