logo logo

Introduction and Getting Started with GraphQL

main post image

It’s 2020 and the need for being digitally available has become a demand. Given the COVID-19 pandemic, I believe you’d agree that it has become an utmost necessity.

Having an online presence alone doesn’t make your business run forefront, but other factors like time to market with good user experience matter a lot. Undoubtedly, the application development shift towards a microservices architecture with an emphasis on flexibility and time to market, tools like GraphQL are redefining API design and the interaction between the client-server, that enhances the developer’s productivity and experience with minimal data transfers.

Today, GraphQL powers a variety of companies such as Airbnb, Atlassian, Audi, CNBC, GitHub, Netflix, Shopify, The New York Times, Twitter, and Pinterest. GraphQL also powers hundreds of billions of API calls a day on Facebook social media platforms.

In this blog series, we are going to focus on GraphQL: What is GraphQL, How is GraphQL different from REST APIs, and testing GraphQL APIs. Finally, we shall also delve into some of the cross-functional testing strategies like load testing.

Table of Contents: The Definitive Guide to Testing GraphQL API

  1. You’re here → Introduction and getting started with GraphQL
  2. Testing GraphQL APIs
  3. Cross-functional testing of GraphQL APIs – Coming Soon

What is an API?

Let’s step back and understand how most of the online transaction happens. For instance, users want to get things done online at a button click. Rather than going in-person to buy a movie or flight tickets, or to shops to purchase an item. In other words, the user is a Client, and the application (web or mobile-app) needs to fetch data that’s stored remotely in some database that’s accessible over the internet, which is, in this case, it’s a server.
Client and server communication

Most of these communications happen via APIs behind the scenes. API is a messenger that accepts a request and says a system what you want to perform and then returns the response back to you. Furthermore, the API development is not new, and it has been around for many years now, and the technologies evolve so does the way to create APIs change too.

Firstly we’ve seen SOAP-based services that dominated in the 90s. Secondly, REST has been dominating for more than 10 years. Thirdly and most importantly, we now have GraphQL that has various advantages over the ways mentioned above for creating APIs. Facebook developed GraphQL due to increased mobile adoption, under low-power devices and poor network coverage. Let us understand, what is GraphQL?

What is GraphQL?

GraphQL is an API specification standard and an Open-Source data query and manipulation language. It has a server-side runtime fulfilling those queries along with the data. In other words, GraphQL follows WYAIWYG pattern What You Ask IWhat You Get. GraphQL allows declarative data fetching where a client can specify what data it needs from an API.

Facebook invented GraphQL, and now it is maintained by a large community of companies and individuals all over the world. GraphQL is a specification and, users shall create their implementation on different platforms conforming to the specification. Therefore, Netflix Open-Sourced their implementation called Falcor. An easy example for folks coming from Test Automation world, it is like WebDriver being a W3C Specification, Selenium and WebDriverIO are its browser automation implementation.

GraphQL has two parts:

  • A Server component, a GraphQL server to accept the incoming requests and send back data precisely.
  • A Client component, to send a POST request (with payload) to the GraphQL server.

GraphQL uses a type system to define the capabilities of an API. All the types declared in an API are written in a schema using the GraphQL Schema. Namely, Schema Definition Language (SDL). It serves as a contract between the client and the server to define how a client can access the data. Defining the Schema allows the back-end and front-end teams to concentrate on their piece of work without much communication.

GraphQL WorkFlow

GraphQLs workflow is very simple and in three parts namely,  Describe, Ask and Get predictable results. Let’s take a look at it using a very simple scenario by fetching (request) a data via GraphQL that will hit the server, and we get back the response.

  • Firstly, you would use the declarative syntax to query the data you’d need from the client to the server. In this case, as you see the query is on the left-hand side and is self-explanatory, trying to fetch the movies name, that’s how simple it is. Anyone can understand the request that we send to the server-side.
  • Secondly, the GraphQL would generate the payload based on the query and as you see on the right-hand side, it has a JSON response with data on it.
  • Finally, the server sends the payload back to the client and the data gets displayed onto the Client (The picture is just a representation of the movie name The Matrix)
    GraphQL Workflow

