Search code examples
springposthttp-postpostmanspring2.x

Trying to post JSON to a method end up with this error - Required String parameter 'name' is not present


I know that this question mind be asked before couldn't find exact same problem and I'm new to spring technology so be gentle please

I'm trying post an object using postman which is supposed to be added on my DB

object constructor looks like this

public PostedProduct(String name, long price) {
  super(name, price, UUID.randomUUID());
  }

Mapping function is this

static final String path = "/Products";

@RequestMapping(method = RequestMethod.POST , value = path) 
public void setProducts(@RequestParam("name") String name, @RequestParam("price") long price){
  service.setProduct(new PostedProduct(name,price));
}

SetProduct is a function I use to add Object to my database debugger is not reaching to that statement. This is what i did to post my JSON object

Header

JSON

the following is the error message

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

I tried to change function to this and tried some other combinations

@PostMapping(path)
public void setProducts(@RequestBody PostedProduct product)
{
   service.setProduct(product);
}

Nothing changed except for the error message

"message": "Required request body is missing: public void  Controllers.MarketController.setProducts(Moldels.ProductModel.PostedProduct)"

I'm not looking for a cheap solution I'm trying to learn why. If anyone is willing to help i can provide more detail


Solution

  • I found a solution after 2 days of searching for answer

    Apparently you need to put a Response entity to make sure Spring to handle POST command correctly

    @RequestMapping(value = "/Product" , method = RequestMethod.POST , consumes = MediaType.APPLICATION_JSON_VALUE)
       public ResponseEntity<Product> setPruduct(@RequestBody PostedProduct product )
       {
          service.setProduct(product);
          return new ResponseEntity<Product>(HttpStatus.OK);
       }
    

    Like this or simply annotating HTTP status is ok is enough like this

    @ResponseStatus(value = HttpStatus.OK)
    @RequestMapping(value = "/Product" , method = RequestMethod.POST , consumes = MediaType.APPLICATION_JSON_VALUE)
    public void setPruduct(@RequestBody PostedProduct product )
    {
    service.setProduct(product);
    }
    

    sorry for the trouble