website statistics

Computer Science


Two arrays from api call from two apis compare them and find the difference

1 Answer

  • Answer:

    have increased in popularity over the last few years. The trend started with giants like eBay and Amazon. This has happened because these types of APIs present multiple advantages. Some of these benefits are: good performance in component interactions, scalability, simplicity, portability and reliability.

    For these types of APIs, JSON files are the default choice for formatting transferred data. These types of files are easy to read and write and can be used with any popular programming language.

    As testers, API testing is something pretty common in today’s industry. These tests are performed in the message layer, since APIs lack a GUI. In a typical scenario, your team decides whether to integrate an API or design one. Before the integration with the UI is complete, the API needs to be tested. Thus, you get access to endpoints that you try various scenarios on: sending a set of parameters and asserting that the response contains the expected data. This is the most basic scenario for an API test.

    Besides the case presented above, API tests can have various requirements, depending on the nature of the project and task.

    One requirement I have come across recently, sounded something like: ‘We have 2 (or more) APIs. We need to check if the keys for an endpoint on API1 are exactly the same as the keys from its equivalent endpoint from API2. ‘The same’ means that the name, order and number of occurrences of each key must coincide.” The order of the of the keys in a JSON would normally not be relevant, but we will see why I mentioned it in this context.

    That’s straightforward enough…

    The solutions on how to test this are numerous:

    The most basic solution would be to use an online JSON comparer (like this one or this one). This would imply though that you have to manually input the responses of the endpoints under test in the online comparer and repeat for every endpoint. Not too elegant if you ask me. Also, inefficient if you have to do it for hundreds of endpoints.

    Another approach is to use various Java libraries that can handle these types of tasks, like Jackson or GSON.

    If you choose to use Jackson, the code would go something like:

    final JSONObject obj1 = /*json*/;

    final JSONObject obj2 = /*json*/;

    final ObjectMapper mapper = new ObjectMapper();

    final JsonNode tree1 = mapper.readTree(obj1.toString());

    final JsonNode tree2 = mapper.readTree(obj2.toString());

    return tree1.equals(tree2);

You May Be Interested