Developing a GraphQL API revolves around three main concepts. Firstly the Schema. Secondly, the Queries and thirdly the Resolvers. We shall deep-dive into these concepts shortly. But before we jump on those concepts, it would be beneficial to understand the differences between GraphQL and REST API.

GraphQL vs. REST API

Both REST and GraphQL, are useful for developing APIs and it is manageable over HTTP.

  • Data Fetching: Data fetching is one of the most significant improvements in GraphQL when compared to REST. GrpahQL is a query language, and your query (request) when triggered it precisely responds with the expected data, no extra information gets retrieved. Whereas, with a REST API, you’d usually retrieve the necessary information by accessing multiple endpoints. In other words, no more over and under fetching of data. GraphQL gives you precise data.How requests are done via GraphQL and REST API
    The diagram above depicts fetching data from a REST and GraphQL API. With REST API, you need to use three different endpoints to fetch the required data. On the other hand in GraphQL you’d send a query and GraphQL responds with exact data. More information is available here.
  • Data Operation: In REST API, each resource is represented with an endpoint, and it’s apparent to end up having multiple endpoints. The data fetch done using the CRUD (Create, Read, Update and Delete) operation via multiple endpoints. Whereas, In GraphQL, everything perceived as a graph and it’s connected and represented as a single endpoint. It also has unique features like Query, Mutation and Subscription.
  • Versioning: In REST API, it is prevalent to see APIs have a different version like v1, v2 and so on. In GraphQL, there’s no need since it is based on Schema and users can quickly mark those types as deprecation for the fields that are no longer needed. This also saves a huge time in back and forth testing on different versions of the same API.
  • Architectural differences are shown below:
    Architecture difference between REST API and GraphQL

There are much more differences between these two APIs. So I’ve summarized it in a table format for you to take a look and understand:

GraphQLREST
ArchitectureClient-DrivenServer-Driven
DesignBased on HTTPBased on HTTP
SpecificationSchema Definition LanguageMultiple Specs (OPEN API)
DataFetch data through a Query LanguageData available as resources over HTTP via URI
Data TypeStrong Type ChecksMultiple Types Formats
PerformanceFastSlower (over fetching and multiple network calls)
VersioningDeprecation of TypesVersioning of APIs allowed
OperationsQuery and MutationsCreate, Read, Update, Delete
PayloadJSONJSON
CommunityFast-growing, back by Linux FoundationWell Established

Why GraphQL?

The reason why? The fact Facebook created GraphQL is an exciting story in itself and is available here as a documentary.

One of the problems that Facebook wanted to solve is the speed and user experience of facebook.com. After a few ideas, the team came up with two main mantras that would work. The team started working towards achieving them, namely As little as possible, as early as possible and Engineering experience in service of user experience. They achieved this by, unifying the fetching of code and data in one single GraphQL query—the GraphQL’s ability to ally the request and minimizes network usage is outstanding. You could read more about this journey here.

GraphQL is promising and evolving by the adoption of a large group of companies rolling out GraphQL in production. However, there is definitely, few caveats in this new modern API design too like caching, Authorization, Error handling, n+1 problems. And there are ways to navigate through these problem areas.

Let’s jump in and take a look at some of the core concepts unique to GraphQL.

Core Concepts of GraphQL

