Skip to content
notes.vinhnq.com

Search

Web & APIMid23 min read

REST APIs: REST constraints, API design conventions and Spring Boot project structure

Review 21 cards
On this page

Web and REST APIs series: 1. The web and HTTP · 2. REST API design and Spring Boot

This post moves up from HTTP semantics (safe and idempotent methods, status codes, see part 1) to API design. Afterwards you can choose URLs, pagination, versioning, an error format and caching for a production API, pick between REST, gRPC and GraphQL, and lay out the layers of a Spring Boot project. The exercises at the end bootstrap the pet project.

1. Meet Spring Boot

Key idea: Spring Boot doesn’t replace Spring; it runs Spring underneath, configures itself from the libraries on the classpath, pins library versions and embeds a web server so java -jar is enough.

1.1. Library vs framework

  • Library: packaged, reusable code. You decide when to call it (Jackson, Guava, Apache Commons).
  • Framework: libraries plus rules you have to follow. The core difference is Inversion of Control: the framework calls your code. You write a @GetMapping method and Spring decides when to invoke it (“Don’t call us, we’ll call you”).

More on IoC in IoC and Dependency Injection.

1.2. Spring and Spring Boot

“Classic” Spring meant a lot of configuration: XML, declaring the DispatcherServlet and DataSource by hand, deploying a WAR to an external Tomcat, and picking library versions that happen to work together. Spring Boot removes that grind:

  • Auto-configuration: if a library is on the classpath and you haven’t defined the bean yourself, Boot creates it.
  • No more dependency conflicts: starters group dependencies by purpose, the BOM pins versions.
  • Embedded server: java -jar app.jar and you’re running.
  • Production readiness: Actuator for health checks and metrics.
Spring Boot underneath: what actually drives each feature
Feature What actually does it
Auto-configuration @AutoConfiguration classes guarded by @ConditionalOnClass, @ConditionalOnMissingBean and friends. If a library is on the classpath and you haven’t defined the bean yourself, Boot creates it
No more dependency conflicts Starters group dependencies by purpose, and the BOM (Bill of Materials, spring-boot-dependencies) pins versions of hundreds of libraries that are tested together
Embedded web server Tomcat (default), Jetty or Undertow inside an executable JAR
Production readiness Actuator: health checks, metrics, info

Debugging tip: run with --debug to print the condition evaluation report and see which auto-configurations kicked in and why. How auto-configuration is discovered and switched on, plus the startup lifecycle: Spring Boot from the inside.

2. REST

Key idea: REST is an architectural style, not a protocol: the system is a set of resources with URLs, and clients exchange representations (JSON) through standard HTTP methods. A production API also needs consistent URLs, pagination, versioning, error format and caching.

2.1. What is an API

An API (Application Programming Interface) is a contract between two pieces of software: how to call it (protocol, address), what to send, what comes back and how errors look. Think of a TV remote: you press a button without knowing the circuitry.

2.2. What is REST

REST (Representational State Transfer) is an architectural style described by Roy Fielding in 2000. The system is modelled as resources (data or functionality), each identified by a URL. Clients manipulate them by exchanging representations (JSON, XML…) through a small, uniform set of operations. The goals: simplicity, low overhead, scalability.

2.3. The six REST constraints

  1. Client-Server: separate the UI from storage and processing so each side evolves on its own.
  2. Stateless: each request carries everything the server needs (token, parameters); the server keeps no client session between requests. That lets you add instances behind a load balancer without sticky sessions (pinning a client to one instance).
  3. Cacheable: a response says whether it can be cached and for how long, e.g. Cache-Control: max-age=3600.
  4. Uniform Interface: every resource is accessed the same way: identified by a URI, manipulated through representations, with self-descriptive messages (method, content type, status) and HATEOAS (responses link to the next possible actions).
  5. Layered System: the client can’t tell whether it’s talking to the origin server or to a CDN, load balancer or API gateway in between.
  6. Code on Demand (the only optional constraint): the server may send code for the client to run, such as JavaScript.

“Stateless” is about conversation state; business state still lives in the database. It doesn’t force JWTs on you either: sessions kept in Redis scale horizontally too. The two are compared, with JWT pitfalls such as revocation and refresh tokens, in Authentication: session cookies and JWT.

Most “REST” APIs stop at level 2 of the Richardson Maturity Model; very few do HATEOAS. Say so in an interview.

Level What it means
0 One endpoint, everything over POST (RPC/SOAP style)
1 Multiple resources with their own URLs
2 Proper HTTP methods and status codes
3 Hypermedia (HATEOAS)

2.4. REST APIs and URL anatomy

A REST API is a set of endpoints (URLs) that applies REST over HTTP.

https://api.example.com:8443/api/v1/courses?category=java&page=0&size=20#reviews
\___/   \_____________/ \__/\_____________/ \___________________________/ \_____/
scheme      domain      port      path               query                fragment
  • Scheme: the protocol, http or https.
  • Domain (host): a name instead of an IP; DNS resolves it.
  • Port: omitted means 80 (http) or 443 (https).
  • Path: where the resource lives.
  • Query parameters: optional extras (filtering, sorting, pagination).

2.5. JSON

JSON is a text format for structured data (objects, arrays, strings, numbers, booleans, null). Alternatives: XML, YAML, or binary formats such as Protobuf and Avro. REST APIs usually declare JSON with Content-Type: application/json and Accept: application/json.

Dates and times need a convention too: instants as RFC 3339 strings in UTC ("2023-09-25T09:20:52.342Z"), plain dates as "2023-10-01", and never let Jackson turn a LocalDate into the array [2023,10,1]. Real Jackson output for each configuration, plus the traps when reading an OffsetDateTime, is in Storing dates and times in PostgreSQL, MySQL and JSON.

2.6. URL conventions

  • Nouns, not verbs: the HTTP method is already the verb. POST /orders, not POST /createOrder.
  • Plural nouns: /users, /users/34. The collection and its items share one root.
  • Version it: /api/v1/....
  • kebab-case in paths (the slides call it “slug-case”): /course-categories. URLs can be case-sensitive, so lowercase with hyphens is safest.
  • snake_case in JSON bodies: the course’s convention, not a REST rule. Google and many Java shops use camelCase; Stripe and GitHub use snake_case. What matters is consistency across the whole system. Jackson: spring.jackson.property-naming-strategy=SNAKE_CASE.

A non-CRUD action becomes a sub-resource: POST /v1/orders/145/cancel. For sorting, use sort=price,-name, not +price.

URL examples and two bugs in the slides’ sort example
Action Request
Create an order POST /order-service/v1/orders
Get order 145 GET /order-service/v1/orders/145
Update only the age of user 34 PATCH /user-service/v1/users/34
Disable user 34 DELETE /user-service/v1/users/34
Courses taught by teacher 7 GET /v1/teachers/7/courses
A non-CRUD action POST /v1/orders/145/cancel or POST /v1/orders/145/cancellation

2.7. Pagination

Advanced REST API design takes this further at scale: the conditions a cursor needs to be correct and tamper-proof, the deferred join for when you must use OFFSET, whitelisting sort fields, and a strict definition of safe and idempotent for each method.

2.8. Versioning

2.9. A consistent error format

Don’t let every controller invent its own error shape. RFC 9457 Problem Details (which replaces RFC 7807) defines an error body served as Content-Type: application/problem+json:

{
  "type": "https://api.example.com/problems/course-full",
  "title": "Course is full",
  "status": 409,
  "detail": "Course 42 has reached its maximum of 100 students",
  "instance": "/v1/courses/42/enrollments",
  "trace_id": "a1b2c3d4"
}

Spring 6+ ships ProblemDetail and ErrorResponseException:

@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(CourseFullException.class)
    ProblemDetail handleCourseFull(CourseFullException ex) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
        pd.setTitle("Course is full");
        pd.setType(URI.create("https://api.example.com/problems/course-full"));
        return pd;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail handleValidation(MethodArgumentNotValidException ex) {
        ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        pd.setTitle("Validation failed");
        pd.setProperty("errors", ex.getFieldErrors().stream()
                .map(e -> Map.of("field", e.getField(), "message", e.getDefaultMessage()))
                .toList());
        return pd;
    }
}

Never put stack traces or SQL in a response; that’s free reconnaissance for an attacker. Log the details server-side and return a trace_id to look them up.

2.10. Caching with HTTP headers

  • Cache-Control: max-age=3600: may be cached for 3600 seconds.
  • no-cache: may be stored but must be revalidated with the server before use. no-store: must not be stored at all (sensitive data).
  • private (browser only) vs public (CDNs and proxies too). Anything user-specific must be private or no-store.
  • ETag + If-None-Match: an ETag is a “version number” for a response. The server sends ETag: "v7", next time the client sends If-None-Match: "v7"; if nothing changed, the server answers 304 Not Modified with no body.
  • ETag + If-Match for writes: the client sends a PUT with If-Match: "v7"; if someone else already moved it to v8, the server answers 412 Precondition Failed. That’s optimistic locking over HTTP, and it maps onto JPA’s @Version (see ORM and JPA).
@GetMapping("/v1/courses/{id}")
ResponseEntity<CourseResponse> get(@PathVariable long id) {
    CourseResponse course = courseService.get(id);
    return ResponseEntity.ok()
            .eTag(String.valueOf(course.version()))
            .cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePrivate())
            .body(course);
}

3. REST vs SOAP, gRPC and GraphQL

Key idea: REST for public APIs and frontends; gRPC for internal services that need speed; GraphQL when many client types need different data; SOAP when you’re forced to integrate with a legacy system.

  • SOAP: an XML messaging protocol with strict standards (WSDL); heavy, and hard to cache because everything is POST.
  • gRPC: RPC over HTTP/2 with Protobuf (binary) and bidirectional streaming, but browsers need gRPC-Web or a proxy.
  • GraphQL: one endpoint where clients pick their fields, avoiding over/under-fetching (getting too much or too little data), but hard to cache and prone to N+1 in resolvers.
Full comparison table: REST, SOAP, gRPC, GraphQL
REST SOAP gRPC GraphQL
What it is Architectural style over HTTP XML messaging protocol with strict standards (WSDL, WS-Security) RPC over HTTP/2 with Protobuf Query language, single endpoint
Format JSON (usually) XML Binary (Protobuf) JSON
Contract OpenAPI (optional) WSDL (required) .proto files (required), code generation Typed schema (required)
Performance Good Heavy (verbose XML) Excellent, bidirectional streaming Good, but complex queries can be expensive
HTTP caching Easy (GET + URL) Hard (everything is POST) Hard Hard (usually POST to one endpoint)
Callable from a browser Yes Yes, but clunky Needs gRPC-Web/a proxy Yes
Strengths Simple, ubiquitous, great tooling Enterprise and banking integrations, legacy systems Internal service-to-service calls, low latency Clients pick fields, fetch many resources at once, no over/under-fetching
Weaknesses Over-fetching, many round trips Complex, heavyweight Hard to eyeball-debug, needs HTTP/2 N+1 in resolvers, hard to rate-limit and cache, query depth/complexity attacks

4. Spring Boot project structure

Key idea: split controller → service → repository, one job per layer, and expose only DTOs. As the project grows, consider packaging by feature and enforcing dependency rules with a tool.

4.1. Layers

flowchart LR
  C[Client] -->|HTTP + JSON| CT[Controller]
  CT -->|DTO| SV[Service]
  SV -->|Entity| RP[Repository]
  RP -->|SQL| DB[(Database)]
  • Controller: receives requests, validates input, calls the service, returns the response. No business logic.
  • DTO (Data Transfer Object): carries data between layers and to the outside world. Java 17+ records keep DTOs compact.
  • Service: business logic, transaction boundaries (@Transactional).
  • Repository: queries and data manipulation.
  • Entity: a class mapped to a table.

Don’t return entities directly: you’d leak sensitive fields (password hashes), hit lazy-loading errors and infinite loops when serializing bidirectional relationships, and tie your API to the database schema.

4.2. Supporting packages

Besides the main layers there are model, util, constant, exception, config and filter.

What goes in each supporting package
Package What goes in it
model Domain classes that are neither entities nor DTOs: calculation results, input objects for services
util Stateless helpers (dates, strings…)
constant Enums and constants
exception Custom exceptions and a @RestControllerAdvice for central error handling
config @Configuration classes and beans that belong to no layer (Jackson, CORS, security, HTTP clients)
filter Servlet filters: request logging, trace ids, authentication

Exercises

The exercises revolve around the course’s pet project: an online-course (E-Learning) platform. Going by the schema from the practice session, it has learners (user), teachers and admins (two separate tables), courses → chapters → lessons (typed VIDEO/PDF/DOCX/SLIDE, ordered), enrolments with a rating and review, and per-lesson progress (START/PROCESSING/DONE). The full schema and its queries are in SQL exercises on the E-Learning database.

Don’t mix it up: the Backend practice series analyses a hotel booking system, the instructor’s worked example of going from requirements to data and API design. Below I apply the same method to E-Learning.

Exercise 1: Bootstrap a Spring Boot project with a “hello” API

Task (paraphrased): create a Spring Boot project for the pet project, push it to Git, and add an endpoint that returns a welcome string for the online-course project.

Solution to exercise 1: Spring Initializr, HelloController and pushing to Git

Generate the project with Spring Initializr (Java 21, Spring Web):

curl https://start.spring.io/starter.zip \
  -d type=maven-project -d javaVersion=21 \
  -d groupId=com.vinhnq -d artifactId=elearning \
  -d dependencies=web,validation,actuator \
  -o elearning.zip && unzip elearning.zip -d elearning
package com.vinhnq.elearning.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello from the e-learning project";
    }
}
./mvnw spring-boot:run
curl -i http://localhost:8080/api/v1/hello

git init && git add . && git commit -m "Bootstrap the e-learning service"
git remote add origin git@github.com:<user>/elearning.git
git push -u origin main

@RestController is @Controller + @ResponseBody, so the return value is written straight into the response body (a String as text/plain, an object as JSON via Jackson). Check that .gitignore excludes target/ and any config file holding passwords.

Exercise 2: Define every URL of the pet project and echo the input

Task (paraphrased): define all the REST endpoints from the pet project’s features. No real logic yet: each endpoint returns the body or parameters it received, or null if there are none. The point is to lock down the API contract before writing business code.

Two decisions worth remembering: progress and reviews use PUT (idempotent, so retries can’t create duplicates), and the /me/... routes take the learner from the token instead of a user_id in the URL.

Solution to exercise 2: the E-Learning endpoint table and an echo controller

Endpoints follow the tables in the schema (teachers, courses, chapters, lessons, enrolments, progress, reviews):

Feature Endpoint
Search, filter and page courses GET /api/v1/courses?keyword=&teacher_id=&status=ACTIVE&page=0&size=20&sort=created_date:desc
Course details GET /api/v1/courses/{course_id}
Create a course POST /api/v1/courses
Full update PUT /api/v1/courses/{course_id}
Partial update PATCH /api/v1/courses/{course_id}
Delete DELETE /api/v1/courses/{course_id}
Courses of a teacher GET /api/v1/teachers/{teacher_id}/courses
Enroll a student POST /api/v1/courses/{course_id}/enrollments
List a course’s chapters (in order) GET /api/v1/courses/{course_id}/chapters
Add a chapter POST /api/v1/courses/{course_id}/chapters
Lessons in a chapter GET /api/v1/chapters/{chapter_id}/lessons
Add a lesson (type: VIDEO, PDF, DOCX, SLIDE) POST /api/v1/chapters/{chapter_id}/lessons
My enrolments, filtered by progress GET /api/v1/me/enrollments?status=PROCESSING
Update progress on a lesson ({"status": "DONE"}) PUT /api/v1/me/courses/{course_id}/lessons/{lesson_id}/progress
Rate and review a course ({"rating": 5, "review": "..."}) PUT /api/v1/me/courses/{course_id}/review
Admin locks a learner’s account ({"status": "INACTIVE"}) PATCH /api/v1/users/{user_id}
Manage teachers (a separate table, not a role) GET/POST /api/v1/teachers, GET/PATCH /api/v1/teachers/{teacher_id}

