I'm working on a REST API using Spring and I'm trying to implement a POST endpoint that receives x-www-form-urlencoded
data in it's body. This is my controller method so far:
@PostMapping(value = "/v1/contracts", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Object> fetchFilteredContracts(
@RequestBody FilterObj body,
@RequestParam(required = false) String number,
@RequestParam(required = false) String supplierNumber
) {
List<DataTableFilter.ColumnFilter> columnFilters = new ArrayList<>();
if (number != null) {
columnFilters.add(new DataTableFilter.ColumnFilter("number", number));
}
if (supplierNumber != null) {
columnFilters.add(new DataTableFilter.ColumnFilter("supplierNumber", supplierNumber));
}
// Additional code not implemented yet
return new ResponseEntity<>(HttpStatus.OK);
}
And just to explain further, this is my FilterObj:
public record FilterObj(
String search_mode
) {}
I am using Postman to call this endpoint bit I get 415: Unsupported Media Type
. See image.
NOTE: If I remove the @RequestBody FilterObj body
annotation from the method parameters it works fine, but then I don't have access to the body
object.
What am I doing wrong here?
@RequestBody will expect JSON/XML as body, and if you are sending key/value pairs then you need to either use @ModelAttribute to bind directly to your FilterObj or use MultiValueMap to (sort of manually) parse pairs and use them in your controller.
Or, if you control the client of your REST service, then use json to send objects to your endpoint.