Spring Boot REST API
A Spring Boot REST API exposes your data as JSON over HTTP, so web front ends, mobile apps and other services can use it. You write plain Java methods in a @RestController, and Spring handles URL routing, JSON conversion, validation and status codes. This lesson builds a course catalog API step by step, from the first GET endpoint to validation, error handling, pagination and a Java client.
The ideas of resources, HTTP methods and status codes come from REST API in Java; here Spring does the plumbing that servlets made you write by hand. Examples use Spring Boot 4.1. Each output assumes a freshly started application.
Spring Boot REST API Project Setup
<dependencies>
<!-- Spring MVC, embedded Tomcat and Jackson for JSON -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<!-- Bean Validation (@NotBlank, @Min, ...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
package com.gocourse.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CourseApiApplication {
public static void main(String[] args) {
SpringApplication.run(CourseApiApplication.class, args);
}
}
How it works:
- In Spring Boot 4 the web starter is named
spring-boot-starter-webmvc. The olderspring-boot-starter-webstill works but is deprecated. - Validation is a separate starter. Without it,
@Validannotations are silently ignored. - Created with the Spring Boot tutorial setup, the app listens on port 8080.
Create Your First @RestController
Start with the data and a service that holds it. A Java record is a perfect fit for JSON data.
package com.gocourse.api.course;
public record Course(String code, String title, String category, int feeInr, int seats) {}
package com.gocourse.api.course;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class CourseNotFoundException extends RuntimeException {
public CourseNotFoundException(String code) {
super("Course " + code + " not found");
}
}
package com.gocourse.api.course;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import org.springframework.stereotype.Service;
@Service
public class CourseService {
// sorted by code and safe for many request threads
private final Map<String, Course> courses = new ConcurrentSkipListMap<>();
public CourseService() {
save(new Course("java", "Java Programming", "backend", 4999, 30));
save(new Course("go", "Go Language", "backend", 2999, 20));
save(new Course("html", "HTML and CSS", "web", 1999, 40));
save(new Course("react", "React Basics", "web", 3499, 25));
save(new Course("spring", "Spring Boot", "backend", 5999, 2));
}
public List<Course> findAll(String category) {
return courses.values().stream()
.filter(course -> category == null || course.category().equalsIgnoreCase(category))
.toList();
}
public Course get(String code) {
Course course = courses.get(code);
if (course == null) {
throw new CourseNotFoundException(code);
}
return course;
}
Course save(Course course) {
courses.put(course.code(), course);
return course;
}
}
package com.gocourse.api.course;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/courses")
public class CourseController {
private final CourseService service;
public CourseController(CourseService service) {
this.service = service;
}
@GetMapping
public List<Course> list(@RequestParam(required = false) String category) {
return service.findAll(category);
}
@GetMapping("/{code}")
public Course get(@PathVariable String code) {
return service.get(code);
}
}
curl -s -w "\n" http://localhost:8080/api/courses/java
curl -s -w "\n" "http://localhost:8080/api/courses?category=web"
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/courses/rust
{"code":"java","title":"Java Programming","category":"backend","feeInr":4999,"seats":30}
[{"code":"html","title":"HTML and CSS","category":"web","feeInr":1999,"seats":40},{"code":"react","title":"React Basics","category":"web","feeInr":3499,"seats":25}]
404
How it works:
@RestControllermeans every method's return value is written to the response body. Jackson turns theCourserecord into JSON using the component names as keys, the same mapping you saw in JSON in Java.@PathVariabletakesjavafrom/api/courses/java.@RequestParam(required = false)reads?category=weband isnullwhen the parameter is missing.@ResponseStatus(HttpStatus.NOT_FOUND)on the exception makes Spring answer 404 instead of 500 when a course is missing.
Request Mapping Annotations
| Annotation | HTTP method | Typical use | Success status |
|---|---|---|---|
@GetMapping | GET | Read one or many resources | 200 OK |
@PostMapping | POST | Create a resource | 201 Created |
@PutMapping | PUT | Replace a whole resource | 200 OK |
@PatchMapping | PATCH | Change some fields | 200 OK |
@DeleteMapping | DELETE | Remove a resource | 204 No Content |
Return Status Codes With ResponseEntity
ResponseEntity lets a method choose the status code and headers, not just the body. Creating a resource should return 201 Created with a Location header that points to the new resource.
package com.gocourse.api.course;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
public record CourseRequest(
@NotBlank @Pattern(regexp = "[a-z0-9-]{2,20}", message = "use 2-20 lowercase letters, digits or '-'")
String code,
@NotBlank @Size(max = 80) String title,
@NotBlank String category,
@PositiveOrZero int feeInr,
@Min(1) @Max(500) int seats) {}
// add to CourseService
public Course create(CourseRequest request) {
Course course = new Course(request.code(), request.title(), request.category(),
request.feeInr(), request.seats());
if (courses.putIfAbsent(course.code(), course) != null) {
throw new IllegalStateException("Course " + course.code() + " already exists");
}
return course;
}
public void delete(String code) {
if (courses.remove(code) == null) {
throw new CourseNotFoundException(code);
}
}
// add to CourseController
@PostMapping
public ResponseEntity<Course> create(@Valid @RequestBody CourseRequest request) {
Course created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{code}")
.buildAndExpand(created.code())
.toUri();
return ResponseEntity.created(location).body(created);
}
@DeleteMapping("/{code}")
public ResponseEntity<Void> delete(@PathVariable String code) {
service.delete(code);
return ResponseEntity.noContent().build();
}
curl -s -i -X POST -H "Content-Type: application/json" \
-d '{"code":"docker","title":"Docker Basics","category":"devops","feeInr":2499,"seats":35}' \
http://localhost:8080/api/courses
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE http://localhost:8080/api/courses/docker
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE http://localhost:8080/api/courses/docker
HTTP/1.1 201
Location: http://localhost:8080/api/courses/docker
Content-Type: application/json
(other headers trimmed)
{"code":"docker","title":"Docker Basics","category":"devops","feeInr":2499,"seats":35}
204
404
How it works:
@RequestBodyconverts the incoming JSON into aCourseRequest. A separate request record keeps clients from setting fields they should not control.ServletUriComponentsBuilder.fromCurrentRequest()starts fromhttp://localhost:8080/api/coursesand appends/docker, so theLocationheader is always correct, even behind a different host or port.- The first DELETE returns 204 with an empty body. The second finds nothing and returns 404, so clients can tell the two cases apart.
Validate Request Bodies With @Valid
@Valid runs the Bean Validation annotations on CourseRequest before your method starts. Invalid input never reaches the service.
| Annotation | Rule |
|---|---|
@NotBlank | Not null and not only spaces |
@Size(max = 80) | Length limit for text or collections |
@Pattern(regexp = ...) | Must match the regular expression |
@Min, @Max | Number range |
@PositiveOrZero | Number is 0 or more |
@Email | Looks like an email address |
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"Java Basics","title":"","category":"backend","feeInr":-100,"seats":30}' \
http://localhost:8080/api/courses
400
How it works:
- Three fields break their rules, so Spring throws
MethodArgumentNotValidExceptionand answers 400 Bad Request. - The default error body does not say which fields are wrong. The next section returns a clear, consistent error format.
Handle Errors With @RestControllerAdvice
A @RestControllerAdvice class catches exceptions from every controller and turns them into one JSON error shape. Clients then parse errors the same way everywhere.
package com.gocourse.api;
import com.gocourse.api.course.CourseNotFoundException;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiErrorHandler {
public record ApiError(int status, String error, String message, Map<String, String> fields) {}
@ExceptionHandler(CourseNotFoundException.class)
public ResponseEntity<ApiError> notFound(CourseNotFoundException ex) {
return build(HttpStatus.NOT_FOUND, ex.getMessage(), Map.of());
}
@ExceptionHandler(IllegalStateException.class)
public ResponseEntity<ApiError> conflict(IllegalStateException ex) {
return build(HttpStatus.CONFLICT, ex.getMessage(), Map.of());
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ApiError> badRequest(IllegalArgumentException ex) {
return build(HttpStatus.BAD_REQUEST, ex.getMessage(), Map.of());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> invalid(MethodArgumentNotValidException ex) {
Map<String, String> fields = new TreeMap<>(); // sorted field names
ex.getBindingResult().getFieldErrors()
.forEach(error -> fields.putIfAbsent(error.getField(), error.getDefaultMessage()));
return build(HttpStatus.BAD_REQUEST, "Validation failed", fields);
}
private ResponseEntity<ApiError> build(HttpStatus status, String message, Map<String, String> fields) {
return ResponseEntity.status(status)
.body(new ApiError(status.value(), status.getReasonPhrase(), message, fields));
}
}
curl -s -w "\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"Java Basics","title":"","category":"backend","feeInr":-100,"seats":30}' \
http://localhost:8080/api/courses
curl -s -w "\n" http://localhost:8080/api/courses/rust
curl -s -w "\n" -X POST -H "Content-Type: application/json" \
-d '{"code":"java","title":"Java Again","category":"backend","feeInr":100,"seats":5}' \
http://localhost:8080/api/courses
{"status":400,"error":"Bad Request","message":"Validation failed","fields":{"code":"use 2-20 lowercase letters, digits or '-'","feeInr":"must be greater than or equal to 0","title":"must not be blank"}}
{"status":404,"error":"Not Found","message":"Course rust not found","fields":{}}
{"status":409,"error":"Conflict","message":"Course java already exists","fields":{}}
How it works:
- Each
@ExceptionHandlermethod handles one exception type. The service keeps throwing plain Java exceptions and knows nothing about HTTP. - The
TreeMapsorts field names, so the error body is stable from run to run. IllegalStateExceptionmaps to 409 Conflict (the request is valid but clashes with current data) andIllegalArgumentExceptionto 400.
Note: Spring also has a built-in error format,
ProblemDetail(RFC 9457). You can returnProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage())from a handler instead of a custom record when clients expect that standard.
Update Resources With PUT and PATCH
PUT replaces the whole resource, so the client sends every field. PATCH changes only the fields it sends.
package com.gocourse.api.course;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.PositiveOrZero;
// null means "leave this field unchanged"
public record CoursePatch(@PositiveOrZero Integer feeInr, @Min(0) Integer seats) {}
// add to CourseService
public Course replace(String code, CourseRequest request) {
get(code); // 404 if it does not exist
if (!code.equals(request.code())) {
throw new IllegalArgumentException("Code in URL and body must match");
}
return save(new Course(code, request.title(), request.category(), request.feeInr(), request.seats()));
}
public Course patch(String code, CoursePatch patch) {
Course current = get(code);
return save(new Course(current.code(), current.title(), current.category(),
patch.feeInr() != null ? patch.feeInr() : current.feeInr(),
patch.seats() != null ? patch.seats() : current.seats()));
}
// add to CourseController
@PutMapping("/{code}")
public Course replace(@PathVariable String code, @Valid @RequestBody CourseRequest request) {
return service.replace(code, request);
}
@PatchMapping("/{code}")
public Course patch(@PathVariable String code, @Valid @RequestBody CoursePatch patch) {
return service.patch(code, patch);
}
curl -s -w "\n" -X PATCH -H "Content-Type: application/json" \
-d '{"feeInr":4499}' http://localhost:8080/api/courses/java
curl -s -w "\n" -X PUT -H "Content-Type: application/json" \
-d '{"code":"go","title":"Go Programming","category":"backend","feeInr":3299,"seats":24}' \
http://localhost:8080/api/courses/go
{"code":"java","title":"Java Programming","category":"backend","feeInr":4499,"seats":30}
{"code":"go","title":"Go Programming","category":"backend","feeInr":3299,"seats":24}
How it works:
- The PATCH body has no
seats, so the record component isnulland the old value of 30 stays. - Wrapper types (
Integer) are used inCoursePatchbecause a primitiveintcannot benulland would turn a missing field into0. - PUT with a mismatched code, such as body
"go"sent to/api/courses/java, hits theIllegalArgumentExceptionhandler and returns 400.
Add Pagination to a REST Endpoint
Large lists should be returned one page at a time. Replace the list method with a paged version that returns items plus totals.
package com.gocourse.api;
import java.util.List;
public record PageResponse<T>(List<T> items, int page, int size, long totalItems, int totalPages) {}
// replaces the earlier list(...) method in CourseController
@GetMapping
public PageResponse<Course> list(@RequestParam(required = false) String category,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
int pageSize = Math.clamp(size, 1, 100); // protect the server from size=1000000
int pageNumber = Math.max(page, 0);
List<Course> all = service.findAll(category);
int from = Math.min(pageNumber * pageSize, all.size());
int to = Math.min(from + pageSize, all.size());
int totalPages = (all.size() + pageSize - 1) / pageSize;
return new PageResponse<>(all.subList(from, to), pageNumber, pageSize, all.size(), totalPages);
}
curl -s -w "\n" "http://localhost:8080/api/courses?page=0&size=2"
curl -s -w "\n" "http://localhost:8080/api/courses?page=2&size=2"
{"items":[{"code":"go","title":"Go Language","category":"backend","feeInr":2999,"seats":20},{"code":"html","title":"HTML and CSS","category":"web","feeInr":1999,"seats":40}],"page":0,"size":2,"totalItems":5,"totalPages":3}
{"items":[{"code":"spring","title":"Spring Boot","category":"backend","feeInr":5999,"seats":2}],"page":2,"size":2,"totalItems":5,"totalPages":3}
How it works:
- Pages start at 0. Page 2 with size 2 skips four courses and returns the last one.
Math.clamp(Java 21+) keepssizebetween 1 and 100, so one request cannot ask for the whole database.- With a database, let Spring Data JPA do the slicing: accept a
Pageableparameter and returnrepository.findAll(pageable), which runslimitandoffsetin SQL.
Call a REST API From Java With RestClient
RestClient is Spring's synchronous HTTP client. It sends requests and converts JSON responses back into records.
package com.gocourse.api.client;
import com.gocourse.api.PageResponse;
import com.gocourse.api.course.Course;
import com.gocourse.api.course.CourseRequest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClient;
public class CourseApiClient {
public static void main(String[] args) {
RestClient client = RestClient.create("http://localhost:8080");
Course java = client.get()
.uri("/api/courses/{code}", "java")
.retrieve()
.body(Course.class);
System.out.println("Fetched: " + java);
PageResponse<Course> web = client.get()
.uri("/api/courses?category={category}", "web")
.retrieve()
.body(new ParameterizedTypeReference<PageResponse<Course>>() {});
System.out.println("Web titles: " + web.items().stream().map(Course::title).toList());
ResponseEntity<Course> created = client.post()
.uri("/api/courses")
.contentType(MediaType.APPLICATION_JSON)
.body(new CourseRequest("kotlin", "Kotlin Basics", "backend", 2999, 25))
.retrieve()
.toEntity(Course.class);
System.out.println("Created: " + created.getStatusCode() + " at " + created.getHeaders().getLocation());
try {
client.get().uri("/api/courses/{code}", "rust").retrieve().body(Course.class);
} catch (HttpClientErrorException.NotFound e) {
System.out.println("Not found: " + e.getResponseBodyAsString());
}
}
}
Fetched: Course[code=java, title=Java Programming, category=backend, feeInr=4999, seats=30]
Web titles: [HTML and CSS, React Basics]
Created: 201 CREATED at http://localhost:8080/api/courses/kotlin
Not found: {"status":404,"error":"Not Found","message":"Course rust not found","fields":{}}
How it works:
uri("/api/courses/{code}", "java")fills URI variables and encodes them safely, so you never build URLs by string concatenation.- A generic type like
PageResponse<Course>needs aParameterizedTypeReference, because Java erases generic types at runtime. retrieve()throwsHttpClientErrorExceptionfor 4xx answers andHttpServerErrorExceptionfor 5xx. Catching the specificNotFoundsubclass handles the missing course.
Real-World Example: Course Enrollment REST API
Enrollments belong to a course, so they use a nested resource URL: /api/courses/{code}/enrollments. The service checks seats and duplicates, and the error handler from earlier turns problems into 404, 409 or 400.
package com.gocourse.api.enrollment;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
public record EnrollmentRequest(@NotBlank @Email String email) {}
package com.gocourse.api.enrollment;
public record EnrollmentResponse(String courseCode, String email, int seatsLeft) {}
package com.gocourse.api.enrollment;
import com.gocourse.api.course.Course;
import com.gocourse.api.course.CoursePatch;
import com.gocourse.api.course.CourseService;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
@Service
public class EnrollmentService {
private final CourseService courses;
private final Map<String, Set<String>> studentsByCourse = new ConcurrentHashMap<>();
public EnrollmentService(CourseService courses) {
this.courses = courses;
}
// synchronized: two students must never take the last seat at the same time
public synchronized EnrollmentResponse enroll(String courseCode, String email) {
Course course = courses.get(courseCode); // 404 if unknown
Set<String> students = studentsByCourse.computeIfAbsent(courseCode, code -> new TreeSet<>());
if (students.contains(email)) {
throw new IllegalStateException(email + " is already enrolled in " + courseCode);
}
if (course.seats() == 0) {
throw new IllegalStateException(course.title() + " is full");
}
Course updated = courses.patch(courseCode, new CoursePatch(null, course.seats() - 1));
students.add(email);
return new EnrollmentResponse(courseCode, email, updated.seats());
}
public synchronized List<String> studentsOf(String courseCode) {
courses.get(courseCode);
return List.copyOf(studentsByCourse.getOrDefault(courseCode, Set.of()));
}
}
package com.gocourse.api.enrollment;
import jakarta.validation.Valid;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/courses/{code}/enrollments")
public class EnrollmentController {
private final EnrollmentService service;
public EnrollmentController(EnrollmentService service) {
this.service = service;
}
@PostMapping
public ResponseEntity<EnrollmentResponse> enroll(@PathVariable String code,
@Valid @RequestBody EnrollmentRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(service.enroll(code, request.email()));
}
@GetMapping
public List<String> students(@PathVariable String code) {
return service.studentsOf(code);
}
}
URL=http://localhost:8080/api/courses
enroll() { curl -s -w " [%{http_code}]\n" -X POST -H "Content-Type: application/json" -d "{\"email\":\"$2\"}" "$URL/$1/enrollments"; }
enroll spring asha@example.com
enroll spring asha@example.com
enroll spring ravi@example.com
enroll spring meena@example.com
enroll spring not-an-email
enroll rust asha@example.com
curl -s -w "\n" "$URL/spring/enrollments"
curl -s -w "\n" "$URL/spring"
{"courseCode":"spring","email":"asha@example.com","seatsLeft":1} [201]
{"status":409,"error":"Conflict","message":"asha@example.com is already enrolled in spring","fields":{}} [409]
{"courseCode":"spring","email":"ravi@example.com","seatsLeft":0} [201]
{"status":409,"error":"Conflict","message":"Spring Boot is full","fields":{}} [409]
{"status":400,"error":"Bad Request","message":"Validation failed","fields":{"email":"must be a well-formed email address"}} [400]
{"status":404,"error":"Not Found","message":"Course rust not found","fields":{}} [404]
["asha@example.com","ravi@example.com"]
{"code":"spring","title":"Spring Boot","category":"backend","feeInr":5999,"seats":0}
How it works:
- Nested URL.
{code}in the class-level@RequestMappingis shared by both methods, so each enrollment is clearly tied to one course. - One error format. The controller never builds error responses. Unknown courses, duplicates, full courses and bad emails all come out of
ApiErrorHandlerwith the same JSON shape and the right status code. - Consistent seat count.
synchronizedmakes the read-check-update sequence happen as one step, so two parallel requests can never both take the last seat. With a database you would use a transaction instead. - Reusing the course API. Seats are changed through
CourseService.patch, soGET /api/courses/springimmediately shows 0 seats. - Ready for real use. Swap the in-memory maps for repositories and protect the endpoints with Spring Security (for example, only logged-in students may enroll), and the controller code stays exactly the same.