Progress and reviews use PUT because each enrolment has exactly one progress record per lesson and one review. The client sends the desired state, and sending it again gives the same result (idempotent), so a mobile app retrying on a flaky network can’t create duplicates. The /me/... routes take the learner from the login token, so nobody can edit someone else’s progress by changing an id.

By contrast, POST /api/v1/chapters/{chapter_id}/lessons (add a lesson) or a payment API is not idempotent: an app that retries after losing the response creates another record. The standard fix is for the client to send an Idempotency-Key header and for the server to rely on a unique constraint to return the result of the first attempt; an implementation tested on PostgreSQL is in Idempotency part 1.

public record CourseRequest(
        @NotBlank @Size(max = 255) String name,
        @Size(max = 1000) String description,
        @NotNull Long teacherId) {}

public record CourseSearchParams(String keyword, Long teacherId, String status,
                                 Integer page, Integer size, String sort) {}

@RestController
@RequestMapping("/api/v1/courses")
public class CourseController {

    @GetMapping
    public CourseSearchParams search(CourseSearchParams params) {
        return params; // Spring binds query parameters into the record
    }

    @GetMapping("/{courseId}")
    public Map<String, Object> detail(@PathVariable long courseId) {
        return Map.of("course_id", courseId);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public CourseRequest create(@Valid @RequestBody CourseRequest body) {
        return body;
    }

    @PutMapping("/{courseId}")
    public CourseRequest replace(@PathVariable long courseId, @Valid @RequestBody CourseRequest body) {
        return body;
    }

    @PatchMapping("/{courseId}")
    public Map<String, Object> patch(@PathVariable long courseId, @RequestBody Map<String, Object> changes) {
        return changes;
    }

    @DeleteMapping("/{courseId}")
    public Object delete(@PathVariable long courseId) {
        return null; // no body: Spring sends an empty 200; the real version should return 204
    }
}

Exercise 3: Push an empty folder structure with .gitkeep

Task (paraphrased): create the project’s packages up front (controller, dto, service, repository, entity, config…) and push them to Git before they contain any code.

Solution to exercise 3: a script for the packages and .gitkeep files
BASE=src/main/java/com/vinhnq/elearning
for p in controller dto service repository entity model util constant exception config filter; do
  mkdir -p "$BASE/$p" && touch "$BASE/$p/.gitkeep"
done
git add . && git commit -m "Add the package skeleton" && git push

Delete the .gitkeep once a package has real Java files in it.

Remember

  • Explain what Spring Boot adds to Spring, and how to see which auto-configurations were applied.
  • Name the six REST constraints and why “stateless” doesn’t mean the app has no database.
  • Know when to use offset vs cursor pagination, and write the keyset SQL.
  • Tell a compatible change from a breaking one, and how to retire an old version.
  • Explain no-cache vs no-store, and how an ETag serves both 304s and optimistic locking.

Interview questions

Junior

Why shouldn’t you return entities directly from an API?

Because an entity is the persistence model, not the API contract: exposing it leaks data and ties clients to the database schema.

Concretely: you leak sensitive fields, you hit lazy-loading errors or infinite recursion when Jackson serializes bidirectional relationships, and every schema change becomes a breaking API change. DTOs decouple the API contract from the persistence model.

How is Spring Boot different from the Spring Framework?

Spring Boot doesn’t replace Spring; it runs Spring underneath with sensible defaults.

It adds auto-configuration (beans created based on what’s on the classpath, only if you haven’t declared your own), starters plus a BOM that pins compatible versions, an embedded server so java -jar is enough, and Actuator for health checks and metrics. You can still override every default; run with --debug to see which auto-configurations were applied and why.

Mid

What does “stateless” mean in REST? Is an app with a database still stateless?

Yes. Stateless refers to conversation state: the server keeps no client session between requests; business state still lives in the database.

Each request carries everything needed (a JWT, for example). The payoff is easy horizontal scaling: any instance can handle any request, no sticky sessions required.

What’s wrong with offset pagination, and what’s the alternative?

Deep pages are slow and changing data causes duplicates or gaps; the alternative is keyset (cursor) pagination.

OFFSET n forces the database to read and discard n rows. Keyset filters on the last values of the previous page (WHERE (created_at, id) < (?, ?)) with a matching index. Performance is stable, but you can’t jump to an arbitrary page.

How do no-cache and no-store differ? What is an ETag for?

no-cache allows storing but requires revalidation before use; no-store forbids storing. An ETag is a version tag for a representation.

With If-None-Match the server can answer 304 when nothing changed, and with If-Match the ETag provides optimistic concurrency control (412 if someone else changed it first).

Senior

How would you version an API and manage breaking changes?

URI versioning (/v1) by default, but what really matters is the compatibility policy and how you retire old versions.

  • URI versioning is obvious and easy to route and cache.
  • Additive changes (new fields or endpoints) don’t bump the version, and clients must ignore unknown fields. Renaming, removing, retyping or changing meaning is breaking and needs a new version.
  • Run both versions side by side for a while, announce retirement with Deprecation/Sunset, and watch traffic on the old version before switching it off.
  • Contract tests in CI (OpenAPI diff, consumer-driven contracts) catch breaking changes early.
When would you choose gRPC or GraphQL over REST?

gRPC for internal calls that need low latency and strict contracts; GraphQL when many client types need different data. REST stays the default for public APIs.

  • gRPC: small payloads, streaming; the cost is harder debugging and no direct browser calls.
  • GraphQL: fewer round trips; the cost is weak HTTP caching, fighting N+1 in resolvers (DataLoader) and limiting query depth and complexity.
  • REST: simple, cache-friendly, great tooling.
How would you design the error format for a system of many services?

Pick one standard such as RFC 9457 Problem Details and ship it as a shared library or enforce it at the API gateway so every service is consistent.

  • Fields: type (a stable URI identifying the error kind that clients can switch on), title, status, detail, instance, plus extensions like errors for validation and a trace_id to find the logs.
  • Status codes must carry the right semantics so retries and monitoring work.
  • Never expose stack traces, SQL or internal class names.
A heavily used GET endpoint is slow. How do you approach it?

Measure first (APM, slow query log), then work from the query up to caching, and make every cache layer answer “how stale is acceptable?”.

  • Fix queries and indexes, remove N+1.
  • HTTP caching (Cache-Control, ETag/304, a CDN for public data).
  • An application cache (Caffeine, Redis) with a clear invalidation strategy.
  • Smaller payloads (pagination, field selection, gzip/br); HTTP/2 and keep-alive.
  • Protect the system with rate limits and timeouts.

Useful phrases for interviews

  • “Strictly speaking, most APIs we call RESTful are level 2 on the Richardson model; we rarely use hypermedia.”
  • “Offset pagination falls apart on deep pages, so for the feed we switched to keyset pagination.”
  • “Adding an optional field is backward compatible; renaming one is a breaking change, so that would go into v2.”
  • “We standardised on Problem Details so every service returns errors in the same shape.”
  • “The trade-off with GraphQL is that you give up simple HTTP caching in exchange for flexible queries.”
  • “Spring Boot’s auto-configuration only kicks in when the library is on the classpath and I haven’t defined that bean myself.”
  • “I never expose JPA entities directly; the API contract lives in DTOs, so the schema can evolve freely.”
  • “The ETag doubles as a version for optimistic locking: if the If-Match value is stale, the server answers 412.”

Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.