Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท HTTP Server and Clients

Request Binding and Responses

Read request bodies, forms and uploads in Micronaut, and build responses with HttpResponse, status codes, headers and content negotiation.

A good API does more than return strings. It accepts structured input, answers with the right status code (201 Created after a POST, 204 No Content after a delete), sets headers such as Location, and honors the client's Accept header. Micronaut gives you two levels of control: return plain values and let the framework choose sensible defaults, or return an HttpResponse and decide everything.

The framework code below is read-only because Micronaut is not installed on this site. The runnable programs are Java stand-ins: a fluent response builder that prints the raw HTTP text, and a content-negotiation routine that chooses a media type from an Accept header.

Reading the request

@Body

@Body binds the payload to a parameter. The Content-Type of the request decides how it is read, and JSON is the default:

Java
record NewBook(@NotBlank String title, @Min(1) int pages) {}

@Post("/books")
HttpResponse<Book> create(@Body NewBook input) {
    Book saved = service.save(input);
    return HttpResponse.created(saved);
}

For JSON you can also bind a single property with @Body("title") String title, or take a Map<String, Object> or a JsonNode. Invalid JSON produces 400 Bad Request before your method runs. Add @Valid on the parameter and constraint annotations on the record to validate the input; see the validation lesson in the configuration chapter.

Forms and uploads

For application/x-www-form-urlencoded posts, declare @Consumes(MediaType.APPLICATION_FORM_URLENCODED) and take a @Body record or individual @Body("name") values. For file uploads, use multipart:

Java
@Post(value = "/avatars", consumes = MediaType.MULTIPART_FORM_DATA)
HttpResponse<String> upload(CompletedFileUpload file) throws IOException {
    byte[] bytes = file.getBytes();
    return HttpResponse.ok("received " + file.getFilename() + " (" + bytes.length + " bytes)");
}

CompletedFileUpload holds a small file in memory. For large files, use StreamingFileUpload, which gives you a reactive stream you can copy to storage while it arrives. Both are limited by micronaut.server.multipart.max-file-size and micronaut.http.client limits.

The raw request

When you need everything, take HttpRequest<?> as a parameter. It exposes headers, cookies, the URI, parameters, the remote address and the body. You can mix it with other bound parameters:

Java
@Get("/whoami")
String whoami(HttpRequest<?> request) {
    return request.getRemoteAddress() + " via " + request.getHeaders().get("User-Agent");
}

Building responses

Returning a plain object gives status 200 OK and the default content type. Returning HttpResponse<T> gives full control through factory methods:

Call Status Typical use
HttpResponse.ok(body) 200 Normal success
HttpResponse.created(body) / created(uri) 201 After creating; sets Location
HttpResponse.accepted() 202 Work queued
HttpResponse.noContent() 204 Success with nothing to return
HttpResponse.notFound() 404 Missing resource
HttpResponse.badRequest(body) 400 Invalid input
HttpResponse.status(HttpStatus.CONFLICT) any Other statuses

Chain .header("X-Total-Count", "42"), .contentType(...) or .cookie(...) to add more:

Java
@Post("/books")
HttpResponse<Book> create(@Body NewBook input) {
    Book book = service.save(input);
    return HttpResponse.created(book)
                       .headers(h -> h.location(URI.create("/books/" + book.id())));
}

A shortcut is the @Status annotation, which sets the status of a method that returns a plain value:

Java
@Delete("/{id}")
@Status(HttpStatus.NO_CONTENT)
void remove(long id) { service.delete(id); }

A method with a void return and no @Status replies 200 with an empty body. Returning Optional.empty() or null gives 404.

Status codes you will use most

200 OK Default for returned values.
201 Created After POST, with a Location header.
204 No Content Successful delete or update.
400 or 404 Bad input or missing resource.

Pick the code that tells the client what really happened.

1 / 2

Stand-in 1: a response builder that prints raw HTTP

A response is only text on the wire. This builder mimics the shape of HttpResponse.created(body).header(...) and renders the exact bytes a client would see. It is a stand-in, not the Micronaut class, so use it to understand what you are building.

Java From HttpResponse to bytes

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.

Content negotiation

A client states what it can read with the Accept header, such as Accept: application/json or Accept: text/csv;q=0.5, application/json. A controller can declare several @Produces methods for the same path, or one method that declares several types and serializes accordingly:

Java
@Get(value = "/books", produces = { MediaType.APPLICATION_JSON, MediaType.TEXT_CSV })

Micronaut compares the request's Accept header with the media types the route produces and chooses the best match. If nothing is acceptable, the response is 406 Not Acceptable. The q value ranks preferences from 0 to 1, with 1 the default. Similarly, @Consumes declares which request Content-Type values a route accepts, and a mismatch gives 415 Unsupported Media Type.

Stand-in 2: choosing a media type from Accept

This routine parses an Accept header, honors q weights and wildcards, and picks the best of the types the route can produce. Real Micronaut does the same comparison internally; this code makes the rules visible.

Java Negotiating the media type

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.

Mistakes to avoid

  • Returning 200 with an error message in the body. Use a proper 4xx or 5xx status so clients and monitoring can react.
  • Forgetting Location after 201. It lets clients find the new resource.
  • Reading a huge upload into memory. Use StreamingFileUpload and set size limits.
  • Using @Body on a GET. The router does not bind bodies for methods that normally have none.

Errors and exceptions are covered in Filters and Error Handling. Next, make sure your objects serialize correctly in JSON and Serialization.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which status should a successful POST that creates a resource normally return?

    201 tells the client a resource was created, and Location points to it.
  2. 2. What does a controller method returning Optional.empty() produce?

    An empty Optional or a null return value for a non-void method is turned into 404.
  3. 3. A client sends Accept: application/xml but the route only produces JSON and CSV. What is the outcome?

    406 means the server cannot produce any representation the client accepts. 415 concerns the request body's type.
  4. 4. Which type should you use to stream a large uploaded file to disk?

    StreamingFileUpload processes data as it arrives instead of holding the whole file in memory.

Summary

  • @Body binds JSON (or forms and multipart) to parameters and records; bad input gives 400.
  • Return plain values for defaults, or HttpResponse for status, headers and cookies.
  • @Status sets the status for simple methods; Optional.empty() and null give 404.
  • Accept drives content negotiation (406 when nothing matches); @Consumes gives 415 for wrong request types.
  • Use StreamingFileUpload and size limits for large uploads.

Next: JSON and Serialization