What The Heck Is GraphQL?
GraphQL has taken this industry by storm, but what is it exactly? In this special episode of the Ladybug Podcast we’ve invited 14 GraphQL experts from the community to educate us on all things GraphQL!
0:00 / 0:00
What The Heck Is GraphQL?
Shout out to our sponsors for supporting the LadyBug Podcast!
Sanity.io is a platform for structured content that comes with an open source editor that you can customize with React. Sanity.io also comes with tooling that lets you build with structured content in React, Vue, and other frontend technologies like Svelte. It also has powerful APIs for reading and writing so that you can use the same content across any device, channel, or product. You also get powerful APIs for querying your content, you can even listen for changes in real-time, and use the write APIs to patch and make new documents from code. You can get started for free on the standard plan, and add a credit card to pay as you go for usage over the generous standard quotas. If you need advanced features like SSL and Single-Sign-On you can find all the prices and details on Sanity.io’s fully transparent pricing page. Listeners of the Ladybug Podcast get a extra special plan with double the usage. Go to sanity.io/ladybug or use “ladybug” where you fill in the coupon code.
Are you a developer looking for your next challenge? Meet Shopify. We’re on a mission to make commerce better for everyone - but we do things a bit differently. We don’t tell people how to solve problems - we give them the tools, trust, and autonomy to build new solutions. We don’t work alone - we leverage the diverse perspectives across our teams in everything we do. And we don’t have all the answers - we’re big enough to tackle problems at scale but small enough that we haven’t figured them all out. If you’re a builder at heart who wants to solve highly technical problems. If you want to take all of your life experiences and apply them to a blank canvas. Or if you want access to really powerful tools - Shopify is the place for you. Visit shopify.com/careers today.
2:00 - What Is GraphQL? (Erin Fox)
8:21 - Benefits Of GraphQL (Akshar Takle)
11:19 - History Of GraphQL (Brian Douglas)
14:01 - Syntax (Chris Biscardi)
17:01 - Schemas (Kurt Kemple)
20:02 - Variables (Swyx)
24:24 - Fragments (Emma Wedekind)
25:36 - Directives (Jon Wong)
32:10 - Toolkit (Alan Johnson)
38:49 - React Hooks & GraphQL (Shruti Kapoor)
46:13 - GraphQL vs. REST (Chantastic)
49:20 - When NOT To Use GraphQL (Zach Lendon)
54:37 - Useful Tools For Learning/Using GraphQL (Manjula Dube)
1:01:27 - Making GraphQL Development Easier With Hasura (Rajoshi Ghosh)
1:05:06 - Wins!
Molly Struve After struggling for 4 days to debug a problem she figured it out and contacted the software creators to update the docs!
Nominate A Ladybug Podcast Guest!
Want to nominate yourself, or someone else, to be on the Ladybug Podcast? Fill out our nomination form to let us know!
- Understanding GraphQL
- Sacha Greif’s GraphQL Article
- Babel Blade Plugin
- ESlint GraphQL Plugin
- Is GraphQL The Future?
- Shruti Kapoor’s Hooks & GraphQL Repo
- GraphQL Editor
- GraphQL Playground
- Hasura’s GraphQL Tutorials
Help us out
Ali [0:00] There’s so many different paths that your career can follow in the tech industry. You can be a software engineer, a QA engineer, a UX engineer, manager, developer advocate, and even more. So in this episode, we’re going to explore a lot of those paths. And let’s go ahead and get started.
Kelly [0:00] Before we jump into the episode we wanted to address some of the changes will be making to this podcast. One of our hosts Lindsey Kopacz has left the team for personal reasons and we wish her all the best.
Additionally, we are going to start having guests on some of our episodes to discuss the things they’re passionate about. If you would like to nominate someone or yourself to be a guest on the Ladybug podcast, we created a Google form for you to do so just visit our website at Ladybug.dev and go to our contact page. We’re really excited about the changes to the podcast and we hope you are too.
Now this week’s episodes extra special. All three of us love GraphQL. But we recognize we’re not experts in this area. So we decided to ask the community for their help on this episode. So during this episode, you’ll be hearing from 14 different programmers from the GraphQL community on a variety of topics. There’s a lot to cover and we have a ton of resources for you. So be sure to check out the episode page on our website at Ladybug.dev for full transcript and a list of resources mentioned in this episode. Now let’s jump in.
Welcome to the Ladybug podcast. I’m Kelly.
Ali [1:05] I’m Ali.
And I’m Emma. And we’re debugging the tech industry.
So let’s start from the beginning here. What exactly is GraphQL? And you know, what are its components? So we’re going to kick things off with Erin Fox, who’s going to give us this introduction to GraphQL.
Erin Fox [1:58] Hello, I’m Erin Fox, a software engineer soon to be starting at an exciting new company that I’ll be announcing very soon. Most recently, I was working at Major League Soccer in New York City on the mobile UI team focusing on creating and launching their React Native app for thousands of soccer fans. We use a lot of great technologies including React Native and GraphQL with Apollo,
I tend to speak at a handful conferences on the side and a couple blog posts every once in a while on things that I’m learning. I’m excited to chat today about one of those things: what is GraphQL. It took me a good chunk of time to understand it. And once I did, I really loved it and really enjoyed the developer experience of it. I eventually wrote a blog post about it called Understanding GraphQL. Finally, while back I even made a GraphQL API Beyonce API, or I like to call it my baby API. So let’s get started.
What is GraphQL? GraphQL got its start by the people at Facebook; they created it to have a single endpoint that can take in complex queries and then update or shape the data output into whatever shape the client requires. And there’s a lot of definitions on what GraphQL is. My favorite one is straight from the documentation.
GraphQL is a query language for API’s and a runtime for fulfilling those queries with your existing data. It provides a complete description of the data in your API gives clients the power to ask for exactly what they need, and nothing more. It also makes it easy for API’s to evolve over time, which I think is one of the huge benefits. So GraphQL, because there’s always something new in this industry. And we always need to be able to evolve and update our apps. So it has a lot of information. Let’s break it down. A little more simple, like describing things more simply.
So there’s two things. It supplies the client with exactly what it needs from the data. And it makes it really easy to collect data from multiple sources. Really what it is it’s a layer that lives between the client and one or more data sources, receiving client requests, and fetching the necessary data according to the instructions that you’re giving them.
My favorite analogy is from Sacha Greif’s GraphQL article, he described GraphQL as a trusty assistant, because who doesn’t want to personal, just the assistant with you? GraphQL is that so you need to tell it to go pick up your lunch, you need to swing by the laundromat to pick up your clean clothes, maybe even go to the grocery store to pick up your favorite frozen treats, all at the same time really fast. You just need to tell this trusty assistant aka GraphQL, what to get and where to go get it.
So in order for all that to happen, there’s three essentials needed, a schema, resolver, and some queries. So let’s start with schema. Schema shows how to get the data and what type of data so it’s where the types are defined. It’s kind of like Flow or TypeScript. So you define your data types here. And when I mean types, I mean a string an integer, a boolean, an id, etc. It’s important to know your backend system to know what’s a string, what’s an empty array. And to know what data is available to you, that will make it a lot easier to create your schema. So just to reiterate, the schema shows how to get the data and what type of data it is.
Second one query. This one’s my favorite. Query returns data these are asked for. So with the query, you’re able to write out exactly what you need. And you get back exactly that. The query has the same format as a result. I love the graphql.org quote, it says, “this is essential to GraphQL because you always get back what you want, what you expect, and the server knows exactly what fields the client is asking for.” There’s also loads of fancy things to add here queries, there’s aliases, fragments, variables, mutations. in mind fragments, highly recommend checking out the documentation on this if you’re really ready for this fancy stuff. also recommend checking out the GitHub GraphQL API
It’s a lot of fun. It’s all set up for you to use Graphiql, which is really laid out simple to kind of practice your queries and even use your own API for the sorry, the GraphQL API to hit your own GitHub stuff. So really fun and a great resource that I recommend. So quick rephrase on query, returns the data that’s been asked for and returned only that data. So it does return JSON, not just one huge object only a small one with the data that was asked for by the client.
Lastly, we have our resolvers sub three. So how does this personal assistant know which burrito place to grab lunch for me or where my dry cleaners is located? You have to tell it where to go and what to get. So similarly, you guys will server won’t know what to do with an incoming query unless you tell it using a result. So in the field is defined in the resolvers it tells GraphQL how and where to fetch the data. The results come back resolved. I’m doing air quotes around resolved on how you want it structured.
Sacha Greif also quoted, “a GraphQL server won’t know what to do with an incoming query unless you tell it using a resolver.” So we had our queries our schema and resolvers to make up kind of our GraphQL layer with client calls and request.
So in conclusion, GraphQL can be used with any back end framework or programming language. In my opinion, it’s really fun and fast. And once you understand it, you start to realize how cool and how great of a developer experience it is. GraphQL is a syntax that describes how to ask for data and is generally used to load data from a server to one client. If you don’t remember any of this, remember these three things. It let’s the client specify exactly what data it needs, makes it easy to aggregate data from multiple sources, and it uses a types of some to describe data. Wrap that all up you got some schemas, you got a schema, queries and revolvers, and I’ll leave you with that. This great quote from graphicalql.org “apps using GraphQL all are fast and stable because they control the data they get, not the server.”
Thank you so much to Erin for that great introduction to GraphQL. She got into some other really great benefits of using GraphQL. But I’m going to turn it over to our next guest, Akshar to talk more about those benefits.
Akshar Takle [8:21] Hi, my name is Akshar. I’m a software engineer at Zillow Group. And what that means is that I write front end code for Zillow Rental platform. So what are the benefits of GraphQL? The first thing that comes into the mind is that GraphQL introduces proper data fetching, more than that and mobile applications are extremely data driven. We often need to fetch combined hand deliver data from various data sources using RESTful APIs. We have been doing this by making multiple network calls to get the data by using GraphQL. We can hit just one endpoint and GraphQL server takes care of resolving data from different sources.
Another thing that GraphQL solves is over fetching or under-fetching of data. In RESTful API is you can retrieve data that is only specified in the resources. If you want more or less data, you need to have separate resources or endpoint which is a tedious task. Using GraphQL, you can dynamically change the query according to your need and retrieve the exact required data. You can also see increase in real and perceived performance. Because we fetch only the required amount of data, no more or no less. We can also combine multiple requests into one which reduces the network overhead.
Another thing that GraphQL brings with it is the speed of development. The rate with which we can iterate and prototype is much faster than what we can do with the RESTful API. It is no longer necessary to specify data requirements on the server side, such as which fields from which models need to be faced and exposed. For GraphQL, you define the schema, which is the model. This completely changes the way we interact with data. Now because of the way GraphQL is designed it offers enhanced security over RESTful API is for two main reasons.
First, it has a strongly typed schema, which means that data validation takes place and there cannot be any SQL injections of wrong type. Second, ability to precisely define the data that client needs. There’s avoiding unintentional data need.
Sometimes we need to refactor the code. GraphQL brings more confidence during this process. GraphQL statically analyze the query which allows us to set up linting rules and detect schema changes. What this means is that you can ensure that new schema is reflected in your queries and mutation. For example, if you wish to rename some food in the schema, you can rename it, run the linter and know exactly what part of code is going to break. And finally, you get improved developer experience that GraphQL. developers need to think less about how to fetch the data. You can simply declare the required data along with your UI. It’s amazingly convenient to consume data this way, because it sits right next to the UI.
Emma [11:04] Thank you so much option for your introduction to some of the benefits of GraphQL. So now that we know some of theee things GraphQL can do for you, why don’t we learn a little bit more about where it came from? I’m going to turn it over to Brian to tell us about the history of GraphQL.
Brian Douglas [11:19] So Brian Douglas developer advocate at GitHub. The original GraphQL spec actually started in 2012. Co created by Lee Byron, Dan Schafer, Nick Schrock, had an issue where they were creating a new version of the Facebook mobile app. And one of the biggest lifts was actually migrating the News Feed API. Yeah, if I get that correctly at the News Feed API into GraphQL into the mobile app, they found that the newsfeed API was actually kind of a mess. Leveraging normal REST API practices, I believe REST API or XML one of the two.
Facebook is an old technology from early to mid 2000s. So, long story short, they successfully leverage this sort of query language and GraphQL. Well call GraphQL. Just test out and launch this Facebook mobile app.
A couple years later, 2014 decided to go ahead and open source the spec for public usage and get some feedback as well, some help in the open source. So they actually recreated a newer version of it, the version that we see today in the spec and open source that until like developer, publicly alpha, back in 2015. Around that time, GitHub, got real excited about that, and actually leverage that to the for the next version of the API to solve a couple of problems GitHub has for public API. Moving on a little bit further GraphQL, gained a lot of adoption around the time of the first GraphQL Summit in 2015. So it’s the fall. The original release was in the spring time / winter time, I’m not actually quite sure when actually the official pre alpha launch was. And so today GraphQL is being leveraged by a lot of different companies like Twitter, Facebook, of course, GitHub, Airbnb.
Kelly [13:34] Awesome, thank you, Brian, for that brief overview of the history of GraphQL. It’s, it’s interesting, you know, talking about the the quick adoption, and it’s it’s exciting to see, and it is also kind of funny thinking about Facebook as being old technology, but it’s true. And regardless of how we all feel about Facebook these days, we do have them to thank for GraphQL so very interesting story. Next we’re going to hear from Chris Biscardi, talking about GraphQI syntax.
Chris Biscardi [14:01] Hi, I’m Chris Biscardi. I’m an independent consultant that focuses on helping early stage startups based on open source software. Some of my recent work includes adding themes and MDX to Gatsby. Let’s talk a little bit about GraphQL. syntax.
There are two main syntax associated with GraphQL: the query language and schema definition language, the query languages and syntax used to query a GraphQL server and get results back. While the schema definition language is used to talk about GraphQL schemas and a language agnostic way. The SDL can also be used to build the types for GraphQL server. Although at scale, some people end up using a more resolver based programming language dependent methodology. The SDL represents GraphQL schemas and can come with a number of scalar types out of the box. We can use floats, strings, booleans or ids by default. Ids are strings and are meant to be opaque to the user in are used to read fetch data.
Many GraphQL implementations also provide additional custom scalars like date, which takes arguments that will you tell the server how to format the output, most of the time will want to create an object types using the scalar types. An object type defines a name of our type, and what fields we can query on it. To define a character type, start with a keyword type than a name like character, the capital C.
From a GraphQL server, which action we’re taking is typically the first key word in the GraphQL query, query mutation, or subscription respectively. After the initial keyword GraphQL queries are typically named with a Pascal case word like Person query with a capital P capital Q to differentiate one query from another.
At this point, a query can declare any variables that it wants to use in the rest of the GraphQL query. After this comes the selection set, which starts and ends with curly braces. The selection set is a list of field names that we want to return on any given object. If a field returns an object, we must add more sub selections to that field until we return a scalar type. Each field can potentially take a number of arguments dictating anything from how to format a date to how to sort the results. These arguments and the fields available to select are dictated by the server’s GraphQL schema.
That was a great introduction to how to start writing GraphQL by Chris! Let’s transfer it over to Kurt to go even more in depth on how to start writing GraphQL schemas.
Kurt Kemple [17:00]
Hey, I’m Kurt Kemple, co-host the Full-Stack Heaelth podcast and developer advocate at AWS and today, I’m going to talk to you about GraphQL schemas. The GraphQL schema definese the functionaity and data available to clients. To make it easy to understand the capabilities of a GraphQL server, GraphQL implements a human readable schema syntax known as it schema definition language, or SDL. SDL is used to express the types available within a schema and how those types relate to each other.
Types provide a wide range of functionality within a schema including the ability to create relationships between types, like say between a book and an author, and define which queries used to fetch data and mutations use for data manipulation can be executed by the client. Scalar types are the base types of a GraphQL schema and they represent the leaf nodes of a schema and always resolve to concrete data. The default scalar types within GraphQL int: assign 32-bit integer, float: assign double precision floating point value, string: UTF-8 character sequence, Boolean: true or false, an ID, that unique identifier often used to refresh an object or as a key for cash. This gets serialized as a string, but it’s not meant to be human readable.
Another very common type is the object type. This is probably the most common type using a schema and represents a group of fields. Each field inside of an object type maps to another type, allowing nested types and circular references. Another important type is the query type. A GraphQL query is used for fetching data and compares to the get verb in REST-based API’s. In order to define what queries are possible on a server query, type is used within the SDL.
Another common type is the mutation type, mutations or operation sent to the server to create, update or delete data. These are comparable to the put post, patch and delete verbs on a REST-based API. Much like how the query type defines the entry points for data fetching operations on a GraphQL server. The root level mutation type specifies the entry points for data manipulation operations.
Now that you know how to query for data and update data and have a basics of scalar types and object types, sounds to me like you’re good to go on just what is a GraphQL schema. Thanks, everybody.
Emma [19:41] Thanks so much, Kurt, for that awesome introduction to GraphQL schemas. Schemas are something that I’ve always struggled with. I’m not sure what it is. But I think you did a really great job breaking it down. So now that we know about GraphQL schemas, let’s learn a little bit more about variables. I’m going to turn it overe to where to Swyx to give us this introduction.
Hi, this is Swyx, and work on developer experience at Netlify, and recently wrote an article on the common trends behind design systems, TypeScript, Apollo GraphQL and react and CSS tricks.
The way GraphQL variables work is best envisioned by how you would use it inside the Graphiql tool. Let’s say you are querying the name of a user with an argument of ID one, we give this query a name of get user, your query would be a simple string on the top left of Graphiql, however, you don’t want to hard code the ID of one since in your app, you might change this around. So the answer is to make your names query itself, take arguments, and then pass those arguments down to whichever field takes those arguments. Think of it like making a function that takes arguments and calls another function with those arguments. To turn a basic hard coded query into a dynamic one with variables you have to do three things.
First, replace the static value in the query with $1, sign and then variable name. So for our example, we replace one with dollar ID. Second, you declare the variable as one of the arguments accepted by the query. GraphQL is strongly typed. So you also have to provide the variables type of front, as long as indicate required argument with a bang, or exclamation mark. So for our example, after the named get user query, we add open parentheses dollar ID, colon, ID, which is the type exclamation mark close parenthesis, third and final step. You separately pass in the variable name, Id value, one in a JSON object to your graph your client library. In Graphiql, this is the sometimes hidden bottom left panel. So just to recap, top left has your query which doesn’t change and bottom left has you query variable, which does change.
For huge apps like Facebook. This made a material difference to their speed. Because upload speeds are typically much slower than download speeds, especially on mobile devices. This is a best practice called persistent queries. You can find more by googling around, think of going to your local diner and instead of ordering two all beef patties, special sauce, lettuce, cheese, pickles onions on a sesame seed bun every time. You just say you have the usual persistent queries are awesome and only possible because of GraphQL variables.
I find GraphQL variables to be super fascinating and kind of confusing, but Swyx did a wonderful job walking us through that. So thank you. And Swyx actually created a video to go alongside his description of GraphQL variables. It’s super helpful. So we’ll link to his article in our resources section. So be sure to check that out. Now next we have a very special guest to talk to us about fragments. And I’m just kidding. Okay, she is special, but she’s not a guest. She’s our very own Emma. So Emma, talk to us about fragments.
Thanks, Kelly for the introduction. So fragments are pretty straightforward. Let’s say we have a pretty complicated app. And let’s say we’re querying for a bunch of different dog breeds. Well, I kind of want the same fields for each breed of dog. Let’s say I’ve got Dalmatian and Australian shepherd. And I’m going to want to grab the breed, the age, their name, the owner, and the owner’s name on all of my different dog breeds. It would be pretty tedious and pretty redundant if I had to query for all of these fields on every query that I did, wouldn’t be great if I could write at once and then kind of just use those fields and each of our queries?
Well, that’s where fragments come in. Fragments let you construct sets of fields and then include them within queries wherever you need them. So let’s say we have dog fields. And here I want to query for the name, the breed, the age and the owner’s name. And then if I have a Dalmatian query and an Australian Shepherd query, I can simply spread the dog fields onto both of these queries. And I just have to declare it once. So fragments really are focused on reducing redundancy and allowing you to create a bunch of different queries on the same type of data really easily.
So now that I’ve just showed you a little bit about GraphQL fragments, I’m gonna turn it over to Jon to tell you a little bit more about GraphQL directives.
Jon Wong [25:36]
Hello, my name is Jon Wong. I’m a staff software engineer at Coursera and education company obsessed with transforming people’s lives with access to the world’s best education. We have almost 4000 courses from universities and enterprises all around the world. And our latest product means you can get degrees like an MBA, and even a master’s in computer science from the comfort of your own home. Check it out some time and let me know what you think.
Today I’ll be talking to you all about GraphQL directives. Directives are annotations that can exist both in GraphQL queries, as well as the GraphQL schema itself, and can be attached to types and fields and other sorts of constructs within graph to all itself. Developers can use directives to provide extra metadata about the execution of GraphQL. Directives typically look like the at symbol followed by the name of the directive. It’s a pattern that in other languages might be called a decorator. We’ll talk about the kinds of directives you might see in a typical GraphQL project starting with graph field queries. The two most common directives you’ll find are included in the GraphQL’s specification itself. Both of these are included in client site queries, and are closely related. The two directives are named include and skip and are opposites of each other. They each take one parameter named F, which has the Boolean type. This allows a client to declare conditional fields in a GraphQL query and use a runtime variable to choose whether or not to include or skip that particular field.
When it comes to the server side, a GraphQL server that’s implementing the GraphQL specification, and uses the GraphQL schema definition language must also implement a dedicated directive, a useful way to annotate parts of the GraphQL schema that should no longer be used. The one and only parameter based on the spec is a parameter called reason, a human readable string for developers trying to figure out what why this particular field cannot be used. Many linting tools such as eslint-plugin-graphql, can link GraphQL queries to warn against the use of deprecated fields. And with a little bit of configuration, you can even warn against the removal of fields that have not been already marked with the deprecated directive. However, that’s not all that directives are capable of. One has the ability to design and build custom directives to guide the execution of a GraphQLquery. I’ll go through a few examples of powerful client side and server side directives that might pique your interest on the client.
One of the more notable directives is the client directive at client. This is a directive defined by the Apollo link state library and generally is available as part of the local state management features that are a part of Apollo itself. The clients directive allows Apollo to strip certain fields in the query before sending the request. And that allows client side resolution of those fields when the response is returned from the server. Semantically, this might feel a little odd as you’re effectively adding new fields to the schema on the client side. But this is a very powerful way of allowing GraphQL to be a one stop shop for all your data, whether it’s local or remote. Typically, a custom client side directive requires some tooling and the GraphQL client itself in order to understand the directive that you’re providing. But since the field and this particular directive are going to get stripped, we don’t actually need the server to know anything about this directive.
Another really awesome client side directive is the deferred directive, which tells the server to go ahead and return a response early before the annotated field has finished resolving. Meanwhile, whenever the server does actually resolve resolve that particular deferred field, it can go ahead and push the results of the client when it has the opportunity. This allows for clients to still declaratively establish what data that they want, without having to pay the runtime cost of loading the entire query on the server before the first response gets returned. Finally, in the GraphQL schema definition language, also known as SDL. Custom directives are used from everything to establishing authorization rules, all the way to hinting at how long that particular fields can get cached. Custom directives on the server require both a declaration in the GraphQL schema definition language to determine what fields and types that they can be attached to. And they also need a runtime definition available to the server itself. All in all directives are really solid way for anyone using GraphQL to provide more information to the GraphQL execution engine, either on the client or on the server to get more fine tuned behavior,
I’ve got to say that that was probably the most comprehensive overview to GraphQL directives that I have ever seen. Thank you so much, Jon, for that really deep dive into directives.
Before we continue on, let’s hear a couple words from our sponsors.
Sanity.io is a platform for structured content that comes with an open source editor that you can customize with React. We made one for Ladybug, and it is gorgeous. Sanity.io comes with the tooling that lets you build structured content and react view and other technologies like spelt. It also has powerful API’s for reading and writings that you can use the same content across any device, channel or product. You also get powerful API’s for querying your content, and you can even listen for changes in real time and use the right API’s to patch and make new documents from code. It is super cool, and I’ve been so impressed while playing with it. This week, we’re even refactoring the Ladybug website to use Sanity.io. You can get started for free on the standard plan and add a credit card to Pay As You Go for usage over the generous standard quotas. If you need advanced features like SSL and single sign on, you can find all the prices and details on Sanity.io’s fully transparent pricing page. Listeners of the Ladybug podcast, get an extra special plan with double the usage. Go to sanity.io/Ladybug or use Ladybug wherever you fill in the coupon code.
Are you a developer looking for your next challenge? Meet Shopify. They’re on a mission to make commerce better for everyone. And they do things a bit differently. They don’t tell you how to solve problems. They give you the tools, trust and autonomy to build new solutions. They don’t want you to work alone, their structures, you can leverage the diverse perspectives across teams in everything you do. And they don’t pretend to have all the answers. They’re big enough for you to tackle problems at scale, but small enough for you to discover and solve new problems. If you’re a builder at heart who wants to solve highly technical problems, and you want to take all of your life experiences and apply them to a blank canvas. Or if you want to access really powerful tools. Shopify is the place for you. Visit shopify.com/careers today.
Now let’s shift gears and talk a little bit more about GraphQL toolkit. And I’m going to turn it over to Alan to do that.
Alan Johnson [32:11]
Hi, everyone. My name is Alan Johnson and I’m a full stack engineer at the moment I’m on a brief short break, but I’ll be joining better calm and a couple weeks as engineering manager. So to talk about GraphQL, what really attracted me to GraphQL as a system is that it was advertised to solve problems that I had experienced myself in building applications, such as designing RESTful APIs that don’t lead to either massive over fetching or under fetching.
I assume that most people are going to be familiar with these, these concepts. So I’m not going to get too into the problems that I saw GraphQL solving, but suffice it to say, I saw a lot of promise in the technology. I follow GraphQL as a concept from a distance for a couple years before I finally had a chance to put it into practice, as I knew would be a big lift to implement, and also a bit of a learning curve.
Eventually, I had the chance to start using it in practice at a previous job. And I just kept running into this issue a mismatch of my mental model of what I thought GraphQL was, and the reality of how it works as a system, it’s both probably know the defining kind of document of any GraphQL system is it schema, I was thinking of the schema as kind of exposing the data model of the the back end of a system, almost like a schema does and in database. But this was causing me all sorts of issues because it’s actually rather awkward to directly model data in your schema. In GraphQL, if you’re used to doing it in a in proper, in some sense data modeling languages, like SQL Jason, XML or ven your languages on Native data types and systems for making data structures.
But things began to click for me when I realized the GraphQL fields, which are kind of the building blocks of the system. And the schema are that they act really more like remote function calls, after all the even take parameters. So to get a bit technical, there are two types of fields. There are scalar fields, which represent chunks of data. So think like strings, and numbers, but it really could be any type of concrete data. And then there are object fields, which are actually the the interesting part of GraphQL. To me, what they do is they don’t return data themselves, but they provide access to further sets of fields, which might be yet more object fields or scalar fields. So they’re kind of like the junction points in a GraphQL request.
And then GraphQL requests are kind of like individual programs that a client asks the server to run. And then the server returns the result of of that program. They’re missing a few things that we think of programming languages, such as looping, and obvious branching. But if you squint hard enough, it has a lot of the same aspects is like a simple scripting language. But most of the literature around GraphQL however, is kind of about requests for fetching data. So you can think of it is, is being that most of the usage of GraphQL is about programs that just are for returning big chunks of data. But what I’m trying to get across is that GraphQL could actually be a lot more interesting than that.
So to draw a parallel with with CSS, which is many listeners know is the subject of a couple earlier Ladybug Ladybug episodes. It’s kind of like how CSS was designed to give the early web design language for doing the sort of text layouts that we see in like newspapers or textbooks. But eventually, the field kind of moved on to building interactive applications with it with complex layouts and transitions. I think GraphQL has a similar potential for, for being capable of doing a lot more than what people think it’s designed for. And I’m really hoping that this gets explored in more detail in the coming years. So I’m going to leave it at that for now. There’s actually a much more deeper argument that made or I guess a more in depth argument, and if you really want to dig into it, I wrote a piece called is GraphQL, the feature for the artsy engineering blog when I work there a couple years ago. So I hope this is thought provoking for people and thanks. Thank you very much to the Ladybug team for inviting me to share these thoughts on their podcast.
Thank you, Alan. That was super insightful. And we’ll link to Allen’s article in the resources section of the episode on our website. I highly, highly recommend you give the article read. It’s a bit lengthy, but it’s a it’s a very good read. So if you have some time, you know, make yourself a cup of coffee and sit down and read through his thoughts here. It’s super fascinating.
So next, we’re going to hear from Shruti Kapoor. And I’m really excited for this one because React hooks are super fascinating to me. And I haven’t had too much of an opportunity to actually use them yet. So yeah, so Shruti is going to be talking to us about React hooks, what they are and how you can use them with GraphQL with managing the state of your app.
Shruti Kapoor [38:49]
Today I’m going to be talking about React hook and how can we use them to manage state and craft your application. So let’s start off by talking about what are hooks. Hooks are a new addition to React and version 16.8. They were proposed in October 2018, and released four months after in February 2019. And they’re hugely popular today. The main selling point of hooks is that it lets us state and a function component which wasn’t possible before. So as you know, there’s two types of components in React functional and class. So previously, to use state you would need to have a class component. These are the components that have that begin with component extends react component. So let’s say you were using a functional component before and you suddenly realized that now you need to use React state. What you would have to do is convert your function component which has component adjusting the state, but now with the addition of hooks, you can call state in a component that has no life cycle methods, that is a function component.
OK, so now moving on to the four types of hooks that I found very useful for state management in a GraphQL application. The four hooks that are commonly used was use state, use effect, use reducer and use context.
So let’s start with use state. I used to use state as the name describes the previously you would initialize and the constructor of the class component. And you would initialize state by state equals an object. And you would call a life cycle method like componenet did mount and update the state they’re typically by using the starts at state. But because in a function component, you don’t have access to lifecycle component, you will not able to use the state. But now with the help of use state, you can call you can do the same things as this.state and the sad state by calling use state. So you do something like const count set count equals useState(0). This is taken directly from the documentation.
So use state returns you a state variable and a setter, the state variable is count and the center is set count. So if you want to get, you want to update the value of count, you would simply do set count to our set count for it’s just a function.
Now let’s talk about use effect. Use effect is the hook that can be used to do side effects such as subscriptions, calling an API, doing the cleanup, things like that are doing dumb manipulations. The work that you do here is similar to the work that you would do in a in a component mount lifecycle method or component update or component will mount.
Now that then we have use reducer It is similar to what a reducer does, and it’s similar to use state in the way it works, except it returns a dispatch method in addition to the state variable, so you can use this dispatch method to call actions.
And lastly, we have use context, which is similar to context API, if you remember. So it has a provider button and subscribe button so you would call the context API at the top level of the component where you want to have access to context and then all of the children components without access to context using use context hook.
Okay, so now, I am going to walk you through an example of how to implement GraphQL API using hooks. If you want a working example, you can head over to my GitHub. github.com/shrutikapoor08/hooks-graphQL. I leave the link in the show notes.
Okay, let’s start by initializing the initial state for the application. So we’re gonna, we’re going to initialize the state have this initial state and maybe a new file. Now the second step is to pass the initial state to use reducer. So we’re going to initialize use reduce or a hook by passing in the initial state. When you call use reducer, it spits out a dispatch function. This is going to come in handy later on when we need to update all the state. So now think of the component that should be the main components such that all children component can share state. This will be your top level component. This is where you’ll be setting up your context subscriber by passing into dispatch, that is just got from use reducer.
Now, once you have hooked this up with context subscriber, all of the children components will have access to the top level state, they can all update the state by dispatching actions. So now figure out where do you need to hook up the GraphQL API, and whatever component you need to hook up the GraphQL API, use the use effect hook for this.
So now once you call the graph, your API would say it’s a query, you have an access, you have access to data in your hands. And now you need to update the global state, but this data so you can do that by using use reducer to update the global state store in context. Once you update the global state, which you did, by calling dispatch functions, this is actions you can use use context to get this data in any component you want. Now you can use your state wherever you need to have local component state like forms are checkboxes. So, in summary, we use for hooks. We used use reducer, used use hook, use context, and use state.
So we used to use reducer to call to set up dispatch functions. We use dispatch to call actions, we use the context subscriber at the top level component where we had set up our top level state. We also set up initial state in the beginning. And then we used use context to get this global state. And whenever we wanted to update the state we got use reeducer, we started fighting actions to use the desert. And we use use state to have local component state. Again, if you want a working example of this, you can head over to my GitHub at https://github.com/shrutikapoor08/hooks-graphQL.
So if you want to use hooks right now in your applications, you can use it out of the box starting React version 16.8. If you are using client side libraries for graph keywords such as Apollo client, Apollo client will have access to hooks as the box starting Apollo client 2.6. If you’re using any other client-side libraries, you can still use React hooks, just make sure your React version is 16.8 or above. That is all I have for now. Thank you so much for your time. If you do have any questions, please reach out to me at shrutikapoor08 on Twitter. Bye.
Every time I hear more and more about React hooks, I just want to use them for everything. So cool. I love that tangible example of actually using GraphQL integrated with another technology that is super hot right now. I also want to transition into talking about GraphQL compared to some other things. So I’ve been reading REST API’s for a really long time. I know a lot of you all probably have to. And so what’s the benefit? Why do we write GraphQL instead of rice? And is one always the right answer. Let’s go ahead and talk to Chantastic about his thoughts.
Hi. I’m Chantasic. And I host a weekly tech show called React Podcast. I’m here to talk about REST vs GraphQL. I’d like to start with an analogy. Imagine this. I’m in a car with my wife and two kids. We’ve been in the sun all day and it’s time for dinner. I want a burger. Nellie wants something Mediterranean. Rock wants pizza and Ruby wants mac and cheese. For the sake of my analogy, let’s consider just two possible outcomes and eliminate options like throwing a bunch of granola bars in the air and yelling dinner is cancelled. Option one, we go to four different locations to fill each request individually. We go to a burger place Mediterranean place a pizza place and a place that has mac and cheese. Option number two, we go to one location with all of the options. Think of a food court, I give everyone 10 bucks, they order what they need, and we then share our varied meals together.
This is how I think of REST vs GraphQL. REST API’s expose types through discrete endpoints. If I want data from multiple endpoints, I have to make a trip to each one individually. GraphQL gives you a single endpoint. From there, I make my request for exactly what I need a burger, a kebab, pizza, mac and cheese.
Now breaking away from the analogy the single endpoint design of GraphQL has some great side effects for teams. Your requests use a proper query language, while REST uses query parameters and URL segments which are ultimately decided on by the implementing developer GraphQL gives you a standard way to pass arguments. And you can specify these on any field or nested object. In GraphQL, because you request only what you need, you can avoid getting unnecessary data with your request, which can prevent a lot of discussions about how to optimize certain endpoints.
This all culminates in a much nicer boundary between clients and services. When you need do data, you don’t need to work with the backend team to design a new endpoint. You simply expose new object types and fields. boom, done. No API design discussion required.
One last thing. We’ve been saying REST vs GraphQL. But they’re not competing solutions. If you already have a REST API, you can wrap it with GraphQL; you don’t have to convince the suits on a big breaking change to your API. Just start doing it a better way.
Can we just take a second to admire that analogy that Chantastic just gave us because not only is this voice captivating, but that was probably one of the best analogies I have ever heard. with anything. So shout out to you for that one. I mean, who doesn’t love burgers, pizza and mac and cheese? If I could find one place that serves me all those things, I would be there every day. So while GraphQL has a ton of benefits, it seems really intuitive to us. And we’ve heard a lot of great things. It might not be the right solution for your team or your project. I’m going to turn it over to Zach to tell us a little bit more about maybe why we shouldn’t use GraphQL.
Zach Lendon [49:19]
Hi, I’m Zach Lendon, and I’m a founder of Crucial development. We are on the web at crucial.dev. We are a software consultancy, that specializes in delivering API and graphical solutions at scale. For some of the world’s largest financial retail medical brands. seem I think it would be a bit awkward for me to talk about why GraphQL is not the answer. After all, I was initial championing architect for Brookfield Hilton Hotels back in 2017. And I love the technology so much, and I made a focus what my company does.
But as software engineers, we have a responsibility to leverage the right technologies at the right time and place to deliver solutions for our clients or employers. But ultimately, delight customers kind of think it should be a place nothing GraphQL is not the right solution. And that’s okay. To me there’s two main areas and ways with GraphQL to get sold.
Traditionally, it is as a modern backend for your front end. Stop repeating business logic and each native mobile and web application, maximize the performance of those applications and enable those application teams to iterate quickly to deliver value to customers.
The second way I want to mention is using GraphQL further down the stack to aggregate server side resources. As organizations have realized the system’s performance and development agility benefits of not over and fetching data, they have ventured and using GraphQL, often over REST for inter service communication with their microservices architecture. This approach has had enough traction where it’s even made that works tech radar for 2018 as an assess technology quite pattern, so let’s quickly dive into a few reasons to give you and your team’s pause for using GraphQL.
In these two paradigms. caching is one common area where rest API’s have traditionally been far superior to GraphQL patterns. And you have a GraphQL detractor in your team, they’d be wise to bring this up first, API gateways, edge solutions. They are just examples of architectural areas that have years of product experience supporting rest based caching, caching, mapping certain URL patterns, HB methods or specific resources, common ways to somewhat mitigate within Greco all this is, is having caching exclusively beneath your GraphQL layer as I think Facebook does. Or of course, some of the handful of edge solutions using say e tags or basketball, for example. But you are likely to run into some challenges here that you’re going to need to mitigate.
One nice benefit of GraphQL is it acts to decouple front end applications and backend system architectures. But for some organizations that may not only be fine, but it may be appropriate if you’re a small company, but it’s a credit application for internal use, the performance benefits of GraphQL may matter less for you. And the benefits of leveraging a rest paradigm that was built with credit principles, you know, get post put, delete, and HB status quo to tell what happened with all that will likely not be outweighed. This is as good a point as any to bring it up.
REST API is can support rudimentary patterns for excluding and including fields and responses to counteract some of the world’s most prominent benefits. And GraphQL usually adds architectural complexity. And our scenarios like these were none of the benefits are receiving in return. And yes, let’s be clear types queries, mutations resolve urs new client libraries. There’s a nonzero cost to using what too many will be new technology, but they have to understand to maintain over time.
Another area where GraphQL may not be right for your organization is with legacy applications. Well can seem compelling to gradually introduce GraphQL into those applications, it’s important to understand how much the benefits of GraphQL will will matter for these applications. For example, how much will performance actually improve? So guess, do PCs and measure it and measure the impact of converting an application versus the applications lifespan and what the impacts might be to manage the application during this transitory period. For me, this is where I was at early proponent of my girlfriend and architectures were like applications can be killed off in pieces over time. That won’t always make sense. I’ll give you exercises like this with the idea of a CIO test.
Namely, imagine you need to sell this to a technology leader that focuses on areas like organizational agility, technical excellence, and culture. The use case or cases for GraphQL should be so compelling that not using it seems unimaginable. Going back to my Hilton experience, GraphQL was the only technology all the architects agreed on for digital transformation initiative. That fandom though was one out through PCs that proved its advantage with hard metrics for real world use cases. Being able to decide on whether or not to use GraphQL by taking real numbers, formats budget impact team velocity impact, and not have them be theoretical. That’s what not only sells when to use GraphQL, it also sells when not to use GraphQL. Make decisions like these based on data, record those decisions and be willing to reevaluate them over time, as new information becomes available.
Thank you, Zach. I think this is a really important topic that we should be discussing. So I’m really glad that this was covered. As Zach said, you know, the technology that you might want to use for an app or for a project, it might not be the best fit for what the customer actually needs. And while we can talk up GraphQL, as much as we want on this episode, you know, it’s not always right in every situation. So I think there’s a lot to take away from that. So next, we’re going to hear from Manula today, she is going to be talking to us about useful tools for working with GraphQL.
Manjula Dube [54:37]
Hello, everyone, I’m Manjula Dube. Before I introduce more about myself, I would like to thank you for having me on this podcast. Thank you so very much. A short intro about myself. I work as a web engineer at in 26 here in Berlin. I’m additionally from India and been walking with the new startups from past four years and now I work at N26. I love my job. I basically work with React and GraphQL these days, and I’m in love with GraphQL. So to say about, I am also a public speaker, and I organize meetups. I’m one of the organizers of React India this year happening in September. So today we are going to be talking about GraphQL editor, Graphiql and GraphQL playground by Primsa.
So I’ve never used visual editor. But visual editor is sort of a visual editor as the name suggests, which kind of gives you a visual code editor and it basically makes it easier to understand your GraphQL schemas which are really difficult, so it sort of basically gives you a UI where you can view your theme schemas in a much easier manner.
Not be used to it. But what from what I know is it automatically generates a fake package. So that’s one of the cool features, I mean, so you can immediately start working with your project.
One cool thing it has is live collaboration, which makes it easier to sort of work online with, you know, your other teammates on the same project. So it’s more like code live editor, you know, which you can share with your teammates so that you know, both of you can work together. One of the cool thing it also has is, you know, you can basically make notes while building the schema. So, this comments basic, this comment system basically allows you to make the notes for other users while working on your schema. This is one of the cool thing, this also improves the collaboration between the teams if you’re working on a particular project. So this is a good thing.
And what it also has is, you know, it basically has a map of your entire system. So the Graphiql editor is a great tool when it comes to managing and navigating to large schemas in your project. So you know, if it creates a map it it is kind of giving you a structure where you can navigate to any of the schemas or data that you’re looking for. So this is one of a cool thing, I think using graph, Graphiql. And it’s more like in browser ID for exploring graph given. If I have to compare Graphiql and GraphQL playground, I would always suggest GraphQL playground, but before I moved to Graphiql, playground and then tell you more about the pros and cons.
I would like to tell Graphiql comes with syntax highlighting type fields, arguments and type documentation and model it also has like real time editor highlighting. So which is good. So, kind of I have used this in the past but recently I switched to GraphQL Playground which is fed by Prisma. So this is more like an another IDE which helps managing subscription dogs and collaborations. So some of the features which are really good and you know, I haven’t been able to find it in Graphiql is more like interactive, multi column schema documentation. It also has automatic schema reloading. So this is one of the cool thing. It has support for GraphQL subscriptions. Also one of the cool thing is it, it always has your query history. So you know, whenever you want to go back to the previous query, you can just look around and you know, your things will be saved in your history. And he definitely has like, several tabs. That is why when you need to go to the previous tab, you can definitely go the previous tab.
That’s it. So, you know, these are some of the cool things which I really like about GraphQL playground. And if I have to talk about some of the pros of using GraphQL Playground or Graphiql, well, I would say tabs are very much, you know, beneficial. So, you know, if you have something which venue where you can run your queries, and those queries are there in different tabs, it’s, it’s easier to manage. Also, query browser easier to navigate back and forth. So that’s what that’s what I thought. It has dark mode, we all love that mode. And there are also some customization options for the editor. So you can customize it as you want.
One thing to tell you is that you know GraphQL Playground is actually built using the components of Graphiql under the hood but is meant as more powerful GraphQL IDE because of certain features it has which we already discussed. So it still gives us Graphiql under the hood but some of the cool features which they have added on the top of it in the GraphQL Playground makes it more easy. It makes it more easier to use and that is why people love you know GraphQL Playground over Graphiql. And yeah, that’s it. So if you have any questions you can write me back I usually read about React and GraphQL. So that’s it. Thank you so much.
There are a lot of great community solutions to making GraphQL development, easier process. But there are also some companies starting up who are creating custom and very awesome GraphQL solutions as well. So we’re going to hear from Hasura and hear what they’re doing in order to make GraphQL development process even better.
Rajoshi Ghosh [1:01:26]
Hi, I’m Rajoshi. I’m one of the founders at Hasura. As a founder I end up wearing many hats, but I focus a majority of my time working with the developer community. I co organizer GraphQL Asia which is an annual conference in Bangalore. The next one’s coming up in February in case anybody wants to apply, as well as the GraphQL meetup in San Francisco, which we are reviving this September and in 26 September’s the next meetup. And along with some of the really amazing folks in the GraphQL community, we also recently launched an Open Source GraphQL series for all major front end frameworks. This is available on learn.hasura.io.
I would like to spend the next few minutes introducing you to Hasura. Hasura is one of the open source tools in the GraphQL. We launched the project about a year ago, and have seen some amazing traction and love from the community. And that’s really helped us grow over the last year. So that is predominantly a tool to bootstrap your GraphQL back end, it also generates your GraphQL server and since it’s open source, you can host it anyway.
Going into a little more detail, there are three main parts to answer. The first one is that it gives you an instant real time GraphQL API on a new or existing database. It comes with a UI or like a dashboard that helps you set up your GraphQL API. You can also hook Hasura into an existing database. Today we have a deep integration with Postgres databases, and get instant API’s on your existing data.
The second part to Hasura is that you can react to changes in your database called web hooks or external API’s or service functions on demand. And the third and final part of us is that you can stitch custom GraphQL API’s and other data sources into a unified GraphQL API.
So imagine that you have like customer data in your database, but the payment information isn’t straight. You can use our solar to fetch information from your database and stripe using a single GraphQL query. It takes about 15 minutes to try us route. And we have a super friendly community of developers and discard. In case you get help and you get stuck and need help. When we are building new features to Hasura, one of our guiding principles has to do with making GraphQL book in a more cloud native environment where teams already have or are moving into using microservices and service GraphQLwhen it was designed, you know had kept the monolith in mind and it really works well with monolithic architectures, because it’s essentially a shared type system across your API in a cloud native setup.
However, APIs and that types of spread across different servers. graphical subscriptions are hard because web sockets estate fall and don’t work easily when services are to scale and go up and down frequently, making GraphQL mutations event driven in a way that works coherently with the rest of the GraphQL API is a challenge to I’m very excited to see what kind of patterns emerge over the coming months and years and how these problems get solved. And I’d love to chat more about you know, your GraphQL architectures, how you use it, if you’re using it with Microsoft’s architecture. You can reach out to me at Twitter on Twitter, my teams are open.
Thank you so much for everybody at Ladybug podcast for having me on the show and have a great day.
I hope today’s episode taught you a ton about what GraphQL is, how to use it and the ecosystem surrounding it. I want to give a huge shout out to all of our guests. I learned so much just from creating this episode. And hope you did to go ahead and follow all of our guests on social media. We have them all organized in the show notes, they are great resources on GraphQL and beyond.
And before we go we just wanted to take a moment to thank our incredible sponsors for today: Log Rocket, Sanity.io and Spotify.
Sponsors allow us to continue producing the show while showcasing some incredible technologies and opportunities. So thank you again to our sponsors.
Ali I also want to give a quick shout out to a listener when so Molly Struve after struggling for four days to debug a problem figured it out. And then she also contacted the software screener to help them update the docs. Congrats Molly.
If you liked this episode, tweet about it. We select one tweeter each week twin Ladybug stickers. We post new podcasts every Monday. Make sure that you subscribe on your podcast listening system of choice to subscribe and be notified. Also leave us review