In this tutorial
Spring Boot is the most popular way to build back-end services in Java, and a REST API is the first thing most developers build with it. In this tutorial you will create a small but properly structured API for managing courses, with validation, correct status codes and clean error responses.
You need Java 17 or newer and an IDE such as IntelliJ IDEA. Maven is used for the build.
Step 1: Create the project
Go to start.spring.io and choose:
- Project: Maven
- Language: Java
- Spring Boot: the latest stable 3.x version
- Group:
com.kooredev, Artifact:courses - Java: 17 or 21
- Dependencies: Spring Web, Validation
Click Generate, unzip the project and open it in your IDE. The important part of pom.xml looks like this:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
The generated main class starts an embedded Tomcat server:
package com.kooredev.courses;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CoursesApplication {
public static void main(String[] args) {
SpringApplication.run(CoursesApplication.class, args);
}
}
Step 2: Model the data
A course has an id, a code, a title and a number of units. Java records are ideal for this:
package com.kooredev.courses;
public record Course(Long id, String code, String title, int units) { }
For incoming requests we use a separate record with validation rules. Clients should not choose the id; the server does.
package com.kooredev.courses;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
public record CourseRequest(
@NotBlank @Pattern(regexp = "[A-Z]{3}\\d{3}", message = "must look like CSC201") String code,
@NotBlank String title,
@Min(1) @Max(6) int units
) { }
Step 3: Write the service
The service holds the business logic. To keep this tutorial focused we store courses in memory with a ConcurrentHashMap; in a real project you would use Spring Data JPA and a database.
package com.kooredev.courses;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@Service
public class CourseService {
private final Map<Long, Course> courses = new ConcurrentHashMap<>();
private final AtomicLong nextId = new AtomicLong(1);
public List<Course> findAll() {
return courses.values().stream()
.sorted(Comparator.comparing(Course::id))
.toList();
}
public Optional<Course> findById(Long id) {
return Optional.ofNullable(courses.get(id));
}
public Course create(CourseRequest req) {
long id = nextId.getAndIncrement();
Course course = new Course(id, req.code(), req.title(), req.units());
courses.put(id, course);
return course;
}
public Optional<Course> update(Long id, CourseRequest req) {
if (!courses.containsKey(id)) {
return Optional.empty();
}
Course updated = new Course(id, req.code(), req.title(), req.units());
courses.put(id, updated);
return Optional.of(updated);
}
public boolean delete(Long id) {
return courses.remove(id) != null;
}
}
@Service tells Spring to create one instance of this class and make it available for injection.
Step 4: Write the controller
The controller maps HTTP requests to service calls:
package com.kooredev.courses;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/api/courses")
public class CourseController {
private final CourseService service;
public CourseController(CourseService service) { // constructor injection
this.service = service;
}
@GetMapping
public List<Course> all() {
return service.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Course> one(@PathVariable Long id) {
return service.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<Course> create(@Valid @RequestBody CourseRequest req) {
Course created = service.create(req);
return ResponseEntity.created(URI.create("/api/courses/" + created.id())).body(created);
}
@PutMapping("/{id}")
public ResponseEntity<Course> update(@PathVariable Long id, @Valid @RequestBody CourseRequest req) {
return service.update(id, req)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
return service.delete(id)
? ResponseEntity.noContent().build()
: ResponseEntity.notFound().build();
}
}
What each piece does:
@RestController: every method’s return value is written to the response body as JSON.@RequestMapping("/api/courses"): the base path for all endpoints in this class.@GetMapping,@PostMapping,@PutMapping,@DeleteMapping: map HTTP methods.@PathVariable: reads{id}from the URL.@RequestBody: converts the JSON body into aCourseRequest.@Valid: runs the validation annotations before the method is called.- Constructor injection: Spring passes the
CourseServicein automatically. No@Autowiredis needed with a single constructor.
Step 5: Return clean validation errors
If validation fails, Spring throws a MethodArgumentNotValidException. By default the response is not very friendly, so add a global handler:
package com.kooredev.courses;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
import java.util.TreeMap;
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new TreeMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(err -> errors.put(err.getField(), err.getDefaultMessage()));
return errors;
}
}
Step 6: Run and test it
Start the application from your IDE, or run:
./mvnw spring-boot:run
Then try the endpoints with curl (or Postman):
# Create a course -> 201 Created
curl -i -X POST localhost:8080/api/courses \
-H "Content-Type: application/json" \
-d '{"code":"CSC201","title":"Object-Oriented Programming","units":3}'
# List all courses -> 200 OK
curl localhost:8080/api/courses
# Get one -> 200 OK, or 404 if it does not exist
curl -i localhost:8080/api/courses/1
# Invalid input -> 400 Bad Request with field errors
curl -i -X POST localhost:8080/api/courses \
-H "Content-Type: application/json" \
-d '{"code":"csc","title":"","units":9}'
# Delete -> 204 No Content
curl -i -X DELETE localhost:8080/api/courses/1
The invalid request returns:
{"code":"must look like CSC201","title":"must not be blank","units":"must be less than or equal to 6"}
REST conventions we followed
- Nouns in URLs, verbs as HTTP methods:
POST /api/courses, not/api/createCourse. - Correct status codes:
200 OK,201 Createdwith aLocationheader,204 No Contentafter delete,400 Bad Requestfor validation errors,404 Not Foundfor missing resources. - Separate request and response models, so clients cannot set server-controlled fields such as
id. - Thin controllers, logic in services. This makes the service easy to unit test and reuse.
Where to go next
- Replace the in-memory map with Spring Data JPA and a database such as PostgreSQL or MySQL.
- Write tests with
@WebMvcTestandMockMvc. - Add API documentation with springdoc-openapi (Swagger UI).
- Secure the endpoints with Spring Security.
Summary
- Spring Initializr gives you a runnable project in seconds.
- Records make concise request and response models; Bean Validation annotations guard your input.
@RestControllerplus mapping annotations turn methods into HTTP endpoints.- Return proper status codes with
ResponseEntity, and handle errors centrally with@RestControllerAdvice.