Search code examples
javaapidesign-patternsmethod-chaining

Best design pattern for API chaining in JAVA


I want to invoke series of API calls in Java. The requirement is that some API's response will be used in the subsequent API call's request. I can achieve this using certain loops. But I want to use a design pattern in such a way that the implementation is generic. Any help?

Chain of responsibility doesn't serve my need as I won't be knowing what is my request context in the beginning.

String out = null;
Response res = execute(req);
out += res.getOut();
req.setXYZ(res.getXYZ);
Response res = execute(req);
out += res.getOut();
req.setABC(res.getABC);
Response res = execute(req);
out += res.getOut();

System.out.println("Final response::"+out);

Solution

  • Thanks all for the inputs, finally I landed on one solution which meets my need. I used one Singleton for the request execution. For each type of command, there will a set of requests to be executed in one particular order. Each command is having a particular order of requests to be executed which I stored in an array with request's unique ID. Then kept the array in a map against command name.

    In a loop, I ran the array and executed, after each iteration I keep setting the response back into the request object and eventually prepared the output response.

        private static Map<RequestAction,String[]> actionMap = new HashMap<RequestAction, String[]>();
    
        static{
        actionMap.put(RequestAction.COMMAND1,new String[]{WebServiceConstants.ONE,WebServiceConstants.TWO,WebServiceConstants.FOUR,WebServiceConstants.THREE});
        actionMap.put(RequestAction.THREE,new String[]{WebServiceConstants.FIVE,WebServiceConstants.ONE,WebServiceConstants.TWO});}
    
    
        public Map<String,Object> execute(ServiceParam param) {
    
        String[] requestChain = getRequestChain(param);
    
        Map<String,Object> responseMap = new HashMap<String, Object>();
    
    
        for(String reqId : requestChain) {
    
            prepareForProcessing(param, tempMap,responseMap);
    
            param.getRequest().setReqId(reqId);
    
            //processing the request
            tempMap = Service.INSTANCE.process(param);
    
            //prepare responseMap using tempMap         
    
            param.setResponse(response);
    
        }
    
        return responseMap;
    }