GraphQL is a query language and runtime for APIs developed by Facebook that gives clients the power to ask for exactly what they need. This post covers GraphQL fundamentals including schemas, queries, mutations, and subscriptions, how GraphQL compares to REST APIs, and why it has become popular for building flexible, efficient APIs for modern applications.
GraphQL Overview
What exactly is GraphQL? GraphQL provides a different way of quering our servers for data. GraphQL specifies how our frontend should talk to our backend APIs and how the backend APIs should be built to respond to GraphQL messages. GraphQL is a language that we use for quering a query language. That's what the QL in GraphQL is short for. Party of the beauty of GraphQL is that it allows you to focus more on your data and how different pieces of data in your server relates to each other. With GraphQL, you always start by describing your data with a schema. For example, if our API is serving data on different open source projects, we might describes that we have projects with names, taglines and a list of contributors to define these schema.
GraphQL has its own type system.
Notice that name and tagline are string, and our contributros is a list of users where a user is another object like our project with its own properties because we can make GrpahQL servers using any programming language. We can't rely on the types provided by TypeScript or Java or any other language with types. GrapQL will make sure that our data has the right shape by using above JSON syntax for all of the data that we're storing with our schema defined, we can queries where we ask for the piece of data that we want,
we ask for data using this javascript like syntax, which lets us query our backend much like we query a database. And this example, we're looking for a project and specifically we're interested in the tagline for that project, GraphQL queries are basically just about selecting fields on an object. So we're selecting the tagline field from the project object and we can pass in arguments as well, asking not just for any project, but the specific one whose name matches the string GraphQL. So how does it help us? Because the shape of our GraphQL queries here matches really closely with the object that we expect in the result, we can predict what our query will return, including the exact fields without knowing about how the data is stored in the server. The result of our query is the JSON object with exactly the data that we asked for. GraphQL is a query language for APIs. That's what GraphQL is.
But at this point, you might be aksing why, why is GraphQL necessary when we've already seen that REST and our existing backend patterns work perfectly well, whatever application it is that we're trying to build. So why is GraphQL so exicting? There has to be a reason why Facebook originally went through all the effort of creating it for their own platform and why alot of different companies have started using GraphQL. As developer, it has the potential to completely changes how we build backend and APIs and how we interact with those backend.
GraphQL vs REST
How does GraphQL differ from our typical RESTful API. How it is better?
There is two main problems that single GraphQL endpoint source, which is over fetching of data and under fetching of data to understand what this means. Let's explore one practical example where GraphQL really shines. A perfect use case for GraphQL is in e-commerce applications, for example, online stores.
Imagine, for example, that we're building amazon.com. We need to build an online store that lists products, allows us to view product details, add products to our shopping cart, make orders and review products that we've purchased. This is a common set of reqirements when you're building e-commerce applications, on the product listing page, which shows aa list of all the products in some category, or maybe all the products matching some search criteria. At the bare minimum, our frontend clients would need to make a get request against some products endpoint. If we doing research, endpoint might possibly take some parameter to filter the products for a specific category. But one way or another, we definitely need that product endpoint. We also need to list the product details when someone clicks on a product to buy it. So, we need to be able to query for an individual product by ID. And our product detail page might include an option to add to cart and also to view existing customer reviews and mybe even add our own review that might be structured as a get tot the reviews collection for a specific product ID.
Let's summarize how does GraphQL compare to REST and RESTful APIs. The truth is that REST is very good. It has alot going for it. It's stateless, which allows us to create clusters and scale our servers more easily. It has named resources or end point that are usually easy to navigate, and it follows the HTTP protocol, which the web is based on very closely. What GraphQL has going for it includes, that we don't under fetch data. RESTful APIs require multiple round trips to our server to get data from different collections. With GraphQL, it all comes from a single endpoint in a single request. And because of GraphQL flexible query language, which lets us select exactly which data we want returned back from the server we prevent over fetching. GraphQL query language allows our frontend clients to query our backend, our server, almost like they would a database and much like a database GraphQL gives us schemas and type. Shemas describe our data and make it easy to discover to understand what data is available in our API. And types, ensure that the data that's being passed backend in our queries is valid. We're not passsing a string where an integer is expected. And last but very much not least for large scale projects, GraphQL speeds up development.
GraphQL Advantages
- No under-fetching
- No over-fetching
- Schemas and types
- Speeds up development
GraphQL also comes with some disadvantages. The flexibility of our queries adds some complexity. Remember, GraphQL still works over the HTTP protocol using our POST request to our GraphQL endpoint. GraphQL just add another layer on top of this, which means now our frontend developers need to understand GraphQL queries as well. And on the backend, you need to invest a bit more time to do the initial setup for GraphQL to define all your schemas and types for really small applications, this might not be worth the effort. GraphQL is difficult to cache. One of the big benefits of the RESTful approach is that the responses from our end point tend to be fixed.
GraphQL Disadvantages
- Flexibility adds complexity
- Difficult to cache
- Not RESTful
GraphQL in Node.js
- npm init -y
- npm install express
- npm install graphql
- npm install express-graphql
Create server.js and paste below code on your local:
How would we add graphQL to our fancy new node server? It's already built in, so we just need to enable it by passing in an option to our GraphQL middleware like below:
Resolvers
Every large scale graphical server has to main components, schemas and resolvers. We already know what is the schemas. But what is a resolver? The answer lies in what happens when we make a query. GraphQL always first determines if the query is valid by looking at our schemas and then it executes that query. When executing a query, the value of each field is determined by calling a function called a resolver. When a field is included in our query, the corresponding resolver is called to provide the value for that field. When the server has called all the resolver functions found in the query, it then wraps all those values up and sends them back to the front and back to the client that asked for the data in the first place.
So, why do we need these resolver functions anyway? What problem do they solve?
In above code, we've been using these root values to determine what data comes back from our APIs. But these root values points to our models that contain hardcoded data, like our orders model.
orders.model.js
Which isn't realistic.
When we need to do an API call, a database query or some other logic to get the data for one of our fields. One of these fields from our graphQL schema.
Instead of using hardcoded root values, we use functions that we call resolvers graphical calls. We fetch the data that we need in our resolver function, and the data gets sent back to our clients. So, we can update our makeExecutableSchema function like below:
When we're passing in some root values, the parent starts out as being that root object, so to return the products resolver. We could just return parent.products and the value from the root will be returned when graphQL calls.
args is used when we have parameterized queries, for example, when we want to filter our products based on some condition.
context is useful for data that's shared across all our different resolvers. for example, if we want to pass down authentication data about which user is logged in to everyone of our resolvers.
info contains some information about the current state of our operation. Because many of these arguments are only used in advanced cases will often see them excluded from our resolvers.
Frequently Asked Questions
What is GraphQL?
GraphQL is an open-source query language for APIs and a server-side runtime that allows clients to specify exactly what data they need, returning only that data in a single request — solving over-fetching and under-fetching problems common with REST APIs.
What is the difference between GraphQL queries and mutations?
In GraphQL, queries are used to read (fetch) data while mutations are used to write (create, update, delete) data; both use the same GraphQL syntax but mutations signal that they will cause side effects on the server.

