Go back to blog listing

What is GraphQL and How to Test it?

GraphQL endpoints need testing as much as any endpoint, and automated testing is here to lend a hand. Learn more about how to test GraphQL with test automation below!

GraphQL is a query language for APIs that began at Facebook but has been open sourced since 2016. The simplification of queries and responses provided by GraphQL originated from usage within mobile applications, but it has general usefulness for simplifying the use of complex APIs while reducing the amount of data returned. 

What is GraphQL?

When GraphQL was originally created, it was built to solve a specific problem. In 2011, as most users were interfacing with applications from their browsers, we started to see a heavy migration from web to mobile. Particularly in Facebook’s case, this required calling multiple APIs from multiple different locations in the application. Depending on what the scenario was trying to achieve, those APIs would either deliver too much or too little information. So, to solve this challenge, Facebook sought to create a way that would simplify the delivery of information and reduce the total traffic that was required to accomplish their scenarios.

This gave birth to GraphQL. The technology was originally used by Facebook’s iOS mobile team and then proliferated to the rest of the mobile interfaces. Soon the vast majority of all mobile interactions were leveraging their GraphQL APIs. In 2015, Facebook announced the implementation, the world saw the advantages of using the technology, and rapid adoption ensued.

How does GraphQL work?

GraphQL is an abstraction layer that exists between the front-end systems and the backend APIs. This abstraction layer allows you to construct queries that access multiple resources in the backend and aggregate that data together into a single meaningful response.

graphQL-1

Backend APIs are typically granular because we want to create reusable building blocks for our applications; however, that doesn’t directly translate to our user stories or to the actions we want to be able to accomplish from the front-end. GraphQL is a way to simplify the interactions with your backend data, by using an interface whose schemas describe the system behavior so you can get efficient data from your APIs.

Each of the GraphQL schema’s map to functions. These functions will then make subsequent calls to the backend, according to your business logic, against your REST APIs, databases, and any other resources necessary to collect the data that was requested.

The functions will then assemble the necessary data into a response that will maintain the same shape as the request making it very easy to understand which data is associated to which elements in the request.

Ask for what you need,
get exactly that - graphql.org

Additionally, GraphQL can be set up to call multiple backend services as it assembles its query response. This reduces the total time that a consumer needs to spend navigating through API docs to understand what information is available from a call.

GraphQL vs. Traditional REST APIs

There are many advantages GraphQL can provide over traditional REST API interfaces. Like most technology implementations, there is no silver bullet or one technology stack that’s better than another. But one of the reasons that GraphQL is gaining traction is because of its flexibility in retrieving information.

When using a traditional REST API, usually the call that you want to make to retrieve your information is not the only call that you make into the system. For example, if I want to retrieve my account balance, the first thing I need to do is retrieve my customer number and then use that customer number to retrieve my account numbers. Once I have my account numbers, I can then do query on the balance for that Account:

  1. Login = CustomerId
  2. CustomerId = account ID
  3. AccountID = Balance

There’s nothing wrong with REST APIs. This is simply how they work, and they allow us to create discrete actions that can be leveraged in many different ways. But in this particular case, in order to retrieve the information that I wanted, I had to make calls with a sequence of three APIs chained together. Additionally, if we think about the volume of data that was exchanged in this interaction for each of these API calls, we had to send the proper request and receive an entire response defined by the schema. In our case, I really only needed to deal with the three values of customer ID, account ID, and balance.

So, let’s see how this transaction would take place in the GraphQL world:

query {
Customer(name:”Chris Colosimo”) {
    accountId{
        Balance
  }
 }
}

If you’re a veteran GraphQL user, please take that request with a grain of salt. I use it to illustrate that what would traditionally be accomplished with three API calls can be accomplished with one using GraphQL. The best part is it that it doesn’t require reimplementation of your existing functionality.

There are many additional pros and cons between REST and GraphQL, but it's important to note that GraphQL and REST APIs are not mutually exclusive, and the adoption of one does not exclude the other. In fact, the two work quite harmoniously together.

So the question isn’t whether to use GraphQL or REST API, but rather, when should you introduce GraphQL to your front-end resources? The answer is actually pretty simple, in theory: You should use GraphQL when you want to create a simple and efficient interface for consumers that want to leverage your APIs. Additionally, you may want to consider leveraging GraphQL when you want to reduce the total traffic exchanged between your frontend and the backend, like Facebook did for mobile traffic.

Automated Testing of GraphQL Endpoints

GraphQL is a very powerful technology that will enable your API consumers to access their information in a more efficient way, but in order to ensure that the experience works the way you expect, you need to validate your GraphQL APIs. This is where test automation comes in.

There are many test automation tools out there that can help you test your GraphQL APIs. I am going to provide you an example using Parasoft SOAtest, a widely used API testing solution that simplifies the often-daunting challenge of validating your critical APIs across multiple technologies. It supports a wide range of message formats and protocols and has had GraphQL support for a while now.

GraphQL endpoints accept queries (as strings) and returns JSON responses with the query results. This fits nicely with SOAtest, since queries can be made by REST clients to send the queries and validation can be done by existing JSON verification tools.

Consider the following simple example GraphQL query:

query {
   users{
      firstname
      lastname
      }
   }

An expected return would be something like:

{
   “data” : {
      “users” : [
         {
            “firstname” : “John”,
            “lastname” : “Doe”
         },
         {
            “firstname” : “Alicia”,
            “lastname” : “Smith”
         }
      ]
   }
}

This same query can be created in Parasoft SOAtest as a REST client:

graphQL-2In SOAtest, the GraphQL queries are sent as a string named “query.” Responses are returned in JSON which SOAtest is readily able to interpret and represent in its traffic viewer:

graphQL-3The returned values are expected. Obviously we need an automated way to verify these results and the SOAtest JSON assertor comes in handy here.

Verifying GraphQL Responses

SOAtest verifies JSON responses using assertions that are configured with its JSON assertor tool. Here’s an example check to see if the first name returned is a string “Luis” (which we know is not a valid value.)

graphQL-4

Running the test again, the test fails:

graphQL-5

As you can see, it’s straightforward testing GraphQL endpoints in SOAtest using already existing capabilities.

What about authentication? This is already handled by SOAtest and the existing client authentication tools will work with GraphQL endpoints as well:

graphQL-6

Why Parasoft SOAtest for GraphQL Testing?

The benefits that SOAtest brings to REST, SOAP, and other API testing remains the same for GraphQL. Designed to fit into an existing testing infrastructure, Parasoft SOAtest accelerates testing that enables agile development by helping testers work smarter, with script-less testing that facilitates collaboration across dev, test, performance, and security teams.

Parasoft SOAtest makes tests easy to create, easy to manage and orchestrate, and easy to run and analyze. Going beyond GraphQL, SOAtest's support for 120+ message formats/protocols plus test generation aided by AI and machine learning is making API testing easier.

Want to see GraphQL testing in action?

Take a look at this video, where we do just that:

 

 

The leading API and UI functional testing solution, powered by AI and machine learning

Stay up to date