简体   繁体   中英

How to call a GraphQL query/mutation with Java code

I know we can use the /graphiql endpoint to test the created or deployed GraphQL API.

在此处输入图片说明

  1. I need to consume a GraphQL API which is already there using a Java code. How can I do it.
  2. How can I test a GraphQL end-point using a postman like application, or is it even possible.

Depending on your situation, utilizing Spring RestTemplate might be simplest thing to do.

public class Person {
    @JsonProperty("query")
    public final String query = "mutation($name:String, $gender:String, $age:Int) { updateDetails (name: $name, gender: $gender, age: $age) }";
    @JsonProperty("variables")
    public final Map<String, String> variables;
...
}
...
(new RestTemplate()).postForEntity("http://example.com/graphql", new Person("David", "male", 12));

Could go even simpler by avoiding Spring and using HttpClient, building same JSON document using StringBuilder.

Alternatively Apollo Andoid can autogenerate client code for you.

An example, to work for me... username and password are wrong :) But, URL is ok...

with that, I don't use RestTemplate, any jars, etc..

private static void test_LivePharma() {
    try {
        URL url = new URL("https://stores-hml.funcionalmais.com/graphql");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");

        String input="{\"query\":\"mutation{createToken(login:\\\"112233\\\",password:\\\"112233\\\"){  token}}\\n\"}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}

Consuming graphql API in your backend code, will require multiple steps such as.

  1. Defining the schema
  2. Installing the dependencies
  3. Defining the graphql endpoint
import com.coxautodev.graphql.tools.SchemaParser;
import javax.servlet.annotation.WebServlet;
import graphql.servlet.SimpleGraphQLServlet;


@WebServlet(urlPatterns = "/graphql")
public class GraphQLEndpoint extends SimpleGraphQLServlet {

    public GraphQLEndpoint() {
        super(SchemaParser.newParser()
                .file("schema.graphqls") //parse the schema file created earlier
                .build()
                .makeExecutableSchema());
    }
}

Here is a detailed guide to do the same : Graphql-java-backend-implementation

Yes, it is possible to send the request using postman. You can simply copy the schema in the body. Doing GraphQL request using Postman

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM