Search code examples
androidandroid-volley

How do I implement dynamic API handling?


So I was working on a project where there are many API is going to be used like 5 different ones, all from different hostnames. For this I am using Volley for the requests. Now my question is how do I get the values produced by the different APIs, with different JSON Output.

The Sample Scenario: I need to get the name of the user from all the APIs but they have all different tags on the API Response. I.E.

API 1 (JSON data):

{
  data: {
    name: 'Sumname',

  }
}

API 2 (JSON data):

{
  data: {
    user_name: 'Sumname'
  }
}

Now I need to get the 'Sumname' (or the name of the user) on both APIs.

Do I need to make multiple Volley requests like this?

private void sumclass(){
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = "URL";
        StringRequest sendQueue = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();
                params.put("value", "value");

                return params;
            }
        };

        queue.add(sendQueue);
}

For every API that is going to be used? OR is there an easy way for this? I usually work with 1 API only, so I don't have much idea on this problem. I did some research but I'm not satisfied with the results.


Solution

  • To solve your issue or to resolve your use-case condition as per my experience you can use Retrofit library.

    1. The retrofit will provide you the dynamic API calling functionality.

    Eg. Suppose you have two API's Api1 and Api2

    The retrofit takes the base address and the remaining address will be the API path of your API.

    Suppose your API is like 1.www.xyz.com/api1 and 2.www.xyz.com/api2

    then your base address will be www.xyz.com/ and the remaining part will be /api1

    In this way, you can solve your use-case.

    And the function/method will be different for each API