Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 119 ยท Spring Boot

Building REST APIs with Spring Boot

Build JSON REST APIs with Spring Boot - @RestController, @GetMapping and friends, path variables, query parameters, request bodies, ResponseEntity and Jackson.

Most Spring Boot applications today are REST APIs: they receive HTTP requests, read and write JSON, and are called by web front ends, mobile apps or other services. Spring MVC handles this with REST controllers, ordinary classes whose methods are mapped to HTTP methods and paths. Spring parses the path, converts parameters, turns the JSON body into a Java object, calls your method, and writes the return value back as JSON.

In this lesson you will build a complete CRUD API for books with @RestController, and learn every piece you need day to day: mapping annotations, @PathVariable, @RequestParam, @RequestBody, ResponseEntity for status codes and headers, how Jackson is configured, and what Spring answers when a request doesn't fit. Spring can't run on this page, so the runnable examples include a working mini-framework, about 150 lines on top of the JDK's HttpServer, that processes the same annotations with reflection. If you built the API in Building a REST API with the JDK, you'll recognize what each annotation replaces. Good REST design itself (URLs, status codes, pagination) is covered in REST API Design.

@RestController

@RestController is @Controller plus @ResponseBody: every method's return value is written to the response body (converted to JSON) instead of being treated as a view name, as in Spring MVC. Here is the full API we will build:

Java
package com.example.library.web;

import java.net.URI;
import java.util.List;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/api/books")                       // common prefix for all methods
public class BookController {

    private final BookService books;

    public BookController(BookService books) {
        this.books = books;
    }

    @GetMapping                                     // GET /api/books?author=...&limit=...
    public List<Book> list(@RequestParam(defaultValue = "") String author,
                           @RequestParam(defaultValue = "10") int limit) {
        return books.find(author, limit);           // 200 OK + JSON array
    }

    @GetMapping("/{id}")                            // GET /api/books/42
    public ResponseEntity<Book> get(@PathVariable long id) {
        return ResponseEntity.of(books.findById(id));   // Optional: 200 + body, or 404
    }

    @PostMapping                                    // POST /api/books  {"title": ...}
    public ResponseEntity<Book> create(@RequestBody NewBook input) {
        Book book = books.create(input);
        URI location = URI.create("/api/books/" + book.id());
        return ResponseEntity.created(location).body(book);   // 201 + Location + body
    }

    @PutMapping("/{id}")                            // PUT /api/books/42
    public Book replace(@PathVariable long id, @RequestBody NewBook input) {
        return books.replace(id, input)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Book " + id + " not found"));
    }

    @DeleteMapping("/{id}")                         // DELETE /api/books/42
    @ResponseStatus(HttpStatus.NO_CONTENT)          // 204 instead of the default 200
    public void delete(@PathVariable long id) {
        if (!books.delete(id)) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Book " + id + " not found");
        }
    }
}

public record Book(long id, String title, String author, int year) {}
public record NewBook(String title, String author, Integer year) {}

Notice what is not in this class: no parsing of URLs or query strings, no ObjectMapper, no status-code bookkeeping for the normal case. The controller should stay this thin: it translates HTTP into calls to a service and back. Business rules belong in the service layer (see Layered Architecture).

A working @RestController engine

Before going through each annotation, run it. The program below defines the same annotations (@RestController, @RequestMapping, @GetMapping, @PathVariable, @RequestParam, @RequestBody...), a ResponseEntity and a ResponseStatusException, and a dispatcher that scans the controller with reflection, matches requests, converts arguments and writes JSON with Jackson. The BookController part reads almost exactly like the Spring version above. A client script then calls every endpoint, including invalid ones.

Java A mini Spring: annotations to JSON endpoints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real Spring does a lot more in each step (dozens of argument types, content negotiation, validation, caching of handler metadata), but the shape is exactly this: mapping at startup, argument resolution, invocation, return value handling, and exception resolution. Now let's look at each annotation the way you use it in Spring.

Mapping annotations

Annotation HTTP method Typical use
@GetMapping GET Read a resource or a collection
@PostMapping POST Create a resource, or trigger an action
@PutMapping PUT Replace a resource completely
@PatchMapping PATCH Change part of a resource
@DeleteMapping DELETE Delete a resource
@RequestMapping any (set method) Class-level prefix, or several methods at once

