GraphQL Basics
GraphQL Basics
What - Scope of this discussion is Understanding basics of GraphQL, its components, Client,
server and how to connect to a lightweight database using GraphQL.
Who – This research will help those who want to get started with GraphQL. I have tried to cover
most of the aspects of GraphQL including how to install client and server. This work of mine can be
a good starting point for someone to go deep into GraphQL
How – For learning GraphQL and using this work, one needs to have working knowledge of node.js
or JavaScript. It can be installed on Windows or Linux OS. I tried it only on Windows
References
• https://developer.barclays.com/blog/differences-between-rest-and-graphql
• https://www.howtographql.com
• https://graphql.org/
• https://www.apollographql.com/
• https://www.apideck.com/bank-api
• https://blog.risingstack.com/graphql-overview-getting-started-with-graphql-and-nodejs/
• https://www.shopify.in/partners/blog/getting-started-with-graphql
• https://codeburst.io/how-to-implement-a-graphql-api-on-top-of-an-existing-rest-api-db8b343ddb5a
• https://dev.to/ajcwebdev/graphql-caching-42ep
References
• https://dev.to/ajcwebdev/graphql-caching-42ep
• https://levelup.gitconnected.com/how-to-add-file-upload-to-your-graphql-api-34d51e341f38
• https://www.freecodecamp.org/news/get-started-with-graphql-and-nodejs/
• https://moonhighway.com/fetching-data-from-a-graphql-api
• https://spectrum.chat/apollo/apollo-server/get-graphql-response-as-a-csv-instead-of-json~a57fb3dd-cd4d-4
adf-936f-c1bb520634d
• https://www.moesif.com/blog/technical/monitoring/How-to-Best-Monitor-GraphQL-APIs/
Constraints Faced
Most of the GraphQL literature is in GitHub which is a blocked site in LTI
Installing any software requires permission. This came in the way of testing the code.
There is plenty of documentation on the net but most of them leave out crucial details. This causes
problems while doing coding.
As there is no proper IDE, so I used Visual Studio Code. Even a simple error is so difficult to
resolve. Writing a code becomes difficult.
Very few websites provide information related to accessing database and other real life examples.
Hence it becomes time-consuming to write correct code using my own-created data
GraphQL - Introduction
GraphQL is a query language for our API, and a server-side runtime for executing queries
We’ve been using REST to build APIs for a long time. Along with that comes some problems.
When building an API using REST design, we face some problems like:
1) Lot of endpoints
2) it’ll be much harder for developers to learn and understand the API
Fewer server requests: GraphQL allows us to make multiple queries and mutations with only one server
request. This can be useful when your server only allows a limited number of requests a day.
Declarative data fetching: Unlike a REST API, GraphQL only fetches what we actually need. All you have to
do is specify what fields to return.
Type system: GraphQL uses a type system to describe our data, which makes developing much easier.
Self-documenting: GraphQL is self-documenting, meaning that all of our queries and mutations will
automatically be documented by GraphQL.
GraphQL Versioning
Versioning the GraphQL is very simple.
We can add new fields and types to your GraphQL API without impacting existing queries.
By using a single evolving version, GraphQL APIs give apps continuous access to new features and
encourage cleaner, more maintainable server code
Client Side code does not depend on the server side code. Hence development can be done
independently
Working of REST
If same problem is implemented in GraphQL
We will need to define a query with the parameter and their datatypes:
type Query {
id: data_type
posts :data_type
followers :data_type
}
Working of GraphQL – GraphQL sends only Post request
Architecture with GraphQL
Components of GraphQL
GraphQL has Server Side components and Client Side components. GraphQL fetches response in
the form of JSON.Server Side components –
The first one is Apollo Client, which is a community-driven effort to build a powerful and flexible
GraphQL client.
The second one is called Relay and it is Facebook’s homegrown GraphQL client that heavily
optimizes for performance and is only browser based.
Typical Structure of a GraphQL working
folder
A graphQL folder will typically contain a file named package.json where start and end scripts can be
put
Other than this we can make a source folder – “src” for our source code.
The src folder contains
index.js (the file which has the scripts for operations),
Relay
GraphQL - Schema
GraphQL Schema is a description of the data clients can request from GraphQL API. It also defines
queries and mutation functions. The schema is the Graph of GraphQL.
Components of a GraphQL schema are Node, Object type, Scalar type, Query Type and
Mutation Type
GraphQL - Schema
GraphQL - Schema
• The above schema defines an object named Book which has fields
Id, title, page, chapters…
Next it defines a query which has the fields that we are going to query
GraphQL - Query
type Query {
greeting:String
students:[Student]
}
type Student {
id:ID!
firstName:String
lastName:String
password:String
collegeId:String
}
Every GraphQL service has a query type and may or may not have mutation type
GraphQL - Mutation
• Mutations are operations sent to the server to create, update or delete
data. These are analogous CRUD operations
• In resolver we assign values to the variables or populate them. One resolver function per field.
const resolvers = {
Query: {
info: () => `This is the API for learning GraphQL`,
feed: () => links,
context: {
prisma,
}
Datatypes
• GraphQL Schema is a description of the data clients can request from GraphQL API. It also defines queries
and mutation functions. The schema is the Graph.
• Schema is written using Schema Definition Language.
• Int, Float, String, Boolean, ID
• We have created a type Author which is an object with below characteristics:
type Author {
id: ID!
firstName : String
lastName : String
rating : Float
numOfCourses : Int
Courses: [String!]
}
GraphQL – Code
Create the directory that’ll hold the files for your GraphQL server!
mkdir mygraph
cd mygraph
npm init –y
This creates a new directory called mygraph and initializes it with a package.json file. package.json is the configuration file for the
Node.js app you’re building. It lists all dependencies and other configuration options (such as scripts) needed for the app.
Creating a raw GraphQL serverWith the project directory in place, wecan go ahead and create the entry point for your GraphQL
server. This will be a file called index.js, located inside a directory called src.
mkdir src
touch src/index.js
GraphQL – Code
• To start the app, we can now execute node src/index.js inside the mygraph directory. At the moment, this won’t do anything
because index.js is still empty
• First, let’s install two important dependencies that will allow you to create your GraphQL server.
• Prisma allows database connection to some of the databases like MySQL,Postgres, MongoDB,SQLLite
Setting up our project with Prisma and SQLite
HTTP endpoint: The HTTP endpoint monitoring gives us information about the overall status of our API.
If there is low latency, low error rates, no customer complains, all green, then we can save time and money by only
looking at these metrics.
GraphQL query: We define a bunch query and variable combinations and run them from test clients that check how
long they take when we roll out a new version
GraphQL resolver - Do we send requests to external APIs that are too slow? All these questions can now be asked
when we see what and how the data is retrieved in our backend. We can monitor the performance of an API by
monitoring the speed of data fetch which points to the performance of the resolver.
Tracing - Tagging a query with a tracing-ID when it comes in and pass this ID along when it got translated to resolvers
and in turn, data-loaders, maybe even to the data-source. This allows us to use the tracing-ID when logging timings
and errors, so we can consolidate them later to get a look at the bigger picture.
Which companies use GraphQL
• Facebook.
• Shopify.
• Instagram.
• Twitter.
• StackShare.
• The New York Times.
• Tokopedia.
• Stack.
• https://www.apideck.com/bank-api - which is a website providing API services for bank has the option of even GraphQL APIs
Disadvantages of GraphQL
1. GraphQL Query Complexity
When a query is requested, the server performs database access. When we have to access multiple fields in one
query whether it is requested in a RESTful architecture or GraphQL, we have to decide the depth of the query so that it
does not become complex
2. GraphQL Caching
It is more complicated to implement a simplified cache with GraphQL than implementing it in REST. In REST API, we
access resources with URLs, so we can cache on a resource level because we have the resource URL as an identifier.
On the other hand, In GraphQL, it is very complex because each query can be different, even though it operates on
the same entity. But most of the libraries built on top of GraphQL offer an efficient caching mechanism.
3. REST API is more proven and has been used for many critical functions. GraphQL is still evolving. About 1552
companies like FaceBook, NetFlix, Twitter are using GraphQL. This can be of great use in cases where bandwidth is
limited and people use mostly mobile. The user base of REST API is much larger
Extensions
Should we move all REST API to GraphQL?
As GraphQL is just another POST endpoint, the REST APIs and GraphQL APIs can live together in one API. This will
also help if we want to slowly migrate to GraphQL without removing all the REST APIs.
There are some steps for migrating REST API to GraphQL which I am not discussing here.
GraphQL is seen by many as a paradigm shift for web services development. Unlike REST, GraphQL allows
developers to create queries to get the exact data they need. No more, no less. This improves performance by
eliminating the over-fetching and under-fetching common to RESTful APIs.
Though GraphQL is growing in popularity, it is still somewhat new and unproven and lacks many important features of
internet data transfers, such as caching or error handling.
GraphQL API developers must create additional code or use third-party tools to make caching work. For error handling,
while REST can natively handle all HTTP status codes (e.g. 404), GraphQL cannot which makes data transfer
monitoring quite difficult.
Finally, there are potential security vulnerabilities associated with GraphQL, such as an increased risk of Denial-of-
Service (DoS) attacks due to the use of a common schema and exposure of internal data structure
I have not done any testing to check any vulnerability
We can wrap a REST API in GraphQL. I have not included that as a part of this research
Points in Favor of REST
REST API has been in existence since 2000 growing rapidly since 2005.
There is a growing group of developers who are working on improving this framework
It is a proven framework which has been used by many financial institutions like Paypal
It has its own advantages with Caching.
REST API is more proven and has been used for many critical functions. GraphQL is still evolving.
About 1552 companies like FaceBook, NetFlix, Twitter are using GraphQL. This can be of great use in cases where
bandwidth is limited and people use mostly mobile.
REST may not go away soon and may continue to exist. Or may be as some websites have predicted that it will
continue to exist the way XML is still there.