DEV Community

Cover image for Demystifying GraphQL Queries
Jaden Baptista for TakeShape

Posted on • Originally published at takeshape.io

Demystifying GraphQL Queries

It's hard to learn new things, isn't it? When I first started to learn Python, it looked like an indiscriminately shuffled string of stray symbols. But eventually I learned; I connected it with concepts I knew from other languages. Later on, I learned JavaScript and went through the same thing; I didn't understand the syntax, so it just looked like a bunch of meaningless characters to me. But once I saw the similarities with languages I already understood, it started to click. I originally had the same reaction to GraphQL queries. It seemed difficult at first, but I came around after I realized the key to learning it was just like the technologies I'd learned before, and now I use it almost every day.

I'm just like every other developer: I want to learn new things but sometimes struggle with remembering the details and grasping the why of it all, so I figured I'd write this post to explain where I started with GraphQL and how I got to where I am now.

Step 1: Conceptualize the thing

I can't get anything done until I can work out what's happening in my head.

Me figuring out something new

Me figuring out something new

I'm grateful though that someone explained GraphQL to me as REST adopting the baby of JSON and SQL. GraphQL is declarative, meaning that you get back what you ask for. No more, no less. When writing a GraphQL query, we're using a syntax that is similar to JSON or a TypeScript interface to define what information we want to get back in our response. Just like how we'd use SQL to define what data to retrieve from a database. Except instead of directly accessing a database with SQL, with GraphQL we're telling an API what information we're looking for.

My lack of understanding was the result of seeing GraphQL in action before knowing why someone would use it in the first place. At the time, I had been working on my own attempt at standardizing API responses in JavaScript, so GraphQL was really right up my alley; I just didn't know it. Once I understood that GraphQL could tackle the problems I was having, I realized it that I had to start learning the syntax. That takes me to step 2...

Step 2: Learn the thing

Once I wrapped my mind around the why of GraphQL, I had to grasp the how of GraphQL. There's a fantastic quickstart tutorial on the official GraphQL website, but I'll just show the basics:

  1. Types. Say you want to get some user account information, but you want it to conform to a certain spec. Let's imagine that you want get their first and last name (both strings), their age (an integer, in years), their username (a string), and whether they're subscribed to your newsletter (a boolean). In plain JavaScript, this would be tough (or at least lengthy) to check manually:

    // assume we've got everything in an object called "data"
    if (
        (typeof data.first_name != "string" && data.first_name != null)
        || (typeof data.last_name != "string" && data.last_name != null)
        || (typeof data.age != "number" && data.age != null)
        || (typeof data.username != "string" && data.username != null)
        || (typeof data.subbed != "boolean" && data.subbed != null
    ) return "invalid";
    

    Let's be honest, that's a bit excessive, isn't it? It's technically best practice, and in theory, it allows each field to be either its assigned datatype or null. It just doesn't scale though. Having this after every API request gets old fast.

    GraphQL forces the API to define those datatypes, so you're guaranteed to get back what you're expecting. If the API says that first_name will be a String, it will come to me as a string or null. I can count on that in my application. They can even rule out null too, by making the datatype String! with the exclamation point. On their side, they're defining a type like this:

    type User {
        first_name: String
        last_name: String
        age: Int
        username: String
        subbed: Bool
    }
    

    Again, the API does all of this, so we don't have to. We can just count on what's coming in and out.

    When you start working with more advanced GraphQL queries, you might end up implementing types on the client-side too! Check out the types docs here on the GraphQL website for more information.

  2. Queries. We talked about guaranteeing what types of data we'll get with GraphQL, but now we actually have to get that data, and we do it with queries. This is the part I was talking about when I said it looks like JSON and SQL. You just kind of give it the keys of the JSON object you're looking for, and it'll fill in the values, similar to how SQL fills in the data once you give it the columns you're selecting.

    Say you're trying to retrieve user data from an API mesh like TakeShape, and it's set up so you can trust that the data you get back conforms to the type up above. A query for that would look something like this:

    {
        getUser (id: f8a5123b9705c8c618043dc206b09c6a) {
            first_name
            last_name
            age
            username
            subbed
        }
    }
    

    You just give the GraphQL API the keys to the JSON object, and the API will just fill in the values. You can nest this too; say we had the user's first and last name in a nested object. The query might look something like this:

    {
        getUser (id: f8a5123b9705c8c618043dc206b09c6a) {
            name {
                first
                last
            }
            age
            username
            subbed
        }
    }
    

    GraphQL is powerful enough to reach down into these nested objects and make sure that everything conforms to the type defined by the API. This way we don't have to worry about getting the wrong information or trying to do all that manual validation in JavaScript anymore.

    This isn't my any means all the things you can do with GraphQL, but it's enough to get by on, especially if you're just consuming a GraphQL API like the one TakeShape's API mesh provides. If you're fascinated by the possibilities here, I'll point you back to the detailed guide on the official GraphQL website here.

Step 3: Use the thing

This is the part I struggle with the most. Finding the time and the right opportunity to use a new technology can be a challenge.

After conceptualizing something new, and learning the syntax, I want to jump head first and start using my newly earned knowledge on a big new project! But, alas, I know that wouldn't be wise. It's best to start tinkering on a low stakes project. I decided to start simple with a starter blog using TakeShape's GraphQL API. Playing in this sandbox was like learning Python again. Just pressing buttons, trying new things, and experimenting with different ideas. It wasn't planned or scripted, and there wasn't any particular thing I wanted to make; I was satisfied just exploring what I didn't know before.

That's the crux of my advice to anyone who is still having trouble demystifying GraphQL queries: just tinker. Experiment. Build something. Anything. You don't have to work it into some polished portfolio-worthy project; you just have to go beyond understanding the why and the how and get to actually using GraphQL.

I hope this guide helped you to go through the same journey with GraphQL queries that I did: conceptualizing it, then learning the syntax, and then using it in a project. I wouldn't call myself an expert, but I think I'm a better developer for having gone through the process I outlined here, and I hope you'll feel the same. If you're looking for a place to dive into GraphQL more, I've littered this article with links and references to the official GraphQL guide and TakeShape, an easy-to-use example of a GraphQL API.

If you have any questions, feel free to reach out to me at jaden@baptista.dev.

Top comments (1)

Collapse
 
arvindpdmn profile image
Arvind Padmanabhan

Those new to GraphQL can also learn how to migrate their REST APIs to GraphQL: devopedia.org/rest-api-to-graphql-...