Home > Software design >  Spring boot same API but different return type of byte[] and json
Spring boot same API but different return type of byte[] and json

Time:06-10

I want the capability to send the JSON list like List if the request Accept Header is of type application/json, but send it in a byte array(avro format) if the request Header is of type application/avro. This should be for the same REST endpoint like /something/employee. Can I have the same method but different return types, will Spring Boot look at the accept header and correctly decide on which method to call?

What should be the return type? Can it be a ResponseEntity without any type?

CodePudding user response:

You can define your method to simply return a naked ResponseEntity and check the value of the Accept header to determine what to return

@GetMapping("/something")
public ResponseEntity getContentNegotiateResponse(@RequestHeader("Accept") String accept) {

    SomeObject someObject = new SomeObject();

    if (accept.equalsIgnoreCase(APPLICATION_JSON_VALUE)) {
        return ResponseEntity.of(Optional.of(someObject));
    } else if (accept.equalsIgnoreCase("application/avro")) {
        byte[] value = "SomeData".getBytes(StandardCharsets.UTF_8);
        return ResponseEntity.of(Optional.of(value));
    } else {
        return ResponseEntity.badRequest().build();
    }
}
  • Related