0% found this document useful (0 votes)
150 views

GraphQL Basics

The document discusses the components, structure, and architecture of GraphQL. It describes the typical components of a GraphQL server including the schema, queries, mutations, and resolvers. It also explains the typical structure of a GraphQL project folder and provides examples of schema definitions, queries, and mutations. GraphQL is presented as an alternative to REST for building APIs that can return precisely the data clients need in a single request.

Uploaded by

Archanna Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views

GraphQL Basics

The document discusses the components, structure, and architecture of GraphQL. It describes the typical components of a GraphQL server including the schema, queries, mutations, and resolvers. It also explains the typical structure of a GraphQL project folder and provides examples of schema definitions, queries, and mutations. GraphQL is presented as an alternative to REST for building APIs that can return precisely the data clients need in a single request.

Uploaded by

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

Sources and Scope

 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/

• LTI Shoshin tutorial

 
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.

 Had to use my personal laptop for testing GraphQL

 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

 3) there is over- and under-fetching of information

To solve these problems, Facebook created GraphQL for building APIs.


GraphQL Business Case
1)Due to increased mobile usage, people want faster apps
3) Faster development speed
4)With GraphQL each client gets precisely the data they need,
5)Due to frequent changes, how data is exposed by the server requires to be
modified due to design changes and new requirements on the client side
6)Any change in requirement does not need adjustment in API
7)By monitoring performance of resolvers, we know the bottlenecks in the system
8)REST has multiple endpoints for operations where as GraphQL has single endpoint
GraphQL Advantages
One endpoint: With traditional REST APIs, we have to create specific endpoints based on the data you
want to request. This makes scaling API difficult because soon, we might find ourselves having to manage
tens, maybe hundreds, of routes that we will have to remember.

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.

Aging fields can be deprecated and hidden from tools.

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 –

 Below are the server side components


# Component Description
1 Schema A GraphQL schema is a description of the data clients can
request from a GraphQL API. It also defines the queries and
mutation functions that the client can use to read and write
data from the GraphQL server.
2 Query A GraphQL query is the client application request to retrieve
data from database or legacy API's.
3 Resolver Resolvers provide the instructions for turning a GraphQL
operation into data. They resolve the query to data by
defining resolver functions.
4. Mutation CRUD operation on the data is performed using this
Components of GraphQL contd.
 Client Side components – This layer is required so that we don’t have to build an http request
ourselves. So we can send queries and mutations directly without constructing HTTP requests.
Client also does validation and optimization of queries based on the schema

 There are two major GraphQL clients available:

 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),

 “schema.graphql” which contains schema definition

 Db.json file for containing data

 Other files related to prisma client


Architecture of GraphQL

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.

 Schema is written using Schema Definition Language.

 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

• Mutation is one of the root-level data-types in GraphQL. The Query type


defines the entry-points for data-fetching operations whereas the
Mutation type specifies the entry points for data-manipulation operations.
Below is a mutation which adds a student.
Example:type Mutation {
addStudent(firstName: String, lastName: String): Student
}
Query Types and Mutation
Type Query {
author_details : [Author]
}
Type Mutation {
addAuthor(firstName : String, lastName : String): Author
}
GraphQL - Resolvers
• A resolver is a function that's responsible for populating the data for a single field in our schema.
Whenever a client queries for a particular field, the resolver for that field fetches the requested data
from the appropriate data source.
• Once a query fetches the data, the resolver function assigns value to each variable queried

• 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.

• npm install apollo-server graphql


