ARTICLE - Dev Stack & Tools

Spring Boot REST APIs: Layers, Validation and Security

Spring Boot reduces setup work, but it does not define the API contract. Controller boundaries, request validation, error responses and authentication rules still need explicit design and tests for both success and failure paths.

2026-08-06 Spring official documentation 64 views
Advertisement

Returning JSON does not yet give an API a stable client contract. Define the status for a successful create, how invalid input is reported, and whether an unauthenticated request is allowed. This guide uses the Spring Boot 4.2.0 reference documentation as its version boundary; its system requirements specify Java 17 or later. Check dependencies and APIs against the Spring Boot version pinned by your project.

Spring MVC request flow HTTP request Security filters Bind and validate Controller Service and data HTTP response Authentication failure stops here Validation can stop handler invocation Typical Servlet MVC sequence; security and data behavior depend on application configuration
Figure 1: Spring MVC request flow (basis: typical Servlet MVC sequence)

Organize the API by responsibility

Separate HTTP handling, business rules and persistence so failures are easier to locate and tests do not need to start the entire application each time.

Layer Main responsibility Avoid making it responsible for
Controller Routing, DTO input, validation trigger and HTTP response Complex business rules or SQL construction
Service Business decisions, transaction boundary and use-case orchestration Expressing business logic through HTTP request objects
Repository / DAO Queries and persistence Choosing API error formats or exposing raw database errors

Generate a project skeleton with Spring Initializr, then add Spring MVC, Bean Validation, data-access and test dependencies as needed. Do not assume JPA is mandatory just because an endpoint reads or writes data: Spring Data JPA can fit entity relationships and common CRUD, while JDBC may fit workloads where explicit SQL control is important. Align dependencies with the project's Boot version.

Define request, response and validation contracts

Accept a dedicated request DTO instead of binding a database entity directly. The snippet assumes that ItemService and ItemView are defined elsewhere in the application; @Valid triggers Bean Validation constraints on the request object.

@RestController
@RequestMapping("/api/items")
class ItemController {
    private final ItemService items;

    ItemController(ItemService items) {
        this.items = items;
    }

    @PostMapping
    ResponseEntity<ItemView> create(@Valid @RequestBody CreateItemRequest request) {
        ItemView created = items.create(request);
        URI location = URI.create("/api/items/" + created.id());
        return ResponseEntity.created(location).body(created);
    }
}

record CreateItemRequest(@NotBlank String name) {}

What to verify: with MVC, a validation implementation and the service configured, a valid POST should return 201 Created, a resource location and a response body. A missing or blank name should fail validation before the business method runs. Use MockMvc to assert the status and JSON fields so routing, binding and validation are checked without a browser.

Distinguish validation of a request object annotated with @RequestBody @Valid from constraints placed directly on method parameters. The Spring MVC validation reference explains that individual object validation and method validation can raise different exceptions depending on the signature and constraint location. Spring Framework 6.1 and later provide built-in MVC method validation. A class-level @Validated on a controller instead routes method validation through an AOP proxy. Handle the validation exceptions actually used by the application rather than assuming every validation failure has one exception type.

Standardize error statuses and response bodies

Choose HTTP statuses that tell the client what it can do, then define the error-body fields. A missing resource commonly maps to 404 and invalid input to 400; error responses should not expose stack traces, SQL, tokens or internal hostnames. Use @RestControllerAdvice to map business exceptions centrally and pin the response shape with MockMvc tests instead of letting each controller invent a format.

Case Common HTTP status What to verify
Resource created 201 Body has a resource identifier; Location identifies the new resource
Request violates constraints 400 Error identifies a correctable field without internal details
Resource does not exist 404 Client can distinguish absence from server failure
Unauthenticated / unauthorized 401 / 403 Distinguish missing valid identity from insufficient permission
Unexpected server failure 500 Client receives a generic error identifier; details stay in controlled logs

Spring Framework error handling can raise different exceptions depending on where validation occurs. Map client errors, business rejections and unexpected failures separately, and test each response. Converting every exception into 200 or one generic business code makes APIs harder to maintain.

Match the security chain to the API

