Question

I'm a client side developer, moving over to server side development. One common problem I am encountering is the need to make one API call (say to get an authentication token) and then make a follow up API call to get the data I want. Sometimes, I need to make two API calls in succession for data, without an auth token as well.

Is there a common design pattern or Java library to address this issue? Or do I need to manually create the string of calls each time I need to do so?

Edit: I'm hoping for something that looks like this

CustomClassBasedOnJson myStuff = callAPI("url", getResponse("authURL"));

This would make a call to the "url" with data received from the "authURL". The point here is that I'm stringing multiple url calls, using the result of one call to define the next one.

Was it helpful?

Solution

When doing Server side programming, it is acceptable for HTTP calls to be called synchronously.

Therefore the proper pattern is to simply make the first call, receive the result, and then use that in the next line. There is no need to separate the calls into separate threads, or asynchronous calls, unless there is major processing happening between http calls.

For example:

 JsonResponseEntry getJsonReportResponse() throws IOException {
         String sReportURL = "https://someurl.com/v2/report/report?" +
                 "startts=" + getDateYesterday("ts") +
                 "&endts=" + getDateNow("ts") +
                 "&auth=" + getAuthCode();

         URL reportURL = new URL(sReportURL);
         URLConnection conn = reportURL.openConnection();
         BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         ObjectMapper mapper = new ObjectMapper();
        JsonNode reportResult = mapper.readTree(buf);
         return convertJSonNodeToJsonResponseEntry(reportResult);
    }

    String getAuthCode() throws IOException {
        String sReportURL = "https://someurl.com/auth";
        URL reportURL = new URL(sReportURL);

        HttpURLConnection conn = (HttpURLConnection) reportURL.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();

        String urlParameters = "username=myUserName&password=mypassword";
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        ObjectMapper mapper = new ObjectMapper();
        AuthResponse response = mapper.readValue(buf, AuthResponse.class);
        return response.toString();
    }

The function getAuthCode() is synchronously called within the URL call that requires the response.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top