🎓 A1Learner
🔍
0 of 50 lessons completed

Content Types

A content type is a label that says what kind of data an answer carries. JSON answers carry one label, and plain text answers carry another.

A text answer

Ask for /hello. The answer is plain text, so its label names plain text with a charset.

@GetMapping("/hello")
public String hello() {
    return "Hello, Spring Boot!";
}

A JSON answer

Ask for /task. The answer is a task as JSON, so its label is application/json.

@GetMapping("/task")
public TaskForm task() {
    return new TaskForm("Buy milk", false);
}

Fix the labels

produces fixes the answer label, and consumes fixes the label the route accepts.

@PostMapping(value = "/tasks", consumes = "application/json", produces = "application/json")
public TaskForm create(@RequestBody TaskForm form) {
    return form;
}

Example

package com.example.demo;

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

@RestController
public class TaskController {

  record TaskForm(String title, boolean done) {
  }

  @GetMapping("/hello")
  public String hello() {
    return "Hello, Spring Boot!";
  }

  @GetMapping("/task")
  public TaskForm task() {
    return new TaskForm("Buy milk", false);
  }
}

Key points

  • A String answer carries a plain-text label with a charset part.
  • A record answer carries the label application/json.
  • Spring Boot picks the label from the return type.
  • produces sets the label of the answer.
  • consumes sets the label a route accepts in a request.

In this example, the record TaskForm holds a title and a done flag. The controller has two routes. The first route answers GET requests for /hello. It returns a String, so the answer is plain text. The second route answers GET requests for /task. It returns a TaskForm, so the answer is JSON. The first answer carries the text label, and the second carries the JSON label.

Note

The label travels in a header called Content-Type.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What label does a record answer carry?