Spring Boot REST API with DTOs, Validation and Exception Handling (Uptime Monitor Part 3)
Build clean Spring Boot CRUD endpoints with DTOs, Bean Validation, SSRF protection and global ProblemDetail error handling. Part 3 of the UpCheck series.
Part 3 of the UpCheck series builds the monitor CRUD API the clean way: controller, service and repository layers, DTOs, validation, SSRF protection and one global error handler.
- Part 1: Project setup with MySQL and Docker
- Part 2: Database design with Flyway and JPA
- Part 3: REST API, validation and error handling (you are here)
- Part 4: Spring Security with JWT
- Part 5: Scheduler with virtual threads
- Part 6: Incidents and email alerts
- Part 7: Uptime stats, pagination and retention
- Part 8: Testing, Docker and deployment
Spring Boot REST API with DTOs, validation and exception handling#
Today you build the monitor CRUD API the clean way: controller → service → repository, request and response DTOs, Bean Validation, and one global handler that returns every error in the same JSON shape.
The endpoints#
| Method | Path | What it does | Success |
|---|---|---|---|
| POST | /api/monitors | Create a monitor | 201 + Location header |
| GET | /api/monitors?page=0&size=20 | List my monitors | 200 |
| GET | /api/monitors/{id} | Get one monitor | 200 |
| PUT | /api/monitors/{id} | Update name, URL, interval, active | 200 |
| DELETE | /api/monitors/{id} | Delete with its history | 204 |
Step 1: Repository#
Ownership is part of every query. Another user's monitor id simply returns 404, so nobody can even learn that it exists.
package com.upcheck.monitor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface MonitorRepository extends JpaRepository<Monitor, Long> {
Page<Monitor> findAllByOwnerId(Long ownerId, Pageable pageable);
Optional<Monitor> findByIdAndOwnerId(Long id, Long ownerId);
long countByOwnerId(Long ownerId);
// Part 5 adds findDueMonitorIds and findCheckTargets here
}
Step 2: Request and response DTOs#
Never expose entities in the API. DTOs let you change the database without breaking clients, and they stop users from setting fields like status or owner themselves.
package com.upcheck.monitor;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.time.Instant;
import java.util.Set;
public final class MonitorDtos {
private static final Set<Integer> ALLOWED_INTERVALS = Set.of(1, 5, 15);
private MonitorDtos() {}
public record MonitorRequest(
@NotBlank @Size(max = 100) String name,
@NotBlank @Size(max = 2048)
@Pattern(regexp = "^https?://[^\\s/$.?#][^\\s]*$", message = "must be a valid http or https URL")
String url,
@NotNull Integer intervalMinutes,
Boolean active
) {
@JsonIgnore
@AssertTrue(message = "intervalMinutes must be 1, 5 or 15")
public boolean isIntervalAllowed() {
return intervalMinutes == null || ALLOWED_INTERVALS.contains(intervalMinutes);
}
public boolean activeOrDefault() {
return active == null || active;
}
}
public record MonitorResponse(Long id, String name, String url, int intervalMinutes,
boolean active, MonitorStatus status,
Instant lastCheckedAt, Instant createdAt) {
public static MonitorResponse from(Monitor m) {
return new MonitorResponse(m.getId(), m.getName(), m.getUrl(), m.getIntervalMinutes(),
m.isActive(), m.getStatus(), m.getLastCheckedAt(), m.getCreatedAt());
}
}
}
package com.upcheck.common;
import org.springframework.data.domain.Page;
import java.util.List;
/** Stable JSON shape for paged results (Spring's Page is not meant to be serialized directly). */
public record PageResponse<T>(List<T> content, int page, int size,
long totalElements, int totalPages, boolean last) {
public static <T> PageResponse<T> from(Page<T> page) {
return new PageResponse<>(page.getContent(), page.getNumber(), page.getSize(),
page.getTotalElements(), page.getTotalPages(), page.isLast());
}
}
Step 3: Block SSRF before it happens#
An uptime monitor makes HTTP calls to URLs that users type in. Without a guard, someone could add http://169.254.169.254/ and read your cloud server's secrets. This is called SSRF (server-side request forgery), and it is a real interview topic.
package com.upcheck.monitor;
import com.upcheck.common.exception.BusinessException;
import com.upcheck.config.AppProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
@Component
public class UrlSafetyValidator {
private final boolean allowPrivateHosts;
public UrlSafetyValidator(AppProperties props) {
this.allowPrivateHosts = props.checker().allowPrivateHosts();
}
public void assertSafe(String url) {
String host;
try {
host = URI.create(url).getHost();
} catch (IllegalArgumentException e) {
throw new BusinessException(HttpStatus.BAD_REQUEST, "URL is not valid");
}
if (host == null) {
throw new BusinessException(HttpStatus.BAD_REQUEST, "URL must contain a host name");
}
if (allowPrivateHosts) {
return;
}
try {
for (InetAddress address : InetAddress.getAllByName(host)) {
if (isInternal(address)) {
throw new BusinessException(HttpStatus.BAD_REQUEST,
"URL points to a private or local network address");
}
}
} catch (UnknownHostException e) {
throw new BusinessException(HttpStatus.BAD_REQUEST, "Host name could not be resolved: " + host);
}
}
private boolean isInternal(InetAddress a) {
return a.isLoopbackAddress() || a.isSiteLocalAddress() || a.isLinkLocalAddress()
|| a.isAnyLocalAddress() || a.isMulticastAddress();
}
}
Step 4: Service layer#
The service owns transactions and business rules: a monitor limit per user, the SSRF check, and ownership.
package com.upcheck.monitor;
import com.upcheck.common.PageResponse;
import com.upcheck.common.exception.BusinessException;
import com.upcheck.common.exception.ResourceNotFoundException;
import com.upcheck.config.AppProperties;
import com.upcheck.monitor.MonitorDtos.MonitorRequest;
import com.upcheck.monitor.MonitorDtos.MonitorResponse;
import com.upcheck.user.User;
import com.upcheck.user.UserRepository;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MonitorService {
private final MonitorRepository monitorRepository;
private final UserRepository userRepository;
private final UrlSafetyValidator urlSafetyValidator;
private final int maxMonitorsPerUser;
public MonitorService(MonitorRepository monitorRepository, UserRepository userRepository,
UrlSafetyValidator urlSafetyValidator, AppProperties props) {
this.monitorRepository = monitorRepository;
this.userRepository = userRepository;
this.urlSafetyValidator = urlSafetyValidator;
this.maxMonitorsPerUser = props.checker().maxMonitorsPerUser();
}
@Transactional
public MonitorResponse create(Long userId, MonitorRequest req) {
if (monitorRepository.countByOwnerId(userId) >= maxMonitorsPerUser) {
throw new BusinessException(HttpStatus.CONFLICT,
"Monitor limit reached (" + maxMonitorsPerUser + ")");
}
urlSafetyValidator.assertSafe(req.url());
User owner = userRepository.getReferenceById(userId); // no extra SELECT
Monitor monitor = new Monitor(owner, req.name().trim(), req.url().trim(), req.intervalMinutes());
if (!req.activeOrDefault()) {
monitor.update(monitor.getName(), monitor.getUrl(), monitor.getIntervalMinutes(), false);
}
return MonitorResponse.from(monitorRepository.save(monitor));
}
@Transactional(readOnly = true)
public PageResponse<MonitorResponse> list(Long userId, Pageable pageable) {
return PageResponse.from(
monitorRepository.findAllByOwnerId(userId, pageable).map(MonitorResponse::from));
}
@Transactional(readOnly = true)
public MonitorResponse get(Long userId, Long monitorId) {
return MonitorResponse.from(findOwned(userId, monitorId));
}
@Transactional
public MonitorResponse update(Long userId, Long monitorId, MonitorRequest req) {
Monitor monitor = findOwned(userId, monitorId);
if (!monitor.getUrl().equals(req.url().trim())) {
urlSafetyValidator.assertSafe(req.url());
}
monitor.update(req.name().trim(), req.url().trim(), req.intervalMinutes(), req.activeOrDefault());
return MonitorResponse.from(monitor); // dirty checking saves it on commit
}
@Transactional
public void delete(Long userId, Long monitorId) {
monitorRepository.delete(findOwned(userId, monitorId));
}
@Transactional(readOnly = true)
public Monitor findOwned(Long userId, Long monitorId) {
return monitorRepository.findByIdAndOwnerId(monitorId, userId)
.orElseThrow(() -> new ResourceNotFoundException("Monitor", monitorId));
}
}
Step 5: Controller#
@CurrentUser UserPrincipal gives us the logged-in user. Both small classes are in Part 4; write them now or tomorrow.
package com.upcheck.monitor;
import com.upcheck.common.PageResponse;
import com.upcheck.monitor.MonitorDtos.MonitorRequest;
import com.upcheck.monitor.MonitorDtos.MonitorResponse;
import com.upcheck.security.CurrentUser;
import com.upcheck.security.UserPrincipal;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
@Tag(name = "Monitors")
@RestController
@RequestMapping("/api/monitors")
public class MonitorController {
private final MonitorService monitorService;
public MonitorController(MonitorService monitorService) {
this.monitorService = monitorService;
}
@PostMapping
public ResponseEntity<MonitorResponse> create(@CurrentUser UserPrincipal user,
@Valid @RequestBody MonitorRequest request) {
MonitorResponse created = monitorService.create(user.id(), request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(created);
}
@GetMapping
public PageResponse<MonitorResponse> list(@CurrentUser UserPrincipal user,
@PageableDefault(size = 20, sort = "createdAt",
direction = Sort.Direction.DESC) Pageable pageable) {
return monitorService.list(user.id(), pageable);
}
@GetMapping("/{id}")
public MonitorResponse get(@CurrentUser UserPrincipal user, @PathVariable Long id) {
return monitorService.get(user.id(), id);
}
@PutMapping("/{id}")
public MonitorResponse update(@CurrentUser UserPrincipal user, @PathVariable Long id,
@Valid @RequestBody MonitorRequest request) {
return monitorService.update(user.id(), id, request);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@CurrentUser UserPrincipal user, @PathVariable Long id) {
monitorService.delete(user.id(), id);
}
}
Step 6: Global exception handling with ProblemDetail#
Spring Boot 3 supports RFC 9457 Problem Details out of the box. Every error leaves the API in one predictable shape, and the catch-all handler logs the real cause but never leaks stack traces or SQL.
package com.upcheck.common.exception;
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String resource, Object id) {
super(resource + " not found: " + id);
}
}
package com.upcheck.common.exception;
import org.springframework.http.HttpStatus;
/** A rule the request broke: duplicate email, monitor limit reached, unsafe URL. */
public class BusinessException extends RuntimeException {
private final HttpStatus status;
public BusinessException(HttpStatus status, String message) {
super(message);
this.status = status;
}
public HttpStatus getStatus() { return status; }
}
package com.upcheck.common.exception;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.net.URI;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(ResourceNotFoundException.class)
public ProblemDetail handleNotFound(ResourceNotFoundException ex, HttpServletRequest req) {
return problem(HttpStatus.NOT_FOUND, "Resource not found", ex.getMessage(), req);
}
@ExceptionHandler(BusinessException.class)
public ProblemDetail handleBusiness(BusinessException ex, HttpServletRequest req) {
return problem(ex.getStatus(), ex.getStatus().getReasonPhrase(), ex.getMessage(), req);
}
@ExceptionHandler(BadCredentialsException.class)
public ProblemDetail handleBadCredentials(BadCredentialsException ex, HttpServletRequest req) {
return problem(HttpStatus.UNAUTHORIZED, "Unauthorized", "Invalid email or password", req);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleValidation(MethodArgumentNotValidException ex, HttpServletRequest req) {
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.putIfAbsent(e.getField(), e.getDefaultMessage()));
ProblemDetail pd = problem(HttpStatus.BAD_REQUEST, "Validation failed",
"One or more fields are invalid", req);
pd.setProperty("errors", errors);
return pd;
}
@ExceptionHandler(PropertyReferenceException.class)
public ProblemDetail handleBadSort(PropertyReferenceException ex, HttpServletRequest req) {
return problem(HttpStatus.BAD_REQUEST, "Invalid sort field", ex.getMessage(), req);
}
@ExceptionHandler(ObjectOptimisticLockingFailureException.class)
public ProblemDetail handleConflict(ObjectOptimisticLockingFailureException ex, HttpServletRequest req) {
return problem(HttpStatus.CONFLICT, "Conflict",
"The monitor was updated at the same time. Please retry.", req);
}
@ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentTypeMismatchException.class})
public ProblemDetail handleBadInput(Exception ex, HttpServletRequest req) {
return problem(HttpStatus.BAD_REQUEST, "Malformed request",
"Request body or parameter has the wrong format", req);
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest req) {
log.error("Unhandled error on {} {}", req.getMethod(), req.getRequestURI(), ex);
return problem(HttpStatus.INTERNAL_SERVER_ERROR, "Internal error",
"Something went wrong. Please try again later.", req);
}
private ProblemDetail problem(HttpStatus status, String title, String detail, HttpServletRequest req) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(status, detail);
pd.setTitle(title);
pd.setInstance(URI.create(req.getRequestURI()));
pd.setProperty("timestamp", Instant.now());
return pd;
}
}
A validation error now looks like this:
{
"type": "about:blank",
"title": "Validation failed",
"status": 400,
"detail": "One or more fields are invalid",
"instance": "/api/monitors",
"timestamp": "2026-10-13T10:15:30Z",
"errors": {
"url": "must be a valid http or https URL",
"intervalAllowed": "intervalMinutes must be 1, 5 or 15"
}
}
./mvnw compile succeeds once the Part 4 classes UserPrincipal and CurrentUser exist. You will call these endpoints with a real token in the next part.
Key takeaways#
- Return DTOs, never entities, so clients cannot set fields like status or owner.
- Put the owner id in every repository query so other users' data returns 404.
- Use ProblemDetail in a @RestControllerAdvice so every error has the same JSON shape.