SlideShare a Scribd company logo
GraphQL is the
Better REST
REST and Its Drawbacks
What is REST?
● REST is the de-facto standard for designing Web APIs
● REST (REpresentational State Transfer) is an architectural
style for developing web services.
● REST is popular due to its simplicity and the fact that it
builds upon existing systems and features of the internet's
HTTP.
REST Design Principles
● Stateless server
● Uniform interface
● Everything is a resource
● Use HTTP verbs for CRUD actions
● Explore associations through URL structure
● Attribute filters, sorting and pagination through query
parameters
● Implement global and local searches
● Error handling using HTTP error codes
● Use JSON as data exchange format
REST APIs have shown to
be too inflexible to keep
up with the rapidly
changing requirements of
the clients that access
them.
REST Drawbacks
● Poor data discovery
● Multiple fetches are common
● Fetching extraneous data
● No query validation
● Does not handle API deprecations, additions
and changes
REST Example
● In a blogging application, an app needs to display the
titles of the posts of a specific user.
● The same screen also displays the names of the last 3
followers of that user.
Source: https://www.howtographql.com/basics/1-graphql-is-the-better-rest/
Get user information
Get user’s posts
Get user’s followers
Problems with this Approach
● It took three HTTP requests to populate the
page (underfetching).
● Each request potentially returned more data
than was necessary (overfetching)
● New client data needs typically require new
endpoints (endpoint management)
Equivalent GraphQL Query
Why is GitHub using GraphQL?
“GitHub chose GraphQL for our API v4 because it offers
significantly more flexibility for our integrators. The ability to
define precisely the data you want—and only the data you
want—is a powerful advantage over the REST API v3
endpoints. GraphQL lets you replace multiple REST requests
with a single call to fetch the data you specify.”
Source: https://developer.github.com/v4/
GraphQL at Netflix
“Since GraphQL allows the client to select only the data it
needs we end up fetching a significantly smaller payload. In
our application, pages that were fetching 10MB of data before
now receive about 200KB. Page loads became much faster,
especially over data-constrained mobile networks, and our
app uses much less memory. “
Source: https://medium.com/netflix-techblog/our-learnings-from-adopting-graphql-f099de39ae5f
GraphQL and REST
● Although GraphQL addresses many shortcomings of
REST, they can be easily used together.
● GraphQL API can be used as a facade with its resolvers
obtaining data using existing REST services.
● This is one way for an organization to incrementally adopt
GraphQL
Source: https://medium.com/netflix-techblog/our-learnings-from-adopting-graphql-f099de39ae5f
Introduction to GraphQL
What is GraphQL
● GraphQL is a query language for your API, and a
server-side runtime for executing queries by
using a type system you define for your data.
● GraphQL isn't tied to any specific database or
storage engine and is instead backed by your
existing code and data.
‘Graph’ in GraphQL
● You model your business domain as a graph by
defining a schema.
● Within your schema, you define different types of
nodes and how they connect/relate to one another.
GraphQL Core Concepts
● The Schema Definition Language (SDL)
○ Queries to Fetch Data
○ Mutations to Update Data
○ Subscriptions for Real-Time Updates
● Resolvers to implement Queries, Mutations and
Subscriptions
GraphQL: Structure vs. Behavior
● Separating interface from implementation
● Interface (structure) is defined by the schema
● Implementation (behavior) is encapsulated in
resolvers.
Structure vs. Behavior in GraphQL
Schema
Resolvers
Specification
Implementation
GraphQL Schema
Source: “Visual Design of GraphQL Data” by Thomas Frisendal
What is a Schema?
● The GraphQL schema defines the server’s API
● The GraphQL schema provides a clear contract
for client-server communication
● GraphQL schemas are language-agnostic
● The main components of a schema definition are
the types and their fields
Example of Types and Fields
type Post {
id: String!
title: String!
publishedAt: DateTime!
likes: Int! @default(value: 0)
blog: Blog @relation(name: "Posts")
}
type Blog {
id: String!
name: String!
description: String,
posts: [Post!]! @relation(name: "Posts")
}
GraphQL Schema Types
● Object types represent a kind of object you can fetch from your
service, and what fields it has
● A type has a name and can implement one or more interfaces
● A field has a name and a type
● GraphQL supports built-in scalar types
● An enum is a scalar value that has a specified set of possible
values
● An Interface is an abstract type that includes a certain set of
fields that a type must include to implement the interface
● Custom types can be created using scalar types, enums, other
custom types and interfaces.
Anatomy of GraphQL Custom Type
type Character {
name: String!
appearsIn: [Episode]!
}
Type Name
Field
Field of Scalar Type
Field of Array Type
Non-nullable field
Built-in Scalar Types
● Int: A signed 32‐bit integer.
● Float: A signed double-precision floating-point value.
● String: A UTF‐8 character sequence.
● Boolean: true or false.
● ID: The ID scalar type represents a unique identifier
Enumeration Types
● Special kind of scalar that is restricted to a particular set of allowed values
● Validates that any arguments of this type are one of the allowed values
● Communicates through the type system that a field will always be one of a
finite set of values
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
Interfaces
interface Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
}
type Human implements Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
starships: [Starship]
totalCredits: Int
}
type Droid implements Character {
id: ID!
name: String!
friends: [Character]
appearsIn: [Episode]!
primaryFunction: String
}
Defining Queries, Mutations
and Subscriptions
Query, Mutation and Subscription Types
● In addition to schema types defining the server-side domain
model, GraphQL defines special types, Query, Mutation and
Subscription
● These types define the server API in terms of domain types
● Query type specifies what queries clients can execute
● Mutation type defines create, update and delete operations
● Subscription defines the events the client can receive from the
server
Snowtooth Example
https://github.com/MoonHighway/snowtooth
GraphQL definition of type Lift
# A `Lift` is a chairlift, gondola, tram, funicular, pulley, rope tow, or other means of ascending a mountain.
type Lift {
# The unique identifier for a `Lift` (id: "panorama")
id: ID!
# The name of a `Lift`
name: String!
# The current status for a `Lift`: `OPEN`, `CLOSED`, `HOLD`
status: LiftStatus
# The number of people that a `Lift` can hold
capacity: Int!
# A boolean describing whether a `Lift` is open for night skiing
night: Boolean!
# The number of feet in elevation that a `Lift` ascends
elevationGain: Int!
# A list of trails that this `Lift` serves
trailAccess: [Trail!]!
}
GraphQL definition of type Trail
# A `Trail` is a run at a ski resort
type Trail {
# A unique identifier for a `Trail` (id: 'hemmed-slacks')
id: ID!
# The name of a `Trail`
name: String!
# The current status for a `Trail`: OPEN, CLOSED
status: TrailStatus
# The difficulty rating for a `Trail`
difficulty: String!
# A boolean describing whether or not a `Trail` is groomed
groomed: Boolean!
# A boolean describing whether or not a `Trail` has trees
trees: Boolean!
# A boolean describing whether or not a `Trail` is open for night skiing
night: Boolean!
# A list of Lifts that provide access to this `Trail`
accessedByLifts: [Lift!]!
}
GraphQL definition of enums LiftStatus and TrailStatus
# An enum describing the options for `LiftStatus`: `OPEN`, `CLOSED`, `HOLD`
enum LiftStatus {
OPEN
CLOSED
HOLD
}
# An enum describing the options for `TrailStatus`: `OPEN`, `CLOSED`
enum TrailStatus {
OPEN
CLOSED
}
GraphQL definition of API Queries against Lists and Trails
type Query {
# A list of all `Lift` objects
allLifts(status: LiftStatus): [Lift!]!
# A list of all `Trail` objects
allTrails(status: TrailStatus): [Trail!]!
# Returns a `Lift` by `id` (id: "panorama")
Lift(id: ID!): Lift!
# Returns a `Trail` by `id` (id: "old-witch")
Trail(id: ID!): Trail!
# Returns an `Int` of `Lift` objects by `LiftStatus`
liftCount(status: LiftStatus!): Int!
# Returns an `Int` of `Trail` objects by `TrailStatus`
trailCount(status: TrailStatus!): Int!
}
GraphQL definition of Mutations and Subscriptions
type Mutation {
"""
Sets a `Lift` status by sending `id` and `status`
"""
setLiftStatus(id: ID!, status: LiftStatus!): Lift!
"""
Sets a `Trail` status by sending `id` and `status`
"""
setTrailStatus(id: ID!, status: TrailStatus!): Trail!
}
type Subscription {
liftStatusChange: Lift
trailStatusChange: Trail
}
GraphQL Queries
Snowtooth Demo
http://snowtooth.moonhighway.com/
GraphQL Queries vs. REST Queries
● REST Server define multiple query endpoints,
each with a predefined data structure
● GraphQL Server provide a single query
endpoints with a flexible query structure
● Query structure in GraphQL is defined in terms
of Schema Types discussed previously
A simple GraphQL query and its result
{
hero {
name
}
}
{
"data": {
"hero": {
"name": "R2-D2"
}
}
}
A multi-level GraphQL query
{
hero {
name
# Queries can have comments!
friends {
name
}
}
}
{
"data": {
"hero": {
"name": "R2-D2",
"friends": [
{
"name": "Luke Skywalker"
},
{
"name": "Han Solo"
},
{
"name": "Leia Organa"
}
]
}
}
}
A named query with an argument
query GetReturnOfTheJedi {
film(id: "ZmlsbXM6Mw==") {
title
director
releaseDate
}
}
{
"data": {
"film": {
"title": "Return of the Jedi",
"director": "Richard Marquand",
"releaseDate": "1983-05-25"
}
}
}
A named query with a variable argument
query GetReturnOfTheJedi($id: ID) {
film(id: $id) {
title
director
releaseDate
}
}
{ "id": filmId }
{
"data": {
"film": {
"title": "Return of the Jedi",
"director": "Richard Marquand",
"releaseDate": "1983-05-25"
}
}
}
A query with a field alias
query GetTitles {
allFilms {
films {
filmTitle: title
}
}
}
{
"data": {
"allFilms": {
"films": [
{
"filmTitle": "A New Hope"
},
{
"filmTitle": "The Empire Strikes Back"
},
{
"filmTitle": "Return of the Jedi"
},
...
Using query fragments
query GetFilmInfo {
film1: film(id: "ZmlsbXM6NA==") {
title
director
producers
}
film2: film(id: "ZmlsbXM6Ng==") {
title
director
producers
}
}
query GetFilmInfo {
film1: film(id: "ZmlsbXM6NA==") {
...info
}
film2: film(id: "ZmlsbXM6Ng==") {
...info
}
}
fragment info on Film {
title
director
producers
}
@include directive
query GetTitles($includeDirector: Boolean!) {
allFilms {
films {
filmTitle: title
director @include(if: $includeDirector)
}
}
}
{
"data": {
"allFilms": {
"films": [
{
"filmTitle": "A New Hope",
"director": "George Lucas"
},
{
"filmTitle": "The Empire Strikes Back",
"director": "Irvin Kershner"
},
{
"filmTitle": "Return of the Jedi",
"director": "Richard Marquand"
},
...
Mutations
Mutations Defined
● The purpose of mutations is
○ Creating new data
○ Updating existing data
○ Deleting data
● Syntax for mutations is similar to that of queries
○ name
○ arguments
○ return object with its fields
Named mutation with parameters
mutation CreateReviewForEpisode($ep: Episode!,
$review: ReviewInput!) {
createReview(episode: $ep, review: $review) {
stars
commentary
}
}
{
"ep": "JEDI",
"review": {
"stars": 5,
"commentary": "This is a great movie!"
}
}
{
"data": {
"createReview": {
"stars": 5,
"commentary": "This is a great
movie!"
}
}
}
GraphQL Resolvers
Resolvers Defined
● Resolvers implement the API
● Each field in a GraphQL schema is backed by a
resolver
● Each resolver knows how to fetch the data for
its field.
GraphQL definition of API Queries against Lists and Trails
type Query {
# A list of all `Lift` objects
allLifts(status: LiftStatus): [Lift!]!
# A list of all `Trail` objects
allTrails(status: TrailStatus): [Trail!]!
# Returns a `Lift` by `id` (id: "panorama")
Lift(id: ID!): Lift!
# Returns a `Trail` by `id` (id: "old-witch")
Trail(id: ID!): Trail!
# Returns an `Int` of `Lift` objects by `LiftStatus`
liftCount(status: LiftStatus!): Int!
# Returns an `Int` of `Trail` objects by `TrailStatus`
trailCount(status: TrailStatus!): Int!
}
GraphQL resolvers for API Queries against Lists and Trails
module.exports = {
allLifts: (root, { status }, { lifts }) => {
if (!status) {
return lifts
} else {
var filteredLifts = lifts.filter(lift => lift.status === status)
return filteredLifts
}
},
allTrails: (root, { status }, { trails }) => {
if (!status) {
return trails
} else {
var filteredTrails = trails.filter(trail => trail.status === status)
return filteredTrails
}
},
Lift: (root, { id }, { lifts }) => {
var selectedLift = lifts.filter(lift => id === lift.id)
return selectedLift[0]
},
...
Resolver definitions continued
...
Trail: (root, { id }, { trails }) => {
var selectedTrail = trails.filter(trail => id === trail.id)
return selectedTrail[0]
},
liftCount: (root, { status }, { lifts }) => {
var i = 0
lifts.map(lift => {
lift.status === status ?
i++ :
null
})
return i
},
trailCount: (root, { status }, { trails }) => {
var i = 0
trails.map(trail => {
trail.status === status ?
i++ :
null
})
return i
}
}
Resolver Parameters
Resolvers get four parameters:
● Root - argument in each resolver call is simply the result of the previous
call (initial value is rootValue from the server configuration)
● Args - carries the parameters for the query
● Context - an object that gets passed through the resolver chain that each
resolver can write to and read from
● Info - an AST representation of the query or mutation
GraphQL definition of type Lift
# A `Lift` is a chairlift, gondola, tram, funicular, pulley, rope tow, or other means of ascending a mountain.
type Lift {
# The unique identifier for a `Lift` (id: "panorama")
id: ID!
# The name of a `Lift`
name: String!
# The current status for a `Lift`: `OPEN`, `CLOSED`, `HOLD`
status: LiftStatus
# The number of people that a `Lift` can hold
capacity: Int!
# A boolean describing whether a `Lift` is open for night skiing
night: Boolean!
# The number of feet in elevation that a `Lift` ascends
elevationGain: Int!
# A list of trails that this `Lift` serves
trailAccess: [Trail!]!
}
Resolvers for the field of the Lift type
module.exports = {
trailAccess: (root, args, { trails }) => root.trails
.map(id => trails.find(t => id === t.id))
.filter(x => x)
}
GraphQL definition of API Queries against Lists and Trails
type Mutation {
"""
Sets a `Lift` status by sending `id` and `status`
"""
setLiftStatus(id: ID!, status: LiftStatus!): Lift!
"""
Sets a `Trail` status by sending `id` and `status`
"""
setTrailStatus(id: ID!, status: TrailStatus!): Trail!
}
type Subscription {
liftStatusChange: Lift
trailStatusChange: Trail
}
Resolvers for Mutations
module.exports = {
setLiftStatus: (root, { id, status }, { lifts, pubsub }) => {
var updatedLift = lifts.find(lift => id === lift.id)
updatedLift.status = status
pubsub.publish('lift-status-change', { liftStatusChange: updatedLift })
return updatedLift
},
setTrailStatus: (root, { id, status }, { trails, pubsub }) => {
var updatedTrail = trails.find(trail => id === trail.id)
updatedTrail.status = status
pubsub.publish('trail-status-change', { trailStatusChange: updatedTrail })
return updatedTrail
}
}
Resolvers for Subscriptions
module.exports = {
liftStatusChange: {
subscribe: (root, data, { pubsub }) => pubsub.asyncIterator('lift-status-change')
},
trailStatusChange: {
subscribe: (root, data, { pubsub }) => pubsub.asyncIterator('trail-status-change')
}
}
The GRANDstack
GRANDstack is a full-stack development
integration for building graph-based
applications.
GRANDstack Technologies
● GraphQL – a query language for APIs and a runtime for
fulfilling those queries with your existing data
● React – a JavaScript library for building user interfaces
● Apollo Client – a fully-featured, production-ready
caching GraphQL client for every server or UI framework
● Neo4j Database – a graph database that is
ACID-compliant and built to store and retrieve
connected data
Top Reasons for Using
GraphQL
GraphQL APIs have a strongly typed schema
A GraphQL schema is the backbone of every
GraphQL API. It clearly defines the operations
(queries, mutations and subscriptions)
supported by the API, including input arguments
and possible responses. The schema is an
unfailing contract that specifies the capabilities
of an API.
GraphQL APIs have a strongly typed schema
Developers don’t have to manually write API
documentation any more — instead it can be
auto-generated based on the schema that
defines the API
No more overfetching and underfetching
Clients can retrieve exactly the data they need
from the API. They don’t have to rely on REST
endpoints that return predefined and fixed data
structures. Instead, the client can dictate the
shape of the response objects returned by the
API.
GraphQL enables rapid product development
Thanks to GraphQL, client libraries (like Apollo,
Relay or Urql) frontend developers are getting
features like caching, realtime or optimistic UI
updates basically for free.
GraphQL enables rapid product development
● Schema-driven development is a process where
a feature is first defined in the schema, then
implemented with resolver functions.
● Tools like GraphQL Faker mocks the entire
GraphQL API (based on its schema definition),
so frontend and backend teams can work
completely independently.
Support for multiple server-side languages
● A GraphQL server can be implemented in any
programming language that can be used to build
a web server.
● Next to Javascript, there are popular reference
implementations for Ruby, Python, Scala, Java,
Clojure, Go and .NET.
Composing GraphQL APIs
● Schema stitching is combining and connecting
multiple GraphQL schemas (or schema
definitions) to create a single GraphQL API.
● Thanks to schema stitching, clients only deal
with a single API endpoint and all complexity of
orchestrating the communication with the
various services is hidden from the client.
Rich open-source ecosystem
● When it came out, the only tooling available for
developers to use GraphQL was the graphql-js
reference implementation, a piece of
middleware for Express.js, and the GraphQL
client Relay (Classic).
Rich open-source ecosystem
GraphQL Clients
● FetchQL
● GraphQL Request
● Apollo Fetch
● Lokka
● Micro GraphQL React
● URQL
● Apollo Client
● Relay Modern
Rich open-source ecosystem
GraphQL Tools
● Prisma - Simplified Database Access
● GraphQL Faker - Mock your future API or
extend the existing API with realistic data
● GraphQL Playground - GraphQL IDE
● Graphql-config - IDE configuration
GraphQL is the Better REST

More Related Content

More from Data Works MD

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
Data Works MD
 
Data in the City: Analytics and Civic Data in Baltimore
Data in the City: Analytics and Civic Data in BaltimoreData in the City: Analytics and Civic Data in Baltimore
Data in the City: Analytics and Civic Data in Baltimore
Data Works MD
 
Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...
Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...
Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...
Data Works MD
 
Automated Software Requirements Labeling
Automated Software Requirements LabelingAutomated Software Requirements Labeling
Automated Software Requirements Labeling
Data Works MD
 
Introduction to Elasticsearch for Business Intelligence and Application Insights
Introduction to Elasticsearch for Business Intelligence and Application InsightsIntroduction to Elasticsearch for Business Intelligence and Application Insights
Introduction to Elasticsearch for Business Intelligence and Application Insights
Data Works MD
 
An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...
An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...
An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...
Data Works MD
 
RAPIDS – Open GPU-accelerated Data Science
RAPIDS – Open GPU-accelerated Data ScienceRAPIDS – Open GPU-accelerated Data Science
RAPIDS – Open GPU-accelerated Data Science
Data Works MD
 
Two Algorithms for Weakly Supervised Denoising of EEG Data
Two Algorithms for Weakly Supervised Denoising of EEG DataTwo Algorithms for Weakly Supervised Denoising of EEG Data
Two Algorithms for Weakly Supervised Denoising of EEG Data
Data Works MD
 
Detecting Lateral Movement with a Compute-Intense Graph Kernel
Detecting Lateral Movement with a Compute-Intense Graph KernelDetecting Lateral Movement with a Compute-Intense Graph Kernel
Detecting Lateral Movement with a Compute-Intense Graph Kernel
Data Works MD
 
Predictive Analytics and Neighborhood Health
Predictive Analytics and Neighborhood HealthPredictive Analytics and Neighborhood Health
Predictive Analytics and Neighborhood Health
Data Works MD
 
Social Network Analysis Workshop
Social Network Analysis WorkshopSocial Network Analysis Workshop
Social Network Analysis Workshop
Data Works MD
 

More from Data Works MD (11)

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Data in the City: Analytics and Civic Data in Baltimore
Data in the City: Analytics and Civic Data in BaltimoreData in the City: Analytics and Civic Data in Baltimore
Data in the City: Analytics and Civic Data in Baltimore
 
Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...
Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...
Exploring Correlation Between Sentiment of Environmental Tweets and the Stock...
 
Automated Software Requirements Labeling
Automated Software Requirements LabelingAutomated Software Requirements Labeling
Automated Software Requirements Labeling
 
Introduction to Elasticsearch for Business Intelligence and Application Insights
Introduction to Elasticsearch for Business Intelligence and Application InsightsIntroduction to Elasticsearch for Business Intelligence and Application Insights
Introduction to Elasticsearch for Business Intelligence and Application Insights
 
An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...
An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...
An Asynchronous Distributed Deep Learning Based Intrusion Detection System fo...
 
RAPIDS – Open GPU-accelerated Data Science
RAPIDS – Open GPU-accelerated Data ScienceRAPIDS – Open GPU-accelerated Data Science
RAPIDS – Open GPU-accelerated Data Science
 
Two Algorithms for Weakly Supervised Denoising of EEG Data
Two Algorithms for Weakly Supervised Denoising of EEG DataTwo Algorithms for Weakly Supervised Denoising of EEG Data
Two Algorithms for Weakly Supervised Denoising of EEG Data
 
Detecting Lateral Movement with a Compute-Intense Graph Kernel
Detecting Lateral Movement with a Compute-Intense Graph KernelDetecting Lateral Movement with a Compute-Intense Graph Kernel
Detecting Lateral Movement with a Compute-Intense Graph Kernel
 
Predictive Analytics and Neighborhood Health
Predictive Analytics and Neighborhood HealthPredictive Analytics and Neighborhood Health
Predictive Analytics and Neighborhood Health
 
Social Network Analysis Workshop
Social Network Analysis WorkshopSocial Network Analysis Workshop
Social Network Analysis Workshop
 

Recently uploaded

06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases
06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases
06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases
Timothy Spann
 
Call Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance Payment
Call Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance PaymentCall Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance Payment
Call Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance Payment
prijesh mathew
 
一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理
一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理
一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理
ywqeos
 
Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...
Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...
Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...
Marlon Dumas
 
一比一原版莱斯大学毕业证(rice毕业证)如何办理
一比一原版莱斯大学毕业证(rice毕业证)如何办理一比一原版莱斯大学毕业证(rice毕业证)如何办理
一比一原版莱斯大学毕业证(rice毕业证)如何办理
zsafxbf
 
一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理
一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理
一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理
nyvan3
 
SAP BW4HANA Implementagtion Content Document
SAP BW4HANA Implementagtion Content DocumentSAP BW4HANA Implementagtion Content Document
SAP BW4HANA Implementagtion Content Document
newdirectionconsulta
 
[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024
Vietnam Cotton & Spinning Association
 
How To Control IO Usage using Resource Manager
How To Control IO Usage using Resource ManagerHow To Control IO Usage using Resource Manager
How To Control IO Usage using Resource Manager
Alireza Kamrani
 
Call Girls Lucknow 0000000000 Independent Call Girl Service Lucknow
Call Girls Lucknow 0000000000 Independent Call Girl Service LucknowCall Girls Lucknow 0000000000 Independent Call Girl Service Lucknow
Call Girls Lucknow 0000000000 Independent Call Girl Service Lucknow
hiju9823
 
PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)
PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)
PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)
Rebecca Bilbro
 
06-18-2024-Princeton Meetup-Introduction to Milvus
06-18-2024-Princeton Meetup-Introduction to Milvus06-18-2024-Princeton Meetup-Introduction to Milvus
06-18-2024-Princeton Meetup-Introduction to Milvus
Timothy Spann
 
一比一原版南昆士兰大学毕业证如何办理
一比一原版南昆士兰大学毕业证如何办理一比一原版南昆士兰大学毕业证如何办理
一比一原版南昆士兰大学毕业证如何办理
ugydym
 
一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理
一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理
一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理
eudsoh
 
Salesforce AI + Data Community Tour Slides - Canarias
Salesforce AI + Data Community Tour Slides - CanariasSalesforce AI + Data Community Tour Slides - Canarias
Salesforce AI + Data Community Tour Slides - Canarias
davidpietrzykowski1
 
[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024
Vietnam Cotton & Spinning Association
 
Overview IFM June 2024 Consumer Confidence INDEX Report.pdf
Overview IFM June 2024 Consumer Confidence INDEX Report.pdfOverview IFM June 2024 Consumer Confidence INDEX Report.pdf
Overview IFM June 2024 Consumer Confidence INDEX Report.pdf
nhutnguyen355078
 
Telemetry Solution for Gaming (AWS Summit'24)
Telemetry Solution for Gaming (AWS Summit'24)Telemetry Solution for Gaming (AWS Summit'24)
Telemetry Solution for Gaming (AWS Summit'24)
GeorgiiSteshenko
 
Data Scientist Machine Learning Profiles .pdf
Data Scientist Machine Learning  Profiles .pdfData Scientist Machine Learning  Profiles .pdf
Data Scientist Machine Learning Profiles .pdf
Vineet
 
A gentle exploration of Retrieval Augmented Generation
A gentle exploration of Retrieval Augmented GenerationA gentle exploration of Retrieval Augmented Generation
A gentle exploration of Retrieval Augmented Generation
dataschool1
 

Recently uploaded (20)

06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases
06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases
06-20-2024-AI Camp Meetup-Unstructured Data and Vector Databases
 
Call Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance Payment
Call Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance PaymentCall Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance Payment
Call Girls Hyderabad ❤️ 7339748667 ❤️ With No Advance Payment
 
一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理
一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理
一比一原版(lbs毕业证书)伦敦商学院毕业证如何办理
 
Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...
Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...
Discovering Digital Process Twins for What-if Analysis: a Process Mining Appr...
 
一比一原版莱斯大学毕业证(rice毕业证)如何办理
一比一原版莱斯大学毕业证(rice毕业证)如何办理一比一原版莱斯大学毕业证(rice毕业证)如何办理
一比一原版莱斯大学毕业证(rice毕业证)如何办理
 
一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理
一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理
一比一原版英国赫特福德大学毕业证(hertfordshire毕业证书)如何办理
 
SAP BW4HANA Implementagtion Content Document
SAP BW4HANA Implementagtion Content DocumentSAP BW4HANA Implementagtion Content Document
SAP BW4HANA Implementagtion Content Document
 
[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics May 2024
 
How To Control IO Usage using Resource Manager
How To Control IO Usage using Resource ManagerHow To Control IO Usage using Resource Manager
How To Control IO Usage using Resource Manager
 
Call Girls Lucknow 0000000000 Independent Call Girl Service Lucknow
Call Girls Lucknow 0000000000 Independent Call Girl Service LucknowCall Girls Lucknow 0000000000 Independent Call Girl Service Lucknow
Call Girls Lucknow 0000000000 Independent Call Girl Service Lucknow
 
PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)
PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)
PyData London 2024: Mistakes were made (Dr. Rebecca Bilbro)
 
06-18-2024-Princeton Meetup-Introduction to Milvus
06-18-2024-Princeton Meetup-Introduction to Milvus06-18-2024-Princeton Meetup-Introduction to Milvus
06-18-2024-Princeton Meetup-Introduction to Milvus
 
一比一原版南昆士兰大学毕业证如何办理
一比一原版南昆士兰大学毕业证如何办理一比一原版南昆士兰大学毕业证如何办理
一比一原版南昆士兰大学毕业证如何办理
 
一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理
一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理
一比一原版马来西亚博特拉大学毕业证(upm毕业证)如何办理
 
Salesforce AI + Data Community Tour Slides - Canarias
Salesforce AI + Data Community Tour Slides - CanariasSalesforce AI + Data Community Tour Slides - Canarias
Salesforce AI + Data Community Tour Slides - Canarias
 
[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024
[VCOSA] Monthly Report - Cotton & Yarn Statistics March 2024
 
Overview IFM June 2024 Consumer Confidence INDEX Report.pdf
Overview IFM June 2024 Consumer Confidence INDEX Report.pdfOverview IFM June 2024 Consumer Confidence INDEX Report.pdf
Overview IFM June 2024 Consumer Confidence INDEX Report.pdf
 
Telemetry Solution for Gaming (AWS Summit'24)
Telemetry Solution for Gaming (AWS Summit'24)Telemetry Solution for Gaming (AWS Summit'24)
Telemetry Solution for Gaming (AWS Summit'24)
 
Data Scientist Machine Learning Profiles .pdf
Data Scientist Machine Learning  Profiles .pdfData Scientist Machine Learning  Profiles .pdf
Data Scientist Machine Learning Profiles .pdf
 
A gentle exploration of Retrieval Augmented Generation
A gentle exploration of Retrieval Augmented GenerationA gentle exploration of Retrieval Augmented Generation
A gentle exploration of Retrieval Augmented Generation
 

GraphQL is the Better REST

  • 2. REST and Its Drawbacks
  • 3. What is REST? ● REST is the de-facto standard for designing Web APIs ● REST (REpresentational State Transfer) is an architectural style for developing web services. ● REST is popular due to its simplicity and the fact that it builds upon existing systems and features of the internet's HTTP.
  • 4.
  • 5. REST Design Principles ● Stateless server ● Uniform interface ● Everything is a resource ● Use HTTP verbs for CRUD actions ● Explore associations through URL structure ● Attribute filters, sorting and pagination through query parameters ● Implement global and local searches ● Error handling using HTTP error codes ● Use JSON as data exchange format
  • 6. REST APIs have shown to be too inflexible to keep up with the rapidly changing requirements of the clients that access them.
  • 7. REST Drawbacks ● Poor data discovery ● Multiple fetches are common ● Fetching extraneous data ● No query validation ● Does not handle API deprecations, additions and changes
  • 8.
  • 9. REST Example ● In a blogging application, an app needs to display the titles of the posts of a specific user. ● The same screen also displays the names of the last 3 followers of that user. Source: https://www.howtographql.com/basics/1-graphql-is-the-better-rest/
  • 13. Problems with this Approach ● It took three HTTP requests to populate the page (underfetching). ● Each request potentially returned more data than was necessary (overfetching) ● New client data needs typically require new endpoints (endpoint management)
  • 15. Why is GitHub using GraphQL? “GitHub chose GraphQL for our API v4 because it offers significantly more flexibility for our integrators. The ability to define precisely the data you want—and only the data you want—is a powerful advantage over the REST API v3 endpoints. GraphQL lets you replace multiple REST requests with a single call to fetch the data you specify.” Source: https://developer.github.com/v4/
  • 16. GraphQL at Netflix “Since GraphQL allows the client to select only the data it needs we end up fetching a significantly smaller payload. In our application, pages that were fetching 10MB of data before now receive about 200KB. Page loads became much faster, especially over data-constrained mobile networks, and our app uses much less memory. “ Source: https://medium.com/netflix-techblog/our-learnings-from-adopting-graphql-f099de39ae5f
  • 17. GraphQL and REST ● Although GraphQL addresses many shortcomings of REST, they can be easily used together. ● GraphQL API can be used as a facade with its resolvers obtaining data using existing REST services. ● This is one way for an organization to incrementally adopt GraphQL Source: https://medium.com/netflix-techblog/our-learnings-from-adopting-graphql-f099de39ae5f
  • 19. What is GraphQL ● GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. ● GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data.
  • 20. ‘Graph’ in GraphQL ● You model your business domain as a graph by defining a schema. ● Within your schema, you define different types of nodes and how they connect/relate to one another.
  • 21.
  • 22. GraphQL Core Concepts ● The Schema Definition Language (SDL) ○ Queries to Fetch Data ○ Mutations to Update Data ○ Subscriptions for Real-Time Updates ● Resolvers to implement Queries, Mutations and Subscriptions
  • 23. GraphQL: Structure vs. Behavior ● Separating interface from implementation ● Interface (structure) is defined by the schema ● Implementation (behavior) is encapsulated in resolvers.
  • 24. Structure vs. Behavior in GraphQL Schema Resolvers Specification Implementation
  • 26. Source: “Visual Design of GraphQL Data” by Thomas Frisendal
  • 27. What is a Schema? ● The GraphQL schema defines the server’s API ● The GraphQL schema provides a clear contract for client-server communication ● GraphQL schemas are language-agnostic ● The main components of a schema definition are the types and their fields
  • 28. Example of Types and Fields type Post { id: String! title: String! publishedAt: DateTime! likes: Int! @default(value: 0) blog: Blog @relation(name: "Posts") } type Blog { id: String! name: String! description: String, posts: [Post!]! @relation(name: "Posts") }
  • 29. GraphQL Schema Types ● Object types represent a kind of object you can fetch from your service, and what fields it has ● A type has a name and can implement one or more interfaces ● A field has a name and a type ● GraphQL supports built-in scalar types ● An enum is a scalar value that has a specified set of possible values ● An Interface is an abstract type that includes a certain set of fields that a type must include to implement the interface ● Custom types can be created using scalar types, enums, other custom types and interfaces.
  • 30. Anatomy of GraphQL Custom Type type Character { name: String! appearsIn: [Episode]! } Type Name Field Field of Scalar Type Field of Array Type Non-nullable field
  • 31. Built-in Scalar Types ● Int: A signed 32‐bit integer. ● Float: A signed double-precision floating-point value. ● String: A UTF‐8 character sequence. ● Boolean: true or false. ● ID: The ID scalar type represents a unique identifier
  • 32. Enumeration Types ● Special kind of scalar that is restricted to a particular set of allowed values ● Validates that any arguments of this type are one of the allowed values ● Communicates through the type system that a field will always be one of a finite set of values enum Episode { NEWHOPE EMPIRE JEDI }
  • 33. Interfaces interface Character { id: ID! name: String! friends: [Character] appearsIn: [Episode]! } type Human implements Character { id: ID! name: String! friends: [Character] appearsIn: [Episode]! starships: [Starship] totalCredits: Int } type Droid implements Character { id: ID! name: String! friends: [Character] appearsIn: [Episode]! primaryFunction: String }
  • 35. Query, Mutation and Subscription Types ● In addition to schema types defining the server-side domain model, GraphQL defines special types, Query, Mutation and Subscription ● These types define the server API in terms of domain types ● Query type specifies what queries clients can execute ● Mutation type defines create, update and delete operations ● Subscription defines the events the client can receive from the server
  • 37. GraphQL definition of type Lift # A `Lift` is a chairlift, gondola, tram, funicular, pulley, rope tow, or other means of ascending a mountain. type Lift { # The unique identifier for a `Lift` (id: "panorama") id: ID! # The name of a `Lift` name: String! # The current status for a `Lift`: `OPEN`, `CLOSED`, `HOLD` status: LiftStatus # The number of people that a `Lift` can hold capacity: Int! # A boolean describing whether a `Lift` is open for night skiing night: Boolean! # The number of feet in elevation that a `Lift` ascends elevationGain: Int! # A list of trails that this `Lift` serves trailAccess: [Trail!]! }
  • 38. GraphQL definition of type Trail # A `Trail` is a run at a ski resort type Trail { # A unique identifier for a `Trail` (id: 'hemmed-slacks') id: ID! # The name of a `Trail` name: String! # The current status for a `Trail`: OPEN, CLOSED status: TrailStatus # The difficulty rating for a `Trail` difficulty: String! # A boolean describing whether or not a `Trail` is groomed groomed: Boolean! # A boolean describing whether or not a `Trail` has trees trees: Boolean! # A boolean describing whether or not a `Trail` is open for night skiing night: Boolean! # A list of Lifts that provide access to this `Trail` accessedByLifts: [Lift!]! }
  • 39. GraphQL definition of enums LiftStatus and TrailStatus # An enum describing the options for `LiftStatus`: `OPEN`, `CLOSED`, `HOLD` enum LiftStatus { OPEN CLOSED HOLD } # An enum describing the options for `TrailStatus`: `OPEN`, `CLOSED` enum TrailStatus { OPEN CLOSED }
  • 40. GraphQL definition of API Queries against Lists and Trails type Query { # A list of all `Lift` objects allLifts(status: LiftStatus): [Lift!]! # A list of all `Trail` objects allTrails(status: TrailStatus): [Trail!]! # Returns a `Lift` by `id` (id: "panorama") Lift(id: ID!): Lift! # Returns a `Trail` by `id` (id: "old-witch") Trail(id: ID!): Trail! # Returns an `Int` of `Lift` objects by `LiftStatus` liftCount(status: LiftStatus!): Int! # Returns an `Int` of `Trail` objects by `TrailStatus` trailCount(status: TrailStatus!): Int! }
  • 41. GraphQL definition of Mutations and Subscriptions type Mutation { """ Sets a `Lift` status by sending `id` and `status` """ setLiftStatus(id: ID!, status: LiftStatus!): Lift! """ Sets a `Trail` status by sending `id` and `status` """ setTrailStatus(id: ID!, status: TrailStatus!): Trail! } type Subscription { liftStatusChange: Lift trailStatusChange: Trail }
  • 44. GraphQL Queries vs. REST Queries ● REST Server define multiple query endpoints, each with a predefined data structure ● GraphQL Server provide a single query endpoints with a flexible query structure ● Query structure in GraphQL is defined in terms of Schema Types discussed previously
  • 45. A simple GraphQL query and its result { hero { name } } { "data": { "hero": { "name": "R2-D2" } } }
  • 46. A multi-level GraphQL query { hero { name # Queries can have comments! friends { name } } } { "data": { "hero": { "name": "R2-D2", "friends": [ { "name": "Luke Skywalker" }, { "name": "Han Solo" }, { "name": "Leia Organa" } ] } } }
  • 47. A named query with an argument query GetReturnOfTheJedi { film(id: "ZmlsbXM6Mw==") { title director releaseDate } } { "data": { "film": { "title": "Return of the Jedi", "director": "Richard Marquand", "releaseDate": "1983-05-25" } } }
  • 48. A named query with a variable argument query GetReturnOfTheJedi($id: ID) { film(id: $id) { title director releaseDate } } { "id": filmId } { "data": { "film": { "title": "Return of the Jedi", "director": "Richard Marquand", "releaseDate": "1983-05-25" } } }
  • 49. A query with a field alias query GetTitles { allFilms { films { filmTitle: title } } } { "data": { "allFilms": { "films": [ { "filmTitle": "A New Hope" }, { "filmTitle": "The Empire Strikes Back" }, { "filmTitle": "Return of the Jedi" }, ...
  • 50. Using query fragments query GetFilmInfo { film1: film(id: "ZmlsbXM6NA==") { title director producers } film2: film(id: "ZmlsbXM6Ng==") { title director producers } } query GetFilmInfo { film1: film(id: "ZmlsbXM6NA==") { ...info } film2: film(id: "ZmlsbXM6Ng==") { ...info } } fragment info on Film { title director producers }
  • 51. @include directive query GetTitles($includeDirector: Boolean!) { allFilms { films { filmTitle: title director @include(if: $includeDirector) } } } { "data": { "allFilms": { "films": [ { "filmTitle": "A New Hope", "director": "George Lucas" }, { "filmTitle": "The Empire Strikes Back", "director": "Irvin Kershner" }, { "filmTitle": "Return of the Jedi", "director": "Richard Marquand" }, ...
  • 53. Mutations Defined ● The purpose of mutations is ○ Creating new data ○ Updating existing data ○ Deleting data ● Syntax for mutations is similar to that of queries ○ name ○ arguments ○ return object with its fields
  • 54. Named mutation with parameters mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { stars commentary } } { "ep": "JEDI", "review": { "stars": 5, "commentary": "This is a great movie!" } } { "data": { "createReview": { "stars": 5, "commentary": "This is a great movie!" } } }
  • 56. Resolvers Defined ● Resolvers implement the API ● Each field in a GraphQL schema is backed by a resolver ● Each resolver knows how to fetch the data for its field.
  • 57. GraphQL definition of API Queries against Lists and Trails type Query { # A list of all `Lift` objects allLifts(status: LiftStatus): [Lift!]! # A list of all `Trail` objects allTrails(status: TrailStatus): [Trail!]! # Returns a `Lift` by `id` (id: "panorama") Lift(id: ID!): Lift! # Returns a `Trail` by `id` (id: "old-witch") Trail(id: ID!): Trail! # Returns an `Int` of `Lift` objects by `LiftStatus` liftCount(status: LiftStatus!): Int! # Returns an `Int` of `Trail` objects by `TrailStatus` trailCount(status: TrailStatus!): Int! }
  • 58. GraphQL resolvers for API Queries against Lists and Trails module.exports = { allLifts: (root, { status }, { lifts }) => { if (!status) { return lifts } else { var filteredLifts = lifts.filter(lift => lift.status === status) return filteredLifts } }, allTrails: (root, { status }, { trails }) => { if (!status) { return trails } else { var filteredTrails = trails.filter(trail => trail.status === status) return filteredTrails } }, Lift: (root, { id }, { lifts }) => { var selectedLift = lifts.filter(lift => id === lift.id) return selectedLift[0] }, ...
  • 59. Resolver definitions continued ... Trail: (root, { id }, { trails }) => { var selectedTrail = trails.filter(trail => id === trail.id) return selectedTrail[0] }, liftCount: (root, { status }, { lifts }) => { var i = 0 lifts.map(lift => { lift.status === status ? i++ : null }) return i }, trailCount: (root, { status }, { trails }) => { var i = 0 trails.map(trail => { trail.status === status ? i++ : null }) return i } }
  • 60. Resolver Parameters Resolvers get four parameters: ● Root - argument in each resolver call is simply the result of the previous call (initial value is rootValue from the server configuration) ● Args - carries the parameters for the query ● Context - an object that gets passed through the resolver chain that each resolver can write to and read from ● Info - an AST representation of the query or mutation
  • 61. GraphQL definition of type Lift # A `Lift` is a chairlift, gondola, tram, funicular, pulley, rope tow, or other means of ascending a mountain. type Lift { # The unique identifier for a `Lift` (id: "panorama") id: ID! # The name of a `Lift` name: String! # The current status for a `Lift`: `OPEN`, `CLOSED`, `HOLD` status: LiftStatus # The number of people that a `Lift` can hold capacity: Int! # A boolean describing whether a `Lift` is open for night skiing night: Boolean! # The number of feet in elevation that a `Lift` ascends elevationGain: Int! # A list of trails that this `Lift` serves trailAccess: [Trail!]! }
  • 62. Resolvers for the field of the Lift type module.exports = { trailAccess: (root, args, { trails }) => root.trails .map(id => trails.find(t => id === t.id)) .filter(x => x) }
  • 63. GraphQL definition of API Queries against Lists and Trails type Mutation { """ Sets a `Lift` status by sending `id` and `status` """ setLiftStatus(id: ID!, status: LiftStatus!): Lift! """ Sets a `Trail` status by sending `id` and `status` """ setTrailStatus(id: ID!, status: TrailStatus!): Trail! } type Subscription { liftStatusChange: Lift trailStatusChange: Trail }
  • 64. Resolvers for Mutations module.exports = { setLiftStatus: (root, { id, status }, { lifts, pubsub }) => { var updatedLift = lifts.find(lift => id === lift.id) updatedLift.status = status pubsub.publish('lift-status-change', { liftStatusChange: updatedLift }) return updatedLift }, setTrailStatus: (root, { id, status }, { trails, pubsub }) => { var updatedTrail = trails.find(trail => id === trail.id) updatedTrail.status = status pubsub.publish('trail-status-change', { trailStatusChange: updatedTrail }) return updatedTrail } }
  • 65. Resolvers for Subscriptions module.exports = { liftStatusChange: { subscribe: (root, data, { pubsub }) => pubsub.asyncIterator('lift-status-change') }, trailStatusChange: { subscribe: (root, data, { pubsub }) => pubsub.asyncIterator('trail-status-change') } }
  • 66. The GRANDstack GRANDstack is a full-stack development integration for building graph-based applications.
  • 67. GRANDstack Technologies ● GraphQL – a query language for APIs and a runtime for fulfilling those queries with your existing data ● React – a JavaScript library for building user interfaces ● Apollo Client – a fully-featured, production-ready caching GraphQL client for every server or UI framework ● Neo4j Database – a graph database that is ACID-compliant and built to store and retrieve connected data
  • 68. Top Reasons for Using GraphQL
  • 69. GraphQL APIs have a strongly typed schema A GraphQL schema is the backbone of every GraphQL API. It clearly defines the operations (queries, mutations and subscriptions) supported by the API, including input arguments and possible responses. The schema is an unfailing contract that specifies the capabilities of an API.
  • 70. GraphQL APIs have a strongly typed schema Developers don’t have to manually write API documentation any more — instead it can be auto-generated based on the schema that defines the API
  • 71. No more overfetching and underfetching Clients can retrieve exactly the data they need from the API. They don’t have to rely on REST endpoints that return predefined and fixed data structures. Instead, the client can dictate the shape of the response objects returned by the API.
  • 72. GraphQL enables rapid product development Thanks to GraphQL, client libraries (like Apollo, Relay or Urql) frontend developers are getting features like caching, realtime or optimistic UI updates basically for free.
  • 73. GraphQL enables rapid product development ● Schema-driven development is a process where a feature is first defined in the schema, then implemented with resolver functions. ● Tools like GraphQL Faker mocks the entire GraphQL API (based on its schema definition), so frontend and backend teams can work completely independently.
  • 74. Support for multiple server-side languages ● A GraphQL server can be implemented in any programming language that can be used to build a web server. ● Next to Javascript, there are popular reference implementations for Ruby, Python, Scala, Java, Clojure, Go and .NET.
  • 75. Composing GraphQL APIs ● Schema stitching is combining and connecting multiple GraphQL schemas (or schema definitions) to create a single GraphQL API. ● Thanks to schema stitching, clients only deal with a single API endpoint and all complexity of orchestrating the communication with the various services is hidden from the client.
  • 76. Rich open-source ecosystem ● When it came out, the only tooling available for developers to use GraphQL was the graphql-js reference implementation, a piece of middleware for Express.js, and the GraphQL client Relay (Classic).
  • 77. Rich open-source ecosystem GraphQL Clients ● FetchQL ● GraphQL Request ● Apollo Fetch ● Lokka ● Micro GraphQL React ● URQL ● Apollo Client ● Relay Modern
  • 78. Rich open-source ecosystem GraphQL Tools ● Prisma - Simplified Database Access ● GraphQL Faker - Mock your future API or extend the existing API with realistic data ● GraphQL Playground - GraphQL IDE ● Graphql-config - IDE configuration