0% found this document useful (0 votes)
57 views8 pages

Graph QL

GraphQL is an open-source query language developed by Facebook that allows clients to define the structure and relationships of the data required and receive only the specified data in a single request. It provides an alternative to REST APIs by allowing clients to fetch related data from multiple sources in one roundtrip to the server. GraphQL queries return predictable results and restrict the data fetched from the server, making applications using GraphQL fast and stable compared to REST.

Uploaded by

Jithin M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views8 pages

Graph QL

GraphQL is an open-source query language developed by Facebook that allows clients to define the structure and relationships of the data required and receive only the specified data in a single request. It provides an alternative to REST APIs by allowing clients to fetch related data from multiple sources in one roundtrip to the server. GraphQL queries return predictable results and restrict the data fetched from the server, making applications using GraphQL fast and stable compared to REST.

Uploaded by

Jithin M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

GraphQL

GraphQL is an open source server-side technology which was developed by Facebook to


optimize RESTful API calls. It is an execution engine and a data query language.

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.

Ask for what you want − and get it


Send a GraphQL query to your API and get exactly what you need. GraphQL queries always
return predictable results. Applications using GraphQL are fast and stable. Unlike Restful
services, these applications can restrict data that should be fetched from the server.
The following example will help you understand this better −
Let us consider a business object Student with the attributes id, firstName,
lastName and collegeName. Suppose a mobile application needs to fetch only
the firstName and id. If we design a REST endpoint like /api/v1/students, it will end up fetching
data for all the fields for a student object. This means, data is over fetched by the RESTful
service. This problem can be solved by using GraphQL.
Consider the GraphQL query given below −
{
students {
id
firstName
}
}
This will return values only for the id and firstname fields. The query will not fetch values for
other attributes of the student object. The response of the query illustrated above is as shown
below −
{
"data": {
"students": [
{
"id": "S1001",
"firstName": "Mohtashim"
},
{
"id": "S1002",
"firstName": "Kannan"
}
]
}
}

Get many resources in a single request


GraphQL queries help to smoothly retrieve associated business objects, while typical REST APIs
require loading from multiple URLs. GraphQL APIs fetch all the data your application need in a
single request. Applications using GraphQL can be quick even on slow mobile network
connections.
Let us consider one more business object, College which has the attributes: name and location.
The Student business object has an association relationship with the College object. If we were
to use a REST API in order to fetch the details of students and their college, we will end up
making two requests to the server like /api/v1/students and /api/v1/colleges. This will lead to
under fetching of data with each request. So mobile applications are forced to make multiple
calls to the server to get the desired data.
However, the mobile application can fetch details for both Student and College objects in a
single request by using GraphQL.

Describe what’s possible with a type system


GraphQL is strongly typed and the queries are based on fields and their associated data types. If
there is type mismatch in a GraphQL query, server applications return clear and helpful error
messages. This helps in smooth debugging and easy detection of bugs by client applications.
GraphQL also provides client side libraries that can help in reducing explicit data conversion and
parsing.
An example of the Student and College data types is given below −
type Query {
students:[Student]
}

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

 Easy to learn and use


 Amazing toolset and IDE integration
 Vastly improves UI engineering team agility and velocity
 Faster client application performance
 Cross service discoverability, standards, semantics, and validation
Operations

 0 downtime, 0 customer outages


 CPU usage low (5–10%) on K8s cluster, using 0.5 cores across instances
 Low memory usage (<200MB)

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.

Dealing with multiple requests #

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:

Add the photos to the response for the api/users/ endpoint

Add a separate endpoint, api/users/:id/photos

Both approaches will work, but which is best?


In the first option, you will end up needing to send and consume far more data than you need
for every user request.
In the second option, you will need to make another call to get their photos once you have
retrieved your user.
This is a simplified example, and there are clever ways to try and reduce this issue, such as only
calling the endpoint when a specific resource is required. But this complicates the job of the
front-end developer. In short, the major issue in REST is the requirement to have multiple
endpoints. This ends up becoming hard to reason with and difficult for your engineering team
to maintain.

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.

So which should I choose? #

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.

You might also like