When Spring Security is on the classpath, Spring Boot secures web applications by default; the generated user credentials are for development, and the generated password is printed at startup. Define your own SecurityFilterChain with explicit rules for public paths, authenticated paths and the authentication mechanism. This minimal HTTP Basic example illustrates authorization rules, not a complete production identity system:

@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/actuator/health").permitAll()
            .requestMatchers("/api/**").authenticated()
            .anyRequest().denyAll())
        .httpBasic(Customizer.withDefaults())
        .build();
}

What to verify: if Actuator is included and the health endpoint is exposed, that path should follow its permit rule; an unauthenticated request to /api/** should be rejected, and an authenticated request should reach the controller. Verify both cases with MockMvc. Production also requires a deliberate choice of transport encryption, credential management, CSRF exposure and business authorization. A JWT resource server must be configured with a trusted issuer; adding Security alone does not configure JWT validation.

Test and verify the running application

Start with slice tests: @WebMvcTest focuses on MVC routing, serialization and error statuses, with dependencies supplied by test doubles; @DataJpaTest checks repository behavior; use @SpringBootTest or integration tests when component wiring and the database must be tested together. A slice does not guarantee that no infrastructure is contacted or that it is always faster; that depends on the test configuration and loaded auto-configuration.

For a Maven project generated with the Spring Initializr wrapper, run:

./mvnw test

What to verify: the test report's test, failure and error counts should match the project's expectations. On failure, inspect the assertion and application-context output; a successful build process alone does not prove that a particular endpoint passed its acceptance criteria. Cover at least one successful request, one validation failure, one not-found case, and authenticated and unauthenticated requests to a protected endpoint.

Limitations

  • Version guidance follows the Spring Boot 4.2.0 documentation checked on 2026-11-28; starter names, test annotations and framework behavior can differ in older releases.
  • Examples use Servlet Spring MVC. WebFlux has a different request-processing and security stack and cannot be substituted mechanically.
  • The HTTP Basic snippet shows access rules and one authentication mechanism; it does not provide production user storage, token issuance, role design or secret management.
  • JPA, schema migrations, pagination, rate limiting, idempotency keys and OpenAPI contracts are not covered; select and verify them for the actual application.

FAQ

Why does a new Spring Boot API return 401 after adding Spring Security?

Spring Security protects web apps by default. In this HTTP Basic example, missing API credentials return 401. Check for a custom SecurityFilterChain and confirm that public routes match exactly; do not disable security globally just to troubleshoot. The generated user and password are for development. Production needs an explicit authentication scheme and separate tests for unauthenticated, authenticated and forbidden requests.

Why did @Valid not check a constraint on my path variable?

Validation depends on the parameter and Spring version. @Valid commonly cascades validation into request-body objects; it is not itself a method constraint. A constraint on a path variable triggers method validation, and the exception and validation path depend on the Spring Framework version and controller annotations. Check the version-specific reference and write separate MockMvc tests for invalid path parameters and request bodies.

Spring Boot and JPA vs JDBC: which data layer should I choose?

Use JPA when entity relationships, object lifecycle and common CRUD dominate; consider JDBC when explicit SQL and query control matter more. Neither choice guarantees performance, which must be tested with real queries, indexes, transactions and data volumes. With JPA, manage production schema changes through migrations and verify their order in the deployment environment.

What production checks are outside the scope of @WebMvcTest?

No. It mainly checks mappings, binding, serialization and security behavior in the MVC slice; it does not cover every service, database, external API or deployment condition. Add repository and integration tests, then verify connections, migrations and authentication in the target environment. A passing slice only confirms the behavior covered by its assertions.

Related Providers

  • PostgreSQL: when PostgreSQL is the relational database, check the JDBC driver, connection settings and migration compatibility.
  • Flyway: when schema changes need versioned migrations deployed with the application, evaluate Flyway.
  • Docker: when packaging the application as an image to align build and runtime environments, consult the Docker resources.

References

Community & Resources

Continue with the Backend Integration category. For third-party interfaces, see Website API Integration Basics and API Authentication and JWT.

Original source: Spring official documentation ↗