I’ve developed a GraphQL server component and Open-Sourced here. We will be primarily be using this Source Code to go over a few important concepts as well as look at the main, Testing aspect too.

  • Schema: As we discussed above, Schema serves as a contract between the client and the server to define how a client can access the data. It’s simple to understand what types your API is going to have and understand by a look of it, as it’s human-readable.
  • Types: Types are the most important concepts of GraphQL. It is a custom object and depicts how your API will look. Types have fields and these fields return a specific data type. In our example, Movie and Actor are two different types that contains fields for querying like name, age, genre and returns a type of data as Int, String, ID, List and a few more. The exclamation mark denotes that the field is mandatory or non-nullable.
    type Actor {
         id:String!
         name:String!
         age:Int
         movies:Movie
      }
    
      type Movie {
         id:String
         name:String!
         genre:String
         actor:Actor
      }
  • Query: In simple terms, queries are ways to get data from the server. No more over or under fetching, you get what exactly you ask. It is a read-only fetch operation. In the REST world, queries are equivalent to how you’d use Request with a payload to get a response from the server. In our example, the schema allows the users to query for four different types of data:
    • A Movie with a valid ID.
    • An Actor with a valid ID.
    • To fetch all the Movies, that returns a data type LIST.
    • To fetch all the Actors, that returns a data type LIST.
      type Query {
           movie(id: ID): Movie
           actor(id: ID): Actor
           movies:[Movie]
           actors: [Actor]
        }
  • Mutation: The way you are going to modify data on the server. The mutations are equivalent to how you’d use the CRUD operation along with Verbs such as GET, POST, PUT, PATCH and DELETE in the REST world. In GraphQL it will always be a POST call. It is a write followed by fetch operation. In our example, as you can see the two mutations that we have are for Creating a Movie that should return a new Movie for us and Creating an Actor that should return a new Actor.`
    # MUTATIONS
    
       type Mutation {
       addMovie(id: String!, name: String!, genre: String): Movie
       addActor(name: String!, age: Int!): Actor
       }
  • Resolvers: A collection of functions that generate a response for a GraphQL query. There is a protocol to follow like, the function name will have the same name as the Query type. In a nutshell, the Resolvers act as a GraphQL query handler. In our example, the resolve function is shown here below that would help fetch the movie.
    movie: {
             type: MovieType,
             args: {id: {type: GraphQLID}},
             resolve(parent, args){
                return Movie.findById(args.id);
             }
           }
    
  • Subscriptions: An important feature for GraphQL, subscriptions allow the server to send data to its clients when a specific event happens. This could be a useful concept to implement, say when a user adds a review for the movie, you’d get notified by the server. We’ve haven’t implemented this in our example, but I hope this gives you an idea.
    subscription {    
        movies {    
            id    
            name    
            genre    
            actor{
               name
            }    
        }
    }

Outro!

Congratulations! 🎉 You’ve made it up until here. Thank you for your patience. I hope, by now you are aware of GraphQL core concepts and able to answer some of the key questions like the How, What and Why of GraphQL, and understand the differences between REST vs. GraphQL.

To summarize, GraphQL was invented having the cons of REST in mind, but GraphQL is very flexible and you can still have your architecture that can include GraphQL and REST together.

Testing your code is always important, that is often left as an after-thought process. The tests would help prevent some bugs also, give you the confidence on the piece of functionality developed would work as intended. Testing GraphQL APIs are quite different and not the same way as you’d be doing for the other API patterns (REST or SOAP). GraphQL API can be tested in a number of ways with supporting tools and editors.

In the next chapter of this tutorial series, we will deep-dive and look at what to test for in the GraphQL APIs, and how to do the same using Open-Source libraries. Stay Tuned! 😉

Avatar

About the author

Manoj Kumar

Manoj Kumar is a Principal Consultant at ThoughtWorks. Manoj is an avid open-source enthusiast and a committer to Selenium & Appium project. And a member of the project leadership committee for Selenium. Manoj has also contributed to various libraries and frameworks in the automated testing ecosystem like ngWebDriver, Protractor and Serenity to name a few. An avid accessibility practitioner who loves to share knowledge and is a voluntary member of the W3C ACT-R group. In his free time, he contributes to Open-Source projects or research on Accessibility and enjoys spending time with his family. He blogs at AssertSelenium.

Join TestProject Community

Get full access to the world's first cloud-based, open source friendly testing community. Enjoy TestProject's end-to-end test automation Platform, Forum, Blog and Docs - All for FREE.

Join Us Now  

Leave a Reply

popup image

Best In Class Java and C# SDK

Join thousands of automation developers using TestProject to supercharge open source testing, with a Selenium and Appium SDK, supporting Java and .NET Core (C#)!
Sign Up Now right arrow
FacebookLinkedInTwitterEmail