How to format a query to be valid Java code?

Viewed 48

enter image description here

I have a query as below:

query  { 
countries  {code , name , phone ,  currency  }
}

that I want to format as below because I'm using Java to call the query:

{\"query\":\"query  { \\r\\n  \\r\\n  countries  {code , name , phone ,  currency  
}\\r\\n\\r\\n\\r\\n}\" ,\"variables\":{} }

The variables is a part needed for GraphQL.

How could I do this dynamically? Could regex solve this?

2 Answers

Simple example to achieve this:

  • Create a class e.g. MyRequest

    public  class MyRequest {
     private String query;
     private Object variables;
     // constructors getters setters
    
    }
    
  • Create a file with your query e.g. test.graphql

    query countryById($id: Int!) {  {
    countryById(id: $id)  {
      code
      name
      phone
      currency
     }
    }
    
  • Construct the request

      final MyRequest request = new MyRequest();
      final String query = getFileAsString(COUNTRY_BY_ID_QUERY_RELATIVE_PATH);
      IdVariables variables = new IdVariables();
      variables.setId(someId);
      request.setQuery(query);
      request.setVariables(variables);
    
  • Construct HttpEntity and post your request

    final HttpEntity<REQUEST> entity = new HttpEntity<>(request, yourHeaders);
    

The above seems like your trying to send a a GraphQL query over HTTP as JSON. You just need to parse the String to JSON and you can obtain the query as expected.

Popular JSON Parsers for Java are Jackson and GSON.

There is tons of documentation and tutorial on how to use those libaries out there.

You for some reason seem to have serialized your Query twice. As you can see in the below snippet, with serializing twice I get the string you post here (the \\n and \\r are just (Windows) newlines and have no relevance for the actual data). Only do that once when you send a request.

const graphQlQuery = {
  query: `query { 
            countries {
              code, 
              name, 
              phone, 
              currency 
            }
          }`,
  variables: {}
};
// invalid JSON resquest body
console.log("Invalid")
console.log(JSON.stringify(JSON.stringify(graphQlQuery)));
// valid JSON request body
console.log("Valid")
console.log(JSON.stringify(graphQlQuery))

In Postman if you select Raw - JSON as request body instead of GraphQLand paste in the following JSON and hit your GraphQL endpoint with that you should get a response:

{
    "query": "query { countries { code, name, phone, currency } }",
    "variables": {}
}
Related