Skip to content

NABEEL-AHMED-JAMIL/Rest_Service_RestTeamplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rest Service with RestTeamplate in Test Case

REST stands for Representational State Transfer.

In Rest based design, resources are being manipulated using a common set of verbs.

  • To Create a resource : HTTP POST should be used
  • To Retrieve a resource : HTTP GET should be used
  • To Update a resource : HTTP PUT should be used
  • To Delete a resource : HTTP DELETE should be used

Writing REST Client using RestTemplate

Postman tool we used above is a wonderful Client to test Rest API. But if you want to consume REST based web services from your application, you would need a REST client for your application. One of the most popular HTTP client is Apache HttpComponents HttpClient. But the details to access REST services using this are too low level.

Spring’s RestTemplate comes to Rescue. RestTemplate provides higher level methods that correspond to each of the six main HTTP methods that make invoking many RESTful services a one-liner and enforce REST best practices.

Below shown are HTTP methods and corresponding RestTemplate methods to handle that type of HTTP request.

HTTP Methods and corresponding RestTemplate methods:

  • HTTP GET : getForObject, getForEntity
  • HTTP PUT : put(String url, Object request, String urlVariables)
  • HTTP DELETE : delete
  • HTTP POST : postForLocation(String url, Object request, String urlVariables), postForObject(String url, Object request, Class responseType, String…​ uriVariables)
  • HTTP HEAD : headForHeaders(String url, String urlVariables)
  • HTTP OPTIONS : optionsForAllow(String url, String urlVariables)
  • HTTP PATCH and others : exchange execute

Out put

https://github.com/NABEEL-AHMED-JAMIL/Rest_Service_RestTeamplate/blob/master/output/

Splite the Url

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);

alternatively

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);

UML

You can see the relationship of class in UML folder