0
votes

I tried to POST like this : curl -X POST -H "Content-Type: application/json" -d "{ \"fisrtName\":\"sunny\" , \"lastName\":\"leone\" }" http://localhost:8080/user

But I get this error : {"timestamp":"2019-12-06T11:07:17.196+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported","path":"/user"}

But, I have my rest-controller like this :

@PostMapping("/user/{firstName}/{lastName}")
    User addUser(@PathVariable String firstName,@PathVariable String lastName)
    {
        return userRepository.save(new User(firstName,lastName));
    }

How this can be resolved ?

2
Well, look at your PostMapping. What is the path? Is it /user as you're using in your curl request? Does the method expects a JSON request body as you're sending in your curl request? - JB Nizet
I'd recommend using a tool such as Postman for using REST url's, makes it a bit easier to understand if you're starting out. - Coder

2 Answers

4
votes

You are passing the firstName and the lastName as JSON.

But your mapping says that they are path variables:

@PostMapping("/user/{firstName}/{lastName}")

Now you try to access http://localhost:8080/user but there is no mapping for this path.

Your post mapping should be:

@PostMapping("/user")
User addUser(@RequestBody User user){
    return userRepository.save(user);
}
0
votes

I hope this will help. if you use @RequestBody instead of pathvariable it will help.

@PostMapping("/user)
    User addUser(@RequestBody User user)
    {
        if(user==null){
        return null;
        }else
        return userRepository.save(user);
    }
curl --location --request POST "http://localhost:8080/user" \
  --header "Content-Type: application/json" \
  --data "{
  \"fisrtName\": \"sunny\",
  \"lastName\": \"leone\"
}"