Testing GraphQL APIs
Write calls in GraphQL Playground, then transform them into test scripts in Ruby.
--
A repost of my daughter’s article with permission. I added a few notes. You can find more examples like this in my book: API Testing Recipes in Ruby.
GraphQL is an open-source data query and manipulation language for APIs and a runtime for fulfilling queries with existing data. It stores data in a graph-like structure.
This article will go through some common GraphQL API tests.
How I write GraphQL tests:
Most GraphQL endpoints provide a convenient and user-friendly interface (called Playground) to try out queries: you can type requests and get response data on the right. You can also view the schema there.
I follow the steps:
- Try out queries in GraphQL Playground.
- I also may do it in an HTTP graphic tool that offers more features.
- By then, I have a good idea of the query request I’m sending and what kind of response data I expect.
- Write an automated test in RSpec.
Invoking the GraphQL endpoint code is common. The majority of the effort is to parse response data and perform assertions. Ruby is a great language for that. - Run, verify and refine (typically, I do this using TestWise).
When my test suite reaches a certain size, I run them in a Continuous Testing server, such as BuildWise.
I will use Trevor Blade’s public Countries API (endpoint: https://countries.trevorblades.com/) for some of the exercises in this article.
LIST all records
GraphQL Query
query
is a GraphQL command to find matching data (list). The example below gets countries and returns the code
and name
back.
query {
countries {
code
name
}
}
You can run this query in the GraphQL Playground, like below: