Search code examples
springspring-bootgraphqlgraphql-javanetflix-dgs

How to use variables in graphql query via dgs java graphql client?


I am using dgs java graphql client in my code. I want to build a query and specify variables in the query, I want to get something like this::

{
    "query": "query ExampleQuery($first: Int, $filter: ExampleFilter) {  exampleData(first: $first, filter: $filter) { id }",
    "variables": {
        "filter": {
            "field": "test"
        },
        "first": 25
    }
}

To do this I write something like the following code:

GraphQLQueryRequest request = new GraphQLQueryRequest(
        ExampleDataGraphQLQuery.newRequest()
                .queryName("ExampleQuery")
                .filter(ExampleFilterInput.newBuilder().field("test").build())
                .first(25),
        new ExampleProjectionRoot<>().id()
);

Example response = graphQLClient
        .executeQuery(request.serialize(), request.getQuery().getInput())
        .extractValueAsObject(DgsConstants.QUERY.Example, Example.class);

But in the end, when executing a request, I get that it is not the passed variables that are used, but static values ​​directly in the request, something like this:

{
    "query": "exampleData(first: 25, filter: { field: \"test\"}) { id }",
    "variables": {
        "filter": {
            "field": "test"
        },
        "first": 25
    }
}

That is, the variables are not actually used, although they are present in the request body.

I realize that I haven't associated variables with the request body myself, but I haven't found a clear way to substitute variables into a request either in the documentation or in other examples elsewhere. Please tell me how you can use dgs java client graphql to execute a query with parameter substitution?


Solution

  • Your question makes sense, but that's actually not supported with the codegen queries. The thinking is that if you're constructing your query in code like that, you can just pass in the variables there in the Java code. The practical problem would be that the arguments in the codegen query are typed, so an Int is an Integer in Java, which also means you wouldn't be able to pass in a $myVar there.

    I agree that it's a bit confusing that the codegen query API doesn't support variables, while the queryExecutor clearly does, but technically these APIs are completely separated.

    If you need to use variables, I would recommend using a multiline String in Java/Kotlin and write the query that way. With Intellij you also have the `@Language("GraphQL") annotation which makes that a pretty good option.

    Note that this answer was originally answered on the DGS discussions page.