Skip to content
Visual explainer 8h to learn 6 steps

REST APIs with Spring MVC

Design and build a REST API with proper status codes and DTOs.

By Invicly Tech, , in Backend Java Development. About 11 minutes to read.

Topic 17 of 29

In short

Spring MVC maps HTTP requests to controller methods and converts Java objects to JSON. A clean API uses resource URLs, the right HTTP methods and status codes, and DTOs instead of entities.

Explained simply

A REST API lets other programs, such as a mobile app or a React website, talk to your backend over HTTP. Each thing your system manages, like a book or an order, is a resource with its own URL, such as /api/books/42.

HTTP methods say what to do with a resource. GET reads it, POST creates a new one, PUT replaces it, PATCH changes part of it, and DELETE removes it. Status codes in the response say how it went: 200 for OK, 201 for created, 404 for not found, and so on.

In Spring, a controller class handles these requests. You annotate a method with @GetMapping("/{id}"), and Spring calls it for matching requests, turns the JSON body into a Java object, and turns your return value back into JSON.

A good API is predictable. Clients should be able to guess URLs, rely on status codes, and get the same JSON shapes every time. DTOs (data transfer objects) help here: they are small classes shaped for the API, separate from your database entities, so you control exactly what goes in and out.

Press Play on a diagram to walk through it one step at a time.

FlowSpring MVC request handling
  1. 1
    HTTP request

    POST /api/books with a JSON body

  2. 2
    DispatcherServlet

    Front controller receives every request

  3. 3
    Handler mapping

    Finds the matching @PostMapping method

  4. 4
    Controller method

    JSON body bound to a DTO parameter

  5. 5
    Service and repository

    Business logic and data access

  6. 6
    JSON response

    Jackson writes the DTO, status code set

LayersTypical layering
  1. 1
    Controller

    HTTP details, DTOs, status codes

  2. 2
    Service

    Business rules and transactions

  3. 3
    Repository

    Database access with Spring Data

  4. 4
    Database

    Tables and rows

SequencePOST /api/books end to end
Client
BookController
BookService
BookRepository
  1. 1POST JSON body
    Client to BookController: POST JSON body
  2. 2create(CreateBookRequest)
    BookController to BookService: create(CreateBookRequest)
  3. 3save(new Book)
    BookService to BookRepository: save(new Book)
  4. 4Book with id 42
    BookRepository to BookService: Book with id 42
  5. 5BookResponse
    BookService to BookController: BookResponse
  6. 6201 Created, Location: /api/books/42
    BookController to Client: 201 Created, Location: /api/books/42

In depth

Designing URLs and choosing methods

Use plural nouns for collections and ids for single items: /api/books and /api/books/42. Nest only one level for clear ownership, such as /api/customers/7/orders. Put filters, search and sorting in query parameters: /api/books?author=tolkien&sort=title. Avoid verbs in paths; the HTTP method is the verb. For actions that are not simple CRUD, a sub-resource such as POST /api/orders/42/cancel is an accepted compromise.

Know which methods are safe and idempotent. GET changes nothing. PUT and DELETE are idempotent: repeating the same request leaves the same state, so clients can retry them after a timeout. POST is not: sending it twice may create two orders. That is why payment APIs accept an idempotency key header on POST.

MapOne resource, five operations
/api/books
  • GET /api/books
    • List, with page and sort
    • 200 OK
  • POST /api/books
    • Create
    • 201 Created + Location
  • GET /api/books/42
    • Read one
    • 200 or 404
  • PUT /api/books/42
    • Replace, idempotent
    • 200 or 404
  • DELETE /api/books/42
    • Remove, idempotent
    • 204 No Content

Status codes clients can rely on

Success codes: 200 OK with a body, 201 Created after POST with a Location header pointing at the new resource, and 204 No Content when there is nothing to return, typical for DELETE. Client errors: 400 Bad Request for malformed or invalid input, 401 when not logged in, 403 when logged in but not allowed, 404 when the resource does not exist, 409 Conflict when the request clashes with current state, such as a duplicate email or a stale version. 500 means a bug on the server and should never be returned on purpose.

In Spring, return ResponseEntity when you need to choose the status or headers, use @ResponseStatus(HttpStatus.NO_CONTENT) for fixed codes, and throw new ResponseStatusException(HttpStatus.NOT_FOUND, "book 42") for quick error cases. Larger apps map their own exceptions to codes in one global handler.

  • ResponseEntity.created(uri).body(dto) gives 201 with Location
  • ResponseEntity.noContent().build() gives 204
  • 422 Unprocessable Content is also used for validation errors by some APIs

Binding requests: path, query, body and headers

@PathVariable takes a value from the URL template, as in /books/{id}. @RequestParam reads query parameters; give optional ones a default with @RequestParam(defaultValue = "0") or use Optional. @RequestBody converts the JSON body into an object, using Jackson through Spring's message converters. @RequestHeader reads headers such as an idempotency key.

Spring converts types for you: a String path segment becomes a Long, an ISO date string becomes a LocalDate, and a mismatch, such as /books/abc for a Long id, gives a 400 error before your code runs. Spring Boot configures Jackson to ignore unknown JSON fields, so older clients keep working when you add fields. Records make excellent request and response types, because they are immutable and Jackson can bind them through their constructor.

Why DTOs and not entities

Returning JPA entities directly from controllers causes three kinds of trouble. First, leaks: every field becomes public JSON, including password hashes or internal flags, and every database change breaks the API. Second, mass assignment: if you bind a request straight into an entity, a client can send "role": "ADMIN" and set fields it should never touch. Third, lazy loading and cycles: Jackson touches every getter, which can trigger extra queries, LazyInitializationException, or endless recursion when Book points to Author and Author back to Book.

Use separate DTOs for each purpose: CreateBookRequest with only the fields a client may set, and BookResponse with only the fields it may see. Map between them in a small mapper class or with a tool like MapStruct. The flow diagram shows where each conversion happens.

FlowWhere DTOs and entities meet
  1. 1
    JSON request

    { "title": "Dune", "authorId": 7 }

  2. 2
    CreateBookRequest

    Only the fields a client may set

  3. 3
    Entity

    Mapper builds Book; service applies rules

  4. 4
    Repository save

    Database assigns the id

  5. 5
    BookResponse

    Only the fields a client may see

  6. 6
    JSON response

    201 Created with Location

Pagination and sorting

Never return an unbounded list; a table that has 50 rows today may have 5 million next year. With Spring Data, add a Pageable parameter to a controller method and Spring fills it from the query string: ?page=0&size=20&sort=title,asc. Pages are zero-based. Pass the Pageable to a repository method that returns Page<T>, which also runs a count query to report total elements and pages. Use Slice<T> to skip that count when you only need a next link.

Protect yourself: spring.data.web.pageable.max-page-size caps the size (2000 by default; set something like 100), and only allow sorting by indexed columns. Since Spring Data 3.3, serialising PageImpl directly logs a warning; return your own page DTO or enable PagedModel serialisation. For very deep pages, offset pagination gets slow, so large feeds use keyset pagination: WHERE id > lastSeenId ORDER BY id LIMIT 20.

  • ?page=2&size=20&sort=price,desc&sort=title
  • @PageableDefault(size = 20, sort = "title")
  • Keyset pagination for infinite scroll and big tables

Learn it in 6 short steps

About 1h 20m each. Track them with a timer in your plan.

  1. 1
    Design resource URLs and HTTP methods~1h 20m
  2. 2
    Build controllers with @RestController~1h 20m
  3. 3
    Map entities to DTOs~1h 20m
  4. 4
    Return correct status codes~1h 20m
  5. 5
    Add pagination and sorting~1h 20m
  6. 6
    Build a CRUD API end to end~1h 20m

Key points

  • Use nouns for URLs (/books/42) and HTTP methods for actions (GET, POST, PUT, DELETE).
  • Return 201 Created with a Location header after POST, and 404 when not found.
  • Map entities to DTOs so you control the JSON and avoid leaking internals.
  • Use Pageable for large collections: /books?page=0&size=20&sort=title.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
@RestController
@RequestMapping("/api/books")
class BookController {
  private final BookService service;
  BookController(BookService service) { this.service = service; }

  @GetMapping("/{id}")
  BookDto get(@PathVariable Long id) { return service.find(id); }

  @PostMapping
  ResponseEntity<BookDto> create(@Valid @RequestBody CreateBookDto dto) {
    BookDto saved = service.create(dto);
    return ResponseEntity.created(URI.create("/api/books/" + saved.id())).body(saved);
  }
}

Update and delete with correct status codes

Step 1: PUT replaces the book; the service throws ResponseStatusException with 404 if the id is unknown, so the client gets a clear error. Step 2: a successful PUT returns 200 with the updated representation. Step 3: DELETE returns 204 No Content via @ResponseStatus, and deleting an id that is already gone can also return 204, which keeps DELETE idempotent. Step 4: the controller stays thin; rules live in the service.

java
@PutMapping("/{id}")
BookResponse replace(@PathVariable long id, @Valid @RequestBody UpdateBookRequest req) {
  return service.replace(id, req);
}

@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
void delete(@PathVariable long id) {
  service.delete(id);   // no error if already deleted
}

// In BookService
Book load(long id) {
  return repo.findById(id).orElseThrow(
      () -> new ResponseStatusException(HttpStatus.NOT_FOUND, "book " + id + " not found"));
}

A paged search endpoint

The book list must support search by author, sorting and pages. Step 1: accept an optional author filter and a Pageable with defaults. Step 2: the repository method findByAuthorContainingIgnoreCase(String, Pageable) is derived by Spring Data. Step 3: map each entity to a response DTO with Page.map. Step 4: return a small page DTO so the JSON shape is stable. A request like GET /api/books?author=le%20guin&page=0&size=10&sort=title returns the first ten matches.

java
record PageResponse<T>(List<T> items, int page, int size, long total) {}

@GetMapping
PageResponse<BookResponse> list(
    @RequestParam(defaultValue = "") String author,
    @PageableDefault(size = 20, sort = "title") Pageable pageable) {
  Page<BookResponse> page = repo
      .findByAuthorContainingIgnoreCase(author, pageable)
      .map(mapper::toResponse);
  return new PageResponse<>(page.getContent(), page.getNumber(),
      page.getSize(), page.getTotalElements());
}

Quick reference

  • Plural nouns for collections: /api/books, /api/books/{id}
  • GET, PUT and DELETE are idempotent; POST is not
  • 201 Created plus Location after POST; 204 No Content after DELETE
  • 409 Conflict for duplicates or stale versions; 404 for unknown ids
  • throw new ResponseStatusException(HttpStatus.NOT_FOUND, msg) for quick errors
  • Separate request and response DTOs prevent leaks and mass assignment
  • Pageable binds ?page=0&size=20&sort=title,asc; pages start at 0
  • Cap page size with spring.data.web.pageable.max-page-size

Common mistakes

  • Returning JPA entities directly, causing lazy-loading errors and leaked fields.
  • Returning 200 for everything, including errors.
  • Verbs in URLs like /getBook instead of GET /books/{id}.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A client times out and retries a request. For which method is a blind retry always safe in terms of final state?

Question 2

2A user registers with an email that already exists. Which status fits best?

Question 3

3Why is binding a request body directly into a User entity dangerous?

Question 4

4What does GET /api/books?page=1&size=20 return with Spring Data paging?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create GET /api/ping that returns JSON {"status": "ok"} with status 200.

  2. Exercise 2medium

    Write POST /api/books that returns 201 Created with a Location header built from the current request URL.

  3. Exercise 3hard

    Build GET /api/customers/{customerId}/orders that returns the customer's orders newest first, 404 if the customer does not exist, and never more than 50 per page.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between PUT and PATCH?
PUT replaces the whole resource with the body you send, so missing fields are cleared. PATCH changes only the fields you send, which is handy for large resources.
Should I version my API?
Version when you must make breaking changes for existing clients. A path prefix such as /api/v1 is the simplest and most visible approach; adding optional fields does not need a new version.
What is the difference between @Controller and @RestController?
@RestController is @Controller plus @ResponseBody, so return values are written as JSON. Plain @Controller is for server-rendered pages where the return value names a view template.
Do I always need to return ResponseEntity?
No. Return the DTO directly for the normal 200 case and use ResponseEntity only when you need a different status or extra headers.

Go deeper

ShareXLinkedInWhatsApp