Tanishq dubey
Tanishq dubey

Reputation: 1542

Spring Boot multiple request types for same endpoint

I am currently porting an old API to Spring Boot and have encountered a problem. In the old API, two types of cURL requests could be made to the same endpoint: one for posting JSON data, and the other for posting JSON data with a file. The two requests look like such:

JSON Only:

curl -i -X POST 'http://localhost:8080/myEndpoint' \
-H 'Accept:application/json' \
-H 'someheader:value' \
-H 'Content-Type:application/json' \
-d '{ "jsondata":"goesHere" }'

JSON with image:

curl -i -X POST 'http://localhost:8080/myEndpoint' \
-H 'Accept: application/json' \
-H 'Content-Type: multipart/mixed' \
-H 'someheader:value' \ 
-F '{ "jsondata":"goesHere" }' \
-F "[email protected]" 

As can been seen, I can either send a Request Body or a Multipart/Mixed request to the same endpoint, and depending on what is received, the server will execute some business logic.

I have tried to replicate this behavior is spring to little avail. I am able to replicate the JSON only request with ease:

@RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
public ResponseEntity createActivityFile(@RequestHeader(value = "someheader") String someheader,
                                         @RequestBody() String body,) {
    // do something...
    return new ResponseEntity(HttpStatus.OK);
}

The trouble arises when I add a multipart file to the mix. I've tried:

@RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
public ResponseEntity createActivityFile(@RequestHeader(value = "someheader") String someheader,
                                         @RequestBody() String body,
                                         @RequestPart(value = "file", required = false) MultipartFile file) {
    // do something...
    return new ResponseEntity(HttpStatus.OK);
}

But with this, I always get a The request was rejected because no multipart boundary was found error.

This leads me to ask, is what I am attempting to do possible with Spring Boot? If so, what would my RequestMapping look like?

Upvotes: 1

Views: 4080

Answers (1)

shi
shi

Reputation: 511

You can do it by using @Consumes annotation

consumes = MediaType.APPLICATION_JSON

And other endpoint with different MediaType

Upvotes: 2

Related Questions