Saturday, 15 October 2016

Rest API Mock Response Example via Interceptor in Spring MVC with minimal code changes

We had a requirement to mock our rest api feeding to mobile client to be able to mock the responses, since maximum time there were issues to the integrated systems, which would cause the mobile developers to loose time.

I thought about making the least possible changes to our existing service code to return responses.

  1. Client request will add a mock header attribute to the request true/false.
  2. Create a mock Interceptor which should the maximum work for you. In case its not mock forward to designated controller and execute - in this case we will add  an   attribute to the request session , name it the probably your api method eg :- validateNumber.
  3. In your controller you will need to set another attribute as the responseString (json string of the response ) your planning to set for the mock request. (so basically your controller will check for attribute in request session set in Step 2) if exists you set the response String in session.
  4. Post Handling of request in  interceptor will use the session variable for you request api name and response string and save to local file on a common path.
  5. Case 2 :- client request for mock requests , we pick up the same file as the api name requested and display the content directly from the interceptor itself.


       
// Save file for mock response 
String fileName = (String)request.getSession().getAttribute("service");
String responseString = (String)request.getSession().getAttribute("responseString");
if(fileName!=null && responseString!=null ){
 FileUtils.writeStringToFile(new File("D://"+fileName+".txt"), responseString); 
}

// Retrieve file for mock response 
File file = new File("D://"+request.getRequestURL().substring(34)+".txt");
String string = FileUtils.readFileToString(file);
response.getWriter().write(string);


       
 

No comments:

Post a Comment

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...