Edmar Munhoz
Edmar Munhoz

Reputation: 221

What is the best way to handle GraphQl response in Java

In a legacy application with Java 6 I am calling a GraphQl API using Spring RestTemplate, now I would like to know what is the best way to handle the response, once GraphQl always will give a response with StatusCode 200 in case of success or error and the difference is that inside the body response there will be a string with "data" for success and "errors" for errors. I was thinking that I can get the response and convert to String and check using "contains" and check if there is "data" or "errors" inside the response body, but I do not know if it is the best way. The code below is how the Java application is calling the GraphQl API:

ResponseEntity<?> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

The way that I thought to handle is:

if (response.getBody().toString().contains("errors")){
    handleException
}

Upvotes: 0

Views: 4157

Answers (1)

Ken Chan
Ken Chan

Reputation: 90447

GraphQL will give the response body in the following JSON format

{
  "data": { ... },
  "errors": [ ... ]
}

If there were errors , it will have an errors fields.

So , it is a bad idea as you are checking if the whole JSON response contains an errors string rather than errors field. It will definitely fail for the success case just because data contains a errors string (e.g Think about it is a get user request but an user use errors as his login ID)

You should parse the response body into the JSON object and check if the JSON contains a field called errors or not.

If you have Jackson in the class path , RestTemplate will detect it and auto configure itself to be able to parse JSON which allows you to do something like:

ResponseEntity<Map<String,Object>> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
Map<String,Object> body = response.getBody();
if(body.containsKey("errors")){
   //handleException
}

Upvotes: 2

Related Questions