autobahn
autobahn

Reputation: 115

Should @RequestParam or @RequestBody be used for POST requests in Spring Boot?

@RequestBody requires that a class be created for the JSON body to deserialize into, while @RequestParams do not.

Which one should be used for POST requests, assuming that the params don’t need to be obfuscated? Does it matter? Is either one recommended over the other?

Upvotes: 1

Views: 563

Answers (2)

Ashwini S
Ashwini S

Reputation: 11

@RequestParam , you can use when you want to map from the GET/POST request to your method argument and you can set some default value to it in case you are not passing any argument. @RequestBody, you can use when you are expecting an object as it will automatically deserializes the json into a java type.

Upvotes: 1

Andreas
Andreas

Reputation: 159096

@RequestBody requires that a class be created for the json body to deserialize into

No it doesn't. You can e.g. deserialize into a Map or a List, depending on the JSON.

Which one should be used for POST requests?

That depends on the Content-Type (mime type) of the request.

Does it matter?

Yes.

Is either one recommended over the other?

For mime types application/x-www-form-urlencoded and multipart/form-data you should use @RequestParam.

For anything else, you need to use @RequestBody.

Upvotes: 2

Related Questions