I'm trying to build a very basic REST API using Spring.
My URL endpoints are:
GET /notes
GET /notes/{noteId}
POST /notes
PUT /notes/{noteId}
DELETE /notes/{noteId}
All these endpoints work perfectly fine as expected except the PUT
request which I want to run to update an item.
The problem is that data is not being received via PUT
, where as it works fine for POST
.
Here's my controller; I've tested it by adding a method identical to the update
method but using POST
and that works fine. I don't know why?
package notes;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/notes")
public class NotesController {
...
@RequestMapping(value="/{noteId}", method=RequestMethod.PUT)
public Response update(@PathVariable Integer noteId, Note note) {
return new Response("Note Updated", note);
}
@RequestMapping(value="/{noteId}", method=RequestMethod.POST)
public Response updateWithPost(@PathVariable Integer noteId, Note note) {
return new Response("Note Updated", note);
}
...
}
Using postman, I've tested POST
http://127.0.0.1:8080/notes/5 and the response was:
{
"message": "Note Updated",
"note": {
"id": null,
"title": "Hello World detail content",
"text": "Hello World",
"createdAt": "72, Mar 2015",
"updatedAt": "72, Mar 2015"
}
}
But for PUT
http://127.0.0.1:8080/notes/5 with exactly same data the response was:
{
"message": "Note Updated",
"note": {
"id": null,
"title": "",
"text": "",
"createdAt": "72, Mar 2015",
"updatedAt": "72, Mar 2015"
}
}
Update Request
For both PUT
& POST
request I'm sending the same test data:
title: Hello World
text: Hello World detail content
Response Class
package notes;
public class Response {
private String message;
private Note note;
public Response(String text) {
setMessage(text);
}
public Response(String text, Note note) {
setMessage(text);
setNote(note);
}
//...getters/setters
}
Note Class
package notes;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Note {
private Integer id = null;
private String title = "";
private String text = "";
private Date createdAt = new Date();
private Date updatedAt = new Date();
public Note() {}
public Note(String title, String text) {
this.setTitle(title);
this.setText(text);
}
//...getters/setters
}
ApplicationConfig
package notes;
import org.springframework.context.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@EnableWebMvc
@Configuration
public class ApplicationConfig {
}
I don't know why this is not working?