Mirco Lcl
Mirco Lcl

Reputation: 373

Unable to send data to POST Service in Spring 4

I'm trying to write a simple HTTP REST service using Spring 4.

I'm having troubles sending data to a POST endpoint

@RequestMapping(value = "/onlyPost", produces = "application/json", method 
= RequestMethod.POST)
public @ResponseBody ResponseEntity<?> createUser(@RequestParam("value1") 
String param1, @RequestParam("value2") String param2) {
....
}

While trying to send data with Postman, I receive a 400 message (obviously the values are setted in the request's body)

"message": "Required String parameter 'value1' is not present",

What I have noticed is that the issue is somewhat related to the headers, because when I remove the postman's header (Content-Type: application/json) everything works fine.

I tried for more than one hour fixing this by myself with no results. Any hints?

Upvotes: 2

Views: 58

Answers (2)

Luciano van der Veekens
Luciano van der Veekens

Reputation: 6577

@RequestParam is used to read a URL query parameter.

http://localhost:8080/springmvc/onlyPost?value1=foo&value2=bar

For instance, in the URL above, value1 and value2 are query parameters that you can read using that annotation.

But if you want to read a JSON request instead, you need to change the method to:

@RequestMapping(value = "/onlyPost", method = RequestMethod.POST, 
    consumes = "application/json")
public @ResponseBody ResponseEntity<?> createUser(@RequestBody User user) {
    ....
}

where User is a POJO holding the two fields:

public class User {
    private String value1;
    private String value2;

    // getters and setters...
}

Upvotes: 1

Pijotrek
Pijotrek

Reputation: 3021

HTTP 400 is returned when your request is badly formatted, i.e. missing required request parameters

@RequestParam is for URL Params, if you want to pass them like that, you call <api_url>/onlyPost?value1=<value1>&value2=<value2> but... if you want to create user you should rather use @RequestBody and put your user data there. Something like that:

@RequestMapping(value = "/users", produces = "application/json", method 
= RequestMethod.POST) 
public @ResponseBody ResponseEntity<?> createUser(@RequestBody User user) {
    [...]
}

if you are creating REST api you should use concrete endpoints, here is a pretty cool reading with some tips: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

Upvotes: 1

Related Questions