• This installs apollo server which is based on express.js and is graphql compliant
• Next update the index.js file
GraphQL – Code
• const { ApolloServer } = require('apollo-server');
• // 1 typedef defines our schema
• const typeDefs = `
• type Query {
• info: String!
• }
• const resolvers = {
• Query: {
• info: () => `This is the API created for Test Purpose`
• }
• }
• const server = new ApolloServer({
• typeDefs,
• resolvers,
• })
GraphQL – Code
• server
• .listen()
• .then(({ url }) =>
• console.log(`Server is running on ${url}`)
• );

• Test the server


• node src/index.js
GraphQL – Code
• The typeDefs constant defines your GraphQL schema
• Here, it defines a simple Query type with one field called info. This field has the type
String!. The exclamation mark in the type definition means that this field is required and
can never be null.
• The resolvers object is the actual implementation of the GraphQL schema. Its structure is
identical to the structure of the type definition inside typeDefs: Query.info.
• Finally, the schema and resolvers are bundled and passed to ApolloServer which is
imported from apollo-server. This tells the server what API operations are accepted and
how they should be resolved.
• For testing the server run node src/index.js
Accessing Database
• Prisma is an open-source database toolkit. It consists of three main tools:
• Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript.
• Prisma Migrate: Declarative data modeling & migration system.
• Prisma Studio: GUI to view and edit data in your database.
Remember the GraphQL schema that we have been working with until now.
• Well, Prisma has a schema, too! Inside the prisma directory that was created in the last step, you’ll see a file
called schema.prisma. schema.prisma file is like a database schema. It has three components:

• Data source: Specifies your database connection.


• Generator: Indicates that you want to generate Prisma Client.
• Data model: Defines your application models. Each model will be mapped to a table in the underlying
database.

• Prisma allows database connection to some of the databases like MySQL,Postgres, MongoDB,SQLLite
Setting up our project with Prisma and SQLite

Steps to install Prisma


• npm install prisma --save-dev
• npm install @prisma/client
• Next, use the Prisma CLI to initialize Prisma in the project.
• It’s as simple as that! You now have /node_modules/@prisma/client which can be imported and used in your
code.
• Let’s write our first query with Prisma Client and break everything down. We will do that in a separate file to not
mess with your current GraphQL server implementation.
Wiring up your GraphQL schema with Prisma Client
• Updating the resolver functions to use Prisma Client. Prisma Client exposes a CRUD API for the models in datamodel for us to
read and write in your database.
• In index.js write
• const { PrismaClient } = require('@prisma/client')

• const prisma = new PrismaClient()


• Then write below code to pass prisma to resolvers
• const server = new ApolloServer({
• typeDefs: fs.readFileSync(
• path.join(__dirname, 'schema.graphql'),
• 'utf8'
• ),
• resolvers,
• context: {
• prisma,
• }
• })
Updating Database Prisma Client
• const resolvers = {
• Query: {
• info: () => `This is the API of a test Clone`,
• feed: async (parent, args, context) => {
• return context.prisma.link.findMany()
• },
• },
• Mutation: {
• post: (parent, args, context, info) => {
• const newLink = context.prisma.link.create({
• data: {
• url: args.url,
• description: args.description,
• },
• })
• return newLink
• },
• },
• }
Updating Database Prisma Client

npx prisma studio


helps in starting prisma studio where we can perform CRUD operations
How to secure GraphQL
1. By Auth – using JWT tokens
2. Reduce the depth of the query because a nested query can cause API to crash
3. We can validate a query using GraphQL schema. For example someone could write below query:
query User {
user (id: "User*") {
email
id
}
}
Which could expose all user ids. We need to build check into the code while validating the query.
4. Other methods are timeout.
There are many other methods
Monitoring GraphQL
Monitoring GraphQL
Depending on our architecture, there can be multiple places in which we can monitor our GraphQL API.

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.

Can GraphQL replace a REST API in all cases? No!


The use of GraphQL in Small Applications is not recommended. If you end up using GraphQL, REST is a better option
because it’s more simple and predictable.
When we know certain URLs will be requested often, we consider caching these in a web cache. Since a REST API
provides many endpoints, we can easily configure a web cache to match certain URL patterns, HTTP methods, or
specific resources.
GraphQL does not follow the HTTP specification for caching and instead uses a single endpoint, so it is up to the
developer to make sure that caching is implemented properly for non-mutable queries. There are some libraries that
can help GraphQL solve this problem.
REST or GraphQL – The debate continues
Whereas REST is an architectural style, GraphQL is a query language for web service APIs.
GraphQL is agnostic to types of databases and transport layers. So, it is potentially possible to implement a GraphQL
server based on TCP, WebSockets, etc. It can connect to SQL database like AWS Aurora or NOSQL database like
MongoDB.

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.

The user base of REST API is much larger

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.

You might also like