Skip to content

How To Automate GraphQL Using Rest Assured

GraphQl Using Rest Assured

In the last article, we learned about GraphQL and how it is different from Rest Services. In case you missed the article you can check it here. In this article, we will find out how to automate GraphQL using the Rest Assured library. Rest assured is a java-based library used primarily to test Restful web services. It can be used to automate GraphQL queries and mutation as well with slight modification.

Let’s start with a simple maven project which includes the following dependencies:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.3.3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.14.3</version>
</dependency>

Our goal is to fetch the fruit details like its name, vendor, and category based on the provided input.

The endpoint URL is: “https://www.predic8.de/fruit-shop-graphql”

Request Body:

query{
  products(id: "7") {
    name
    price
    category {
      name
    }
    vendor {
      name
      id
    }
  }
}

We need to follow the below steps in Rest Assured:

  • Specify the base URL.
  • Convert GraphQL query into request payload using Jsonobject.
  • Specify Content-Type.
  • Send the Request to the Server
  • Get the Response back from the server
  • Print the returned Response’s Body.

How To Use Rest assured For Graphql Automation?

a)First Import these static packages into your class file.

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import org.json.JSONObject;

b) Create a method that will accept the String payload and convert it into JSON.

private static String graphqlToJson(String payload)
{
     JSONObject json = new JSONObject();
     json.put("query",payload);
     return  json.toString();
}

c) Let’s Create a test method using Rest Assured to hit the endpoint and fetch the response from the server. Validate response body and status code.

Steps:

1)Provide BaseURI
2)Convert GraphQL query into JSON
3)Sent Post request with JSON payload
4)Validate the status line.

@Test
public void testGraphql()
{
RestAssured.baseURI="https://www.predic8.de/fruit-shop-graphql?";
String query="query{
  products(id: "7") {
    name
    price
    category {
      name
    }
    vendor {
      name
      id
    }
  }
}
"             
String jsonString=graphqlToJson(query);
		
given().log().all().contentType("application/json").body(<meta charset="utf-8">jsonString)
.when().log().all().post().then().log().all().assertThat().statusLine("HTTP/1.1 200 OK");

Great! We have successfully written and run our first GraphQL API test using Rest Assured. Suppose we want to test this API with an input variable. We don’t want to hardcode the data. In this case, we need to use variables. Let’s try to incorporate query variables in our test script.

Test GraphQL
QueryWithVariable

In the above screenshot, We can see the Query schema on the left and the input variable “id” in the right section. To achieve this Rest assured we will use the Data provider concept of TestNg. First, modify our API to accept input types and then provide input by using a Data provider method of the TestNG framework.

What is DataProvider?

Data Provider is an important feature provided by TestNg Framework to write data-driven tests which means that the same test method can be run multiple times with different sets of data. We will utilize this method to pass query variables as input and execute the same query for different groups of inputs.

@DataProvider
public Object[][] getQueryData(){
return new Object[][] {{"8"},
};
}

@Test(dataProvider="getQueryData")
public void testGraphqlwithVariable(String id)
{
RestAssured.baseURI="https://www.predic8.de/fruit-shop-graphql?";
String query="{\"query\":\"query($id:String!){\\n  products(id:$id) {\\n    name\\n    price\\n    category {\\n      name\\n    }\\n    vendor {\\n      name\\n      id\\n    }\\n  }\\n}\\n\","
+ "\"variables\":{\"id\":"+id+"}}";

given().log().all().contentType("application/json").body(query)
.when().log().all().post().then().log().all().assertThat()
.statusLine("HTTP/1.1 200 OK");
}

Now execute it and it will successfully fetch the result:

GraphQL using Rest Assured
Response

Let’s take a look at a different type of Schema. Here Instead of a query operation, we want to perform the mutation.

mutation ($id:Int!, $name:String!,$products[Int!]){
  updateCategory(id:$id, name:$name, products:$products) {
    name
    products {
      name
    }
  }
}

This mutation query updates the category of the existing product. To achieve this goal we will follow the same approach as we did for the simple query. Again, we will utilize the DataProvider method to feed the required data to the mutation query based on which existing category of fruits(product) will be updated.

@DataProvider
public Object[][] getMutationData(){
return new Object[][] {{7,"CherryRed"},
};
}

@Test(dataProvider="getMutationData")
public void TestMutationWithVariable(int id, String Name)
{
RestAssured.baseURI="https://www.predic8.de/fruit-shop-graphql?";
		
String Query="{\"query\":\"mutation ($id:Int!, $name:String!,$products:[Int!]){\\n  updateCategory(id:$id, name:$name,products: $products)  {\\n    name\\n    products {\\n      name\\n    }\\n  }\\n}\\n\",\"variables\":{\"id\":"+id+",\"name\":\""+Name+"\",\"products\":[2,7]}}";
				
given().log().all().contentType("application/json").body(Query)
.when().log().all().post().then().log().all().assertThat().statusLine("HTTP/1.1 200 OK");
}
	

We have seen that it is possible to use Rest assured to write scripts for GraphQL Queries. We can use POJO classes just like Rest APIs to use serialization and deserialization concepts. By using Jackson’s data-bind library we can parse GraphQL data, which can be another alternative to automate GraphQL API.

For more theory related to Rest Assured please visit https://www.swtestacademy.com/rest-assured-tutorial-api-testing/.