Graph QL
Graph QL
Why GraphQL
RESTful APIs follow clear and well-structured resource-oriented approach. However, when the
data gets more complex, the routes get longer. Sometimes it is not possible to fetch data with a
single request. This is where GraphQL comes handy. GraphQL structures data in the form of a
graph with its powerful query syntax for traversing, retrieving, and modifying data.
type Student {
id:ID!
firstName:String
lastName:String
fullName:String
college:College
}
type College {
id:ID!
name:String
location:String
rating:Float
students:[Student]
}
GraphQL vs REST
REST offers us a standard way to interact with domain objects in terms of URL familiarity,
statelessness, and HTTP verbs. However, GraphQL gives engineering teams a level
of semantic standardization (and validation!) that is hugely beneficial. Knowing how to build
components against common data shapes accelerates UI development and makes fixing bugs
and extending our applications quicker and easier.
Until recently, it was extremely likely that the APIs you designed and consumed were REST APIs.
Now, the landscape has changed, and popular services such as GitHub, Facebook, Pinterest, and
even Starbucks are using GraphQL. As a developer, you may be faced with designing an API at
work and have the choice of implementing a REST or GraphQL service. But how do you choose?
Both have their advantages and disadvantages, so it is essential to understand these when
deciding what technology to use.
Summary of GraphQL Advantages
REST
REST is an acronym for ‘Representational State Transfer.’ It is a stateless and uniform format
that decouples the client from the server.
REST is initially fairly simple to implement and uses the HTTP transport layer to support
creating, reading, updating, and deleting data (CRUD).
Each operation in REST is characterized via an endpoint. For example, you may want to retrieve
a user from your API, and you might have an endpoint like this:
/api/users/1
This tells the server that you are requesting the user resource and want to select the user with
the identifier 1.
In principle, this is pretty straightforward and very easy to reason with. You may, however, be
able to see where issues can arise.
With a system of any complexity, you need to make multiple requests to get the data you need.
For example, let’s say you have a user, and the user has photos. You have two ways to
approach this as a developer:
GraphQL #
GraphQL offers many advantages over REST, especially because it removes the multiple
endpoints issue. Instead, graphQL has a single endpoint which allows you to declaratively tell
the API what you want.
Using our previous example of retrieving a user and their photos above, we would simply do
the following in GraphQL:
query {
user {
name
photos {
id
path
}
}
}
Now, in a single request, we have retrieved our user and their photos. But what else do you
notice?
We have only retrieved one field from the user. We do not need their ID, their email, or any
other information, so we do not ask for it.
This results in a much smaller payload and returns exactly what we need. Nothing more,
nothing less.
Don’t worry if this looks a bit confusing right now. In the next few lessons, we will learn how a
GraphQL schema is structured and how to work with it.
With all that said, GraphQL is no silver bullet and introduces its own complexity and issues. We
will explore some of these and how to mitigate them in a further lesson.
This really depends on your use case. Neither REST nor GraphQL are better than one
another. They simply work differently.
If you are concerned about retrieving exactly the data you require and want a more declarative
way to consume your API then I would recommend adopting GraphQL.
If you are happy making multiple trips to retrieve data and are conscious of the tradeoffs of
designing endpoints to meet specific use cases, then stick with REST.
One of the advantages of GraphQL is that you can adopt it incrementally or even use it as a
wrapper over a REST API. This does not need to be a final decision, but it is worth exploring the
pros and cons of each.
A good API is created the most through considered design and less through the specific
technology stack.
The code below demonstrates a simple GraphQL schema with a User type and a Photos type.
We then add a resolver, which allows you to return data for both types.
Example :2
The core idea of REST is the resource. Each resource is identified by a URL, and you retrieve that
resource by sending a GET request to that URL. You will likely get a JSON response, since that’s
what most APIs are using these days. So it looks something like:
// GET /books/1
{
"title": "Black Hole Blues",
"author": {
"firstName": "Janna",
"lastName": "Levin"
}
// ... more fields here
}
Note: In the example above, some REST APIs would return “author” as a separate resource.
One thing to note in REST is that the type, or shape, of the resource and the way you fetch that
resource are coupled. When you talk about the above in REST documentation, you might refer
to it as the “book endpoint”.
GraphQL is quite different in this respect, because in GraphQL these two concepts are
completely separate. In your schema, you might have Book and Author types:
type Book {
id: ID
title: String
published: Date
price: String
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
books: [Book]
}
Notice that we have described the kinds of data available, but this description doesn’t tell you
anything at all about how those objects might be fetched from a client. That’s one core
difference between REST and GraphQL — the description of a particular resource is not coupled
to the way you retrieve it.
To be able to actually access a particular book or author, we need to create a Query type in our
schema:
type Query {
book(id: ID!): Book
author(id: ID!): Author
}
Now, we can send a request similar to the REST request above, but with GraphQL this time:
// GET /graphql?query={ book(id: "1") { title, author { firstName } } }
{
"title": "Black Hole Blues",
"author": {
"firstName": "Janna",
}
}
Nice, now we’re getting somewhere! We can immediately see a few things about GraphQL that
are quite different from REST, even though both can be requested via URL, and both can return
the same shape of JSON response.
First of all, we can see that the URL with a GraphQL query specifies the resource we’re asking
for and also which fields we care about. Also, rather than the server author deciding for us that
the related author resource needs to be included, the consumer of the API decides.
But most importantly, the identities of the resources, the concepts of Books and Authors, are
not coupled to the way they are fetched. We could potentially retrieve the same Book through
many different types of queries, and with different sets of fields.