6.9 Response Status

A Micronaut’s controller action responds with a 200 HTTP status code by default.

If the controller’s action returns a HttpResponse object, you can configure the status code for the response object with the status method.

  1. @Get(value = "/http-response", produces = MediaType.TEXT_PLAIN)
  2. public HttpResponse httpResponse() {
  3. return HttpResponse.status(HttpStatus.CREATED).body("success");
  4. }
  1. @Get(value = "/http-response", produces = MediaType.TEXT_PLAIN)
  2. HttpResponse httpResponse() {
  3. HttpResponse.status(HttpStatus.CREATED).body("success")
  4. }
  1. @Get(value = "/http-response", produces = [MediaType.TEXT_PLAIN])
  2. fun httpResponse(): HttpResponse<String> {
  3. return HttpResponse.status<String>(HttpStatus.CREATED).body("success")
  4. }

You can also use the @Status annotation.

  1. @Status(HttpStatus.CREATED)
  2. @Get(produces = MediaType.TEXT_PLAIN)
  3. public String index() {
  4. return "success";
  5. }
  1. @Status(HttpStatus.CREATED)
  2. @Get(produces = MediaType.TEXT_PLAIN)
  3. String index() {
  4. return "success"
  5. }
  1. @Status(HttpStatus.CREATED)
  2. @Get(produces = [MediaType.TEXT_PLAIN])
  3. fun index(): String {
  4. return "success"
  5. }

or even respond with an HttpStatus

  1. @Get("/http-status")
  2. public HttpStatus httpStatus() {
  3. return HttpStatus.CREATED;
  4. }
  1. @Get("/http-status")
  2. HttpStatus httpStatus() {
  3. HttpStatus.CREATED
  4. }
  1. @Get("/http-status")
  2. fun httpStatus(): HttpStatus {
  3. return HttpStatus.CREATED
  4. }