GraphQL API Automation

   We know that GraphQL is designed to make APIs fast, flexible, and developer-friendly. It can even be deployed within an integrated development environment (IDE) known as GraphiQL. As an alternative to REST, GraphQL lets developers construct requests that pull data from multiple data sources in a single API call. It is a query language and server-side runtime for APIs that prioritizes giving clients exactly the data they request and no more. In this article, I would like to share the implementation part for GraphQL API automation in different programming languages.

GraphQL API Automation in Java

   To achieve GraphQL automation in Java, we can use the rest-assured library. Below are the sample code details:

public Response postRequestWithGraphQL(String baseURI, String endPointPath, String graphQLQuery, String contentType) {
Response response = null;
try {
String requestPayload = graphqlToJSON(graphQLQuery);
response = RestAssured.given().baseUri(baseURI).basePath(endPointPath).body(requestPayload)
.contentType(contentType).log().all().when().post().andReturn();
response.then().log().all().extract().response();
System.out.println("Execution completed successfully");
} catch (Exception e) {
e.printStackTrace();
}
responseInString = response.asString();
return response;
}

private String graphqlToJSON(String graphQLQuery) {
JSONObject json;
try {
json = new JSONObject();
json.put("query", graphQLQuery);

} catch (Exception e) {
e.printStackTrace();
}
return json.toString();
}

We can call the method as below for the execution,

String baseURI = "https://www.predic8.de";
String endPoint = "/fruit-shop-graphql?";
String graphQLQuery = "query{\r\n" + " products(id: \"7\") {\r\n" + " name\r\n" + " price\r\n"
+ " category {\r\n" + " name\r\n" + " }\r\n" + " vendor {\r\n" + " name\r\n"
+ " id\r\n" + " }\r\n" + " }\r\n" + "}";
postRequestWithGraphQL(baseURI, endPoint, graphQLQuery,
"application/json");

   In the above logic, the method postRequestWithGraphQL helps to execute the GraphQL API. The graphqlToJSON private method helps to convert the string query to JSON format.

GraphQL API Automation in Python

   To achieve GraphQL automation in Python, we can use the package requests, anyway the package will be available along with Python. Below are the sample code details:

def post_request_with_graphql(base_uri, end_point_path, graphql_query, variables=None, header=None):
global url
try:
if end_point_path is None:
url = base_uri
else:
url = base_uri + end_point_path
data = {"query": graphql_query, "variables": variables}
response = requests.post(url, json=data, headers=header)
print(f'API executed successfully and the response is\n {response.json()}')
return response
except Exception as e:
print('The error is ', e)

We can call the method as below for the execution,

def test_post_request_with_graphql(self):
query_data = """
query ($id: String!){
products(id: $id) {
name
price
category {
name
}
vendor {
name
id
}
}
}
"""
variables = {
"id": "1"
}
response = post_request_with_graphql('https://www.predic8.de/fruit-shop-graphql?', None, query_data, variables)
print(response.json())
print(get_response_time(response))

   In the above logic, the method post_request_with_graphql helps to execute the GraphQL API. The test_post_request_with_graphql is a test method to perform the execution.

GraphQL API Automation in C#

   To achieve GraphQL automation in C#, we can use the package RestSharp. Below are the sample code details:

public string Execute_GraphQL_API(string apiURL, string query)
{
try
{
RestClient client = new RestClient();
var request = new RestRequest(apiURL, Method.Post);
request.AddParameter("application/graphql", query, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
return response.Content.Trim();
}
catch (Exception lException)
{
throw new Exception(lException.StackTrace);
}
}

We can call the method as below for the execution,

string apiURL = "https://www.predic8.de/fruit-shop-graphql?";
string query = @"
{
products(id: ""3"") {
name
price
category {
name
}
vendor {
name
id
}
}
}";
Execute_GraphQL_API(apiURL, query);

   In the above logic, the method Execute_GraphQL_API helps to execute the GraphQL API.

GraphQL API Automation in JavaScript

   To achieve GraphQL automation in JavaScript, we can use the method fetch(). Below are the sample code details:

async postRequestWithGraphQL(apiURL, graphQLQuery, headers = {}, JSONreturn = true) {
try {
const graphqlRequest = {
method: 'POST',
headers: headers,
body: JSON.stringify({ query: graphQLQuery }),
};
const response = await fetch(apiURL, graphqlRequest);
if (JSONreturn) {
const data = await response.json();
console.log('The respons is ' + data);
return data;
}
else {
console.log('The respons is ' + response);
return response;
}
} catch (error) {
console.error('Error:', error);
throw error;
}
}

We can call the method as below for the execution,

const query = `query{
products(id: "7") {
name
price
category {
name
}
vendor {
name
id
}
}
}`;
await postRequestWithGraphQL("https://www.predic8.de", "/fruit-shop-graphql?", query, { 'Content-Type': 'application/json' }, false);

   In the above logic, the method postRequestWithGraphQL helps to execute the GraphQL API.

   The GraphQL API testing is very important in the most applications. In this article, we discussed about GraphQL API automation using different programming languages (Java, Python, C# and JavaScript). I hope you really enjoyed reading this article and try to utilize the implementation logic in your live automation projects if you have such a requirement. 

make it perfect!

Leave a comment

Create a website or blog at WordPress.com

Up ↑