@RequestMapping("/api/books") on the class sets a prefix; each method adds its own suffix. Mappings can narrow further with consumes (the request's Content-Type), produces (what the client Accepts), params and headers. Spring answers 405 Method Not Allowed (with an Allow header) when the path exists but not for this method, and 404 when no mapping matches the path.

Spring Framework 7 (Spring Boot 4) added first-class API versioning: mappings get a version attribute, for example @GetMapping(path = "/{id}", version = "2"), and you configure where the version comes from (a header, a query parameter, the path or the media type). Earlier versions solved this with path prefixes like /api/v2/..., which still work everywhere. See REST API Design for the trade-offs.

Path variables and query parameters

@PathVariable binds a in the path; @RequestParam binds a query parameter (or a form field). Both are converted to the parameter's type: long, int, boolean, enums, LocalDate (with @DateTimeFormat), UUID and more.

Java
@GetMapping("/{id}")
public Book get(@PathVariable long id) { ... }               // /api/books/42

@GetMapping("/search")
public List<Book> search(
        @RequestParam String q,                              // required: missing -> 400
        @RequestParam(defaultValue = "0") int page,          // optional with a default
        @RequestParam Optional<String> author,               // optional, no default
        @RequestParam(required = false) Integer year,        // optional, null when absent
        @RequestParam List<String> tag) { ... }              // ?tag=sf&tag=classic

Rules worth remembering:

  • A @RequestParam without a default is required. A missing one gives 400 Bad Request before your method runs. Make it optional with defaultValue, required = false (use a wrapper type such as Integer, never int), or Optional<T>.
  • A value that can't be converted (/api/books/two, ?page=abc) also gives 400. You saw both in the program above.
  • Path variables are for identity (which resource); query parameters are for options (filtering, sorting, paging).
  • For many filter parameters, bind them all to one record: a parameter like BookFilter filter (without an annotation) is filled from the query string field by field.

Request bodies

@RequestBody reads the request body and converts it with an HttpMessageConverter, Jackson for JSON. Records make excellent input types: immutable, concise, and Jackson reads them through their canonical constructor.

Java
public record NewBook(String title, String author, Integer year) {}

@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> create(@RequestBody NewBook input) { ... }

Use a separate input type (a DTO) instead of your stored entity: clients must not be able to set id, createdAt or role. Accepting the entity directly is a classic "mass assignment" security bug. Malformed JSON gives 400; a body with the wrong Content-Type gives 415 Unsupported Media Type. To check values (title must not be blank), add Bean Validation with @Valid, the topic of the next lesson.

ResponseEntity and status codes

Returning an object gives 200 OK with the object as JSON. When you need a different status or extra headers, return ResponseEntity<T>:

Java
ResponseEntity.ok(book)                                   // 200 + body
ResponseEntity.created(URI.create("/api/books/7")).body(book)   // 201 + Location
ResponseEntity.accepted().build()                         // 202, e.g. a job was queued
ResponseEntity.noContent().build()                        // 204, no body
ResponseEntity.notFound().build()                         // 404, no body
ResponseEntity.of(optionalBook)                           // 200 with body, or 404
ResponseEntity.status(HttpStatus.CONFLICT).body(error)    // any status
ResponseEntity.ok().eTag("\"v3\"").cacheControl(CacheControl.maxAge(Duration.ofMinutes(5))).body(book)

Alternatives: @ResponseStatus(HttpStatus.CREATED) on a method fixes the success status without ResponseEntity, and throwing ResponseStatusException ends the request with an error status from anywhere. Use ResponseEntity when the status depends on the outcome, and exceptions for failures, so the happy path stays readable.

To build an absolute Location from the current request, Spring offers ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(book.id()).toUri(). A relative Location like /api/books/7 is also valid HTTP.

JSON with Jackson in Spring Boot

Boot configures one shared JSON mapper bean, and Spring MVC uses it for every @RequestBody and return value. Boot's defaults differ from a plain new ObjectMapper() in two ways that matter:

  • Dates are written as ISO-8601 strings ("2026-03-01"), not as numbers or arrays, and java.time types work out of the box.
  • Unknown properties are ignored instead of failing. A client that sends {"title": "Dune", "colour": "red"} gets no error; the extra field is silently dropped.

Both can be changed with properties, for example:

PROPERTIES
spring.jackson.deserialization.fail-on-unknown-properties=true
spring.jackson.default-property-inclusion=non_null
spring.jackson.property-naming-strategy=SNAKE_CASE

Field-level control uses the Jackson annotations from Advanced Jackson: @JsonProperty, @JsonIgnore, @JsonFormat, @JsonInclude. The program below shows the difference between a plain mapper and one configured the way Boot does it, on the same record.

Java Plain Jackson versus Spring Boot's defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A plain mapper can't even write a LocalDate without the Java time module. With the module but default settings, dates become numbers and arrays, which clients find hard to read. Boot's configuration gives ISO strings and tolerates unknown fields. Whether tolerance is good is a design choice: it lets old servers accept newer clients, but it also hides typos like "autor". Many teams switch fail-on-unknown-properties back on for public APIs.

Spring Boot 4 uses Jackson 3 by default, whose packages start with tools.jackson instead of com.fasterxml.jackson (the annotations keep their old package), and whose main type is JsonMapper. Jackson 3 already writes dates as ISO strings by default and has built-in java.time support. Boot 4 can still use Jackson 2 for migration. The examples on this page use Jackson 2, which is what's available here; the concepts are identical. See JSON with Jackson.

When the request doesn't fit

Spring answers many bad requests before your code runs. Knowing these defaults saves debugging time:

Situation Status Spring exception
No mapping for the path 404 NoResourceFoundException
Path exists, method doesn't 405 + Allow HttpRequestMethodNotSupportedException
Content-Type not accepted (consumes) 415 HttpMediaTypeNotSupportedException
Nothing matches the Accept header (produces) 406 HttpMediaTypeNotAcceptableException
Missing required @RequestParam 400 MissingServletRequestParameterException
Type conversion fails 400 MethodArgumentTypeMismatchException
Malformed JSON body 400 HttpMessageNotReadableException
Any other exception 500 (your bug)

By default Boot renders errors as a small JSON object: {"timestamp": "...", "status": 404, "error": "Not Found", "path": "/api/books/42"}. The exception message is not included by default, so internals don't leak. You'll replace this with standard problem details in Validation and Error Handling.

Content negotiation deserves a closer look. The same resource can have several representations; the client says which it wants with Accept, and the server picks a matching converter or answers 406. In Spring you'd write two methods with different produces, or let one method return an object and register converters for several media types. Here is the mechanism, with the error statuses from the table:

Java Content negotiation: Accept, Content-Type, 406, 415 and 405

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Trying your API

While developing, call endpoints from the command line or your IDE's HTTP client:

Terminal
curl -i http://localhost:8080/api/books?author=Octavia%20E.%20Butler
curl -i -X POST http://localhost:8080/api/books \
     -H "Content-Type: application/json" \
     -d '{"title": "Parable of the Sower", "author": "Octavia E. Butler", "year": 1993}'
curl -i -X DELETE http://localhost:8080/api/books/1

-i prints the status line and headers, which is where most REST bugs show. For documentation, the springdoc-openapi library generates an OpenAPI description and a Swagger UI from your controllers. And when your service must call other APIs, Spring's RestClient (RestClient.create().get().uri(...).retrieve().body(Book.class)) is the modern synchronous client; it mirrors what you did with HttpClient in Calling APIs with HttpClient.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A method is declared as list(@RequestParam int page) and the client calls GET /api/books without a page parameter. What happens?

    A @RequestParam without defaultValue, required = false or Optional is required. Spring rejects the request before calling the method.
  2. 2. What does return ResponseEntity.of(repository.findById(id)); return when the Optional is empty?

    ResponseEntity.of maps a present Optional to 200 with the body and an empty one to 404.
  3. 3. Why should a POST endpoint accept a NewBook DTO instead of the stored Book entity?

    The input type should contain only what a client may send. Binding directly to an entity lets clients overwrite fields they shouldn't control.
  4. 4. A client sends {"title": "Dune", "colour": "red"} to a Spring Boot endpoint whose record has no colour field. With Boot's default Jackson settings, what happens?

    Spring's mapper disables FAIL_ON_UNKNOWN_PROPERTIES by default. You can turn it back on with spring.jackson.deserialization.fail-on-unknown-properties=true.
  5. 5. An endpoint is mapped with produces = "application/json". A client sends Accept: application/xml. What is the response?

    The server can't produce any representation the client accepts, so the answer is 406. 415 is about the request body's Content-Type.

Summary

  • @RestController = @Controller + @ResponseBody: return values become the JSON response body.
  • Map endpoints with @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping, and a class-level @RequestMapping prefix.
  • @PathVariable identifies the resource; @RequestParam carries options. Parameters are converted automatically; missing required ones and failed conversions give 400.
  • @RequestBody reads JSON into a record; use input DTOs, never entities.
  • Return objects for 200, ResponseEntity for other statuses and headers (created, noContent, of(Optional)), and ResponseStatusException for errors.
  • Boot's Jackson defaults write ISO dates and ignore unknown properties; tune them with spring.jackson.*. Boot 4 uses Jackson 3 (tools.jackson packages).
  • Spring answers 404, 405, 406, 415 and 400 for requests that don't fit, before your code runs.

Next: Validation and Error Handling adds @Valid input checks and consistent problem-detail error responses to this API.