I am learning how REST APIs work in Spring Boot and found an issue when sending JSON data to a controller endpoint.
My API returns:
HTTP 415 Unsupported Media Type
even though the JSON body itself seems valid.
Controller example:
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody User user) {
return "User created";
}
}
Model:
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
JSON body sent from Postman:
{
"name": "Jeferson",
"age": 20
}
Request configuration in Postman:
Method:
POSTURL:
http://localhost:8080/usersBody type:
rawFormat selected:
JSON
I already checked:
the endpoint URL
the HTTP method
the JSON format
the model fields and getters/setters
I also reviewed the HTTP 415 documentation related to unsupported media types, but I still do not fully understand why Spring Boot rejects the request body in this case.
I noticed that when the request fails, Postman sends this header:
Content-Type: text/plain
instead of:
Content-Type: application/json
My questions are:
Why does Spring Boot reject the request when the JSON body itself is valid?
Is the
Content-Typeheader required for@RequestBodyto work correctly?How does Spring Boot determine which media types are supported for a request?