Spring REST API -Part 4.2: Spring Controllers (RestController — POST,PUT,DELETE)

Zia khalid
5 min readApr 30, 2017

Part 4.2: Spring Controllers (RestController — POST,PUT,DELETE)

Note — Codes in the story is in continuation to the previous parts, so if you feel uncomfortable or disconnected please check the previous parts or navigate through git commit to have a better understanding.

In this part we will learn about HTTP method POST, PUT and DELETE

HTTP POST

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

Note — it should not updates existing resources as we have different method for it(PUT).

POST method is basically used to add new entity, If you want to add new entry to your collection you should go for POST.

Handling POST request

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> addTopic(@RequestBody Topic topic) {
if (topicRepository.save(new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
return Util.createResponseEntity("Successful creation of a resource", HttpStatus.CREATED);
}
return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}

@RequestBody annotation indicating a method parameter should be bound to the body of the web request.The body of the request is passed through an HttpMessageConverter which process HTTP requests and responses, to resolve the method argument depending on the content type of the request.

<S extends T> S save(S entity) Saves the given entity.

Commit
https://github.com/ziakhalid/spring-rest-sample/commit/4deb99ff5884c010c6b636557ea7eec324427e9b

Thats it, your api is ready to handle POST request.

Hit Run

Using Client : Postman
Sending POST request to add new topic.

Select request type to POST
Select Body tab > raw > add json object of Topic type

Goto Headers tab > set Key to Content-Type and value to application/json

Hit Send, this should add new topic to your previous list. To check if your request is added to the list, again Hit GET request to get the list of topics, which should have newly added topic “”Java 8 — lambda”

HTTP PUT

PUT should be used to update existing resource.

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.”

Updating existing resource

Now you wanna update existing resource, lets say you wanna update resource with id 1

Adding getTopicById which will return Topic by Id

@RequestMapping(method = RequestMethod.GET, value = "topicId/{topicId}")
public Topic getTopicById(@PathVariable Long topicId) {
return topicRepository.findOne(topicId);
}

Lets see if its working

topicId 1 returns a topic named “Multi Threading”, i wanna update it to “Language Fundamentals” and increase “questionCount”

Adding updateTopic which will handle HTTP PUT request and update the requested data

@RequestMapping(method = RequestMethod.PUT, value = "topicId/{topicId}")
public ResponseEntity<?> updateTopic(@RequestBody Topic topic, @PathVariable long topicId) {
Topic newTopic = topicRepository.findOne(topicId);
if (newTopic != null) {
newTopic.setTopicName(topic.getTopicName());
newTopic.setQuestionCount(topic.getQuestionCount());
if (topicRepository.save(newTopic).getId().equals(topicId)) {
return Util.createResponseEntity("Data updated successfully", HttpStatus.OK);
}
}
return Util.createResponseEntity("Error updating data", HttpStatus.NOT_FOUND);
}

Commit
https://github.com/ziakhalid/spring-rest-sample/commit/6fce96130e056759b5b76d5b035a6bb685a63888

Hit Run

Using Client : Postman
Sending PUT request to update existing resource.

Select request type to PUT
Select Body tab > raw > add json object of updated Topic type

Goto Headers tab > set Key to Content-Type and value to application/json

Hit Send, this should update your data.

To recheck your updated data Hit GET request for topicId 1

Here you go data updated successfully :)

HTTP DELETE

The DELETE method requests that the origin server delete the resource identified by the Request-URI.

Now i wanna delete existing resource, lets say i wanna delete topic with topicId 1

Adding deleteTopic which will delete topic based on topicId

@RequestMapping(method = RequestMethod.DELETE, value = "topicId/{topicId}")
ResponseEntity<?> deleteTopic(@PathVariable long topicId) {
try {
topicRepository.delete(topicId);
return Util.createResponseEntity("Data deleted successfully", HttpStatus.ACCEPTED);
} catch (Exception e) {
return Util.createResponseEntity("Resource not found", HttpStatus.NOT_FOUND);
}
}

Commit
https://github.com/ziakhalid/spring-rest-sample/commit/6722782df03cdb903da27f0d412f33d26b1ae18f

Hit Run

Using Client : Postman
Sending DELETE request to delete existing resource.

Here you go, “Data deleted successfully”

If you find something to improve please let me know, I will try my best to improve this story.

If this article was helpful to you, please do hit the 💚 button below. Thanks!

See you in the next story!

--

--