SlideShare a Scribd company logo
GraphQL vs REST
Chris Noring
Google Developer Expert
Digital McKinsey
@chris _noring
Why should I care
Presentation Structure
How to wrap an API in GraphQL
REST GraphQL comparison
Why should I care?
Problem 1
Growing end points
GET /user
POST /user
PUT /user
DELETE /user
GET /user/query..
Products
New resources needs to be added
Orders
Categories
…
Number of endpoints becomes really large, really fast
Resources needs to look different if we are dealing
with mobile or desktop
GET /users/1
data : {
firstname : ‘chris’,
}
GET /mobile/users/1
data : {
firstname : ‘chris’,
region : { url : ‘/regions/1’ }
}
Only the linkEagerly loaded
region : {
id : 1,
city : ‘Warsaw’,
country : ‘Poland’
}
Problem 2
Need for a unified way of asking for data
Twitter
Reddit
Github
Data Service
GraphQL
runtime
Frontend Query
Problem 3
Not the output I want
Mismatch in response
Mapping is needed
{ “data” : {
“name”,
“address” : “Warsaw”
}
}
class Person {
surname: string;
city: string,
}
Need to rename to avoid remapping in Frontend
Might need several endpoints
class Person {
fname : string;
surname: string;
address: string,
friends : [],
records : []
}
Might lead to multiple requests
api/people/1
api/people/1/friends
api/people/1/records
Solution
GraphQL
Lets the client specify what they need,
“content negotiation”
Easier to aggregate data from many sources
Uses a type system to describe data
Application layer query language
Multiple resources in a single request
Open sourced by Facebook in 2015
Main building blocks
Schemas
Queries
Resolvers
Mutations
How to Query
{
resource {
column,
column2
}
}
Query
data : {
resource {
column,
column2
}
}
Response
Query example
Given these resources
User ( id, name, age, address, orders) Order ( id, created, items )
OrderItem ( id, product, Quantity, Price ) Product ( id, Name )
Users {
name,
orders {
created,
items {
Quantity,
Price,
product {
Name
}
}
}
}
data : [{
‘John’,
orders : [{
‘2017-01-01’,
items : [{
Quantity : 3,
Price : 110,
Product : { Name : ‘DVD’ }
}]
}]
}]
Query with parameter
Users( email : ‘chris@chris.com’ ) {
…
}
SELECT …
FROM resource
WHERE email =‘chris@chris.com’
Query with operators
Users( email__contains : ‘chris’ ) {
}
is, not, lt, lte, gt, gte, contains, icontains, startswith, endswith,
iendswith, like, ilike
GraphQL runtime
Define a schema
Resolving a query
Building a runtime is about the following
Define queries Define mutators
Create
Update
Delete
Runtime: hello world
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLString
} from 'graphql';
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world';
}
}
}
})
});
Define a schema
Define a query
Define a queryable field
Respond/Resolve what to answer
var query = '{ hello }';
graphql(schema, query).then(result => {
// prints { data : { “hello” : “world” } }
console.log(result);
});
Do the query
Where to go from here?
A more advanced schema
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world';
}
},
human : {
type : humanType,
resolve : () => getHuman()
}
}
})
});
function getHuman() {
return Promise.resolve(
return {
id : ‘1’,
description : ‘ a description’,
name : ‘john’
})
}
Our resolver should call
a db ideally
Resolver function
var humanType = new GraphQLObjectType({
name : 'Human',
fields : () => ({
id: { type: GraphQLString },
description : { type : GraphQLString },
name : { type : GraphQLString } }),
})
}
Complex type
var query = '{ human { name, description } }';
graphql(schema, query).then(result => {
// prints { data : { “human” : { “name” : “john”, “description” : “a description” } } }
console.log(result);
});
Do the query
Define and query a list type
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world';
}
},
human : {
type : humanType,
resolve : () => getHuman()
},
humans : {
type : new GraphQLList(humanType),
resolve : () => getHumans()
}
}
})
});
var query = '{ humans { name, description } }';
graphql(schema, query).then(result => {
// prints { data : { “humans” : [
{ id: 1, name : ‘Luke’, description: ‘anakins son’ },
{ id: 2, name : ‘Vader’, description: ‘anakins?’},
{ id: 3, name : ‘Palpatine’, description: ‘anakins boss’ }] }
console.log(result);
});
Do the query
function getHumans() {
return Promise.resolve(
[{
id: 1, name : ‘Luke’, description: ‘anakins son’
},
{
id: 2, name : ‘Vader’, description: ‘anakins?’
},
{
id: 3, name : ‘Palpatine’, description: ‘anakins boss’
}]
)
}
Resolve dependencies part I
Imagine the following schema
humans : {
type: new GraphQLList(humanType),
resolve : (root, {}) => {
return getHumans();
}
}
getHumans() {
const humans = [
{id :'1', name: 'Luke', description: 'Anakins son', friends : ['2'] },
{id :'2', name: 'Darth', description: 'Anakin', friends : ['3'] },
{id :'3', name: 'Palpatine', description: 'Anakins master', friends : [] }
];
return Promise.resolve( humans );
}
How to resolve these
ids into objects?
var humanType = new GraphQLObjectType({
name : 'Human',
fields : () => ({
id: { type: GraphQLString },
description : { type : GraphQLString, description : 'desc' },
name : { type : GraphQLString, description : 'name of person' },
}),
interfaces : [ characterInterface ]
})
Resolve dependencies part II
Resolve
function getFriends(character) {
return character.friends.map( f => getHuman(f) );
}
Lookup by id
friends : {
type: new GraphQLList(humanType),
resolve : human => getFriends( human )
}
Query with an argument
human : {
type : humanType,
args : {
id: {
description: 'id of the jedi',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }) => getHumanById(id)
}
resolve, we dig out the id
and use it to query our resolver
var query = '{ human(id: 1) { name, description } }';
graphql(schema, query).then(result => {
// prints { data : { “human( id: 1 )” : { “name” : “john”, “description” : “a description” } } }
console.log(result);
});
Do the query
Resolver
Define args
function getHumanById(id) {
let result = return Promise.resolve(
[{
id: 1, name : ‘Luke’, description: ‘anakins son’
},
{
id: 2, name : ‘Vader’, description: ‘anakins?’
},
{
id: 3, name : ‘Palpatine’, description: ‘anakins boss’
}].filter( h => h.id === id );
return result.length === 0 ? null : result[0];
)
}
Aliases
Alias = rename field name in the query
query Test {
github {
userchris: user(username:"softchris") {
repos {
name
}
}
}
}
New value
Old value
“data” : {
“github” : {
“userchris” : {
“repos” : [{ “name” : “…”, … }]
}
}
}
Fragments
Fragment is about cleaning up the code and make part of it
reusable
fragment UserDetail on GithubUser {
company: my_company,
avatar_url,
repos {
name,
commits {
message
}
}
}
query Github($user: String!, $repo: Boolean!) {
github {
user(username :$user) {
...UserDetail
}
}
}
We don’t need
to clutter the query
Update in one place when a field needs to be added
Directives
Directive - Conditionally include / exclude
query ConditionalQuery($var: Boolean) {
otherField,
skipFieldPossibly @skip(if: $var)
}
Skip
query Github($user: String!, $repo: Boolean!) {
github {
user(username :$user) {
company,
avatar_url,
repos @include (if: $repo) {
name,
commits {
message
}
}
}
Include
Mutators
Mutator - delete
function deleteArticle(id) {
return articleService.delete( id )
}
Resolver
export default new GraphQLSchema({
query: QueryType,
mutation: MutationType
});
Define in schema
mutation “Delete Article” {
deleteArticle(id:123) {
status
}
} Response back
Input argument
Call
var MutationType = new GraphQLObjectType({
name: ‘Deletetion Example',
description: ‘removing article',
fields: () => ({
deleteArticle: {
type: ArticleType,
description: 'Delete an article with id and return the article that was deleted.',
args: {
id: { type: new GraphQLNonNull(GraphQLInt) }
},
resolve: (value, { id }) => {
return deleteArticle(id);
}
}
}),
});
Mutator - create
var MutationType = new GraphQLObjectType({
name: 'GraphQL Mutations',
description: 'Mutations',
fields: () => ({
createArticle: {
type: ArticleType,
description: 'Create a new article',
args: {
article: { type: ArticleInputType }
},
resolve: (value, { article }) => {
return createArticle(article);
}
}
}),
});
function createArticle(article) {
return articleService.create( article )
}
Resolver
mutation “Create Article” {
createArticle(article: {
title : “Tomato”,
description : “Veggie”
}) {
status
}
Call
We have learned
Set up a schema
To define different types
Learned about resolvers
Mutators
Directives
Fragments
Aliases
What about consuming the
GraphQL?
{
"data": {
"humans": [
{ "name": “Luke", "description": "Anakins son”, "friends": [{ "name": “Darth" }],},
{ "name": “Darth", "description": “Anakin", "friends": [ { "name": “Palpatine" }],},
{ "name": "Palpatine","description": "Anakins master","friends": [],}
],
}
}
Content-Type: application/graphql
http://localhost:4000/graphql?
query={humans{name,description,friends{name}}}
GET
Apollo client
Inrementally adoptable
Universally compatible
Simple to get started with
Inspectable and understandable
Built for interactive apps
Small and flexible
Community driven
GraphQL Client with integrations to all major frameworks
Also get Chrome plugin
https://chrome.google.com/webstore/detail/apollo-client-
developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm/related
npm install apollo-client graphql-tag --save
Install
Playgrounds
http://graphql.org/swapi-graphql/
Star wars API wrapped in GraphQL
https://www.graphqlhub.com/
Social media such as Twitter, Github, Reddit etc.
Links
graphql-express
Learn to build your own API
https://github.com/softchris/graphql-express-demo
Or cheat and check out my repo :)
http://graphql.org/learn/
Official documentation
Summing up
Is GraphQL replacing REST? You can use both actually
REST has many endpoints
and HATEOAS
GraphQL has one endpoint
and content negotiation
REST is an architecture
concept
GraphQL is query
language + tools
GraphQL only asks for fields
it need
REST responds with a
whole object
Thank you

More Related Content

PDF
Nativescript angular
PDF
Angular 2 introduction
PPTX
Angular mix chrisnoring
PDF
Integrating React.js with PHP projects
PDF
React lecture
PPTX
How to perform debounce in react
PPTX
Firebase ng2 zurich
PPTX
Typed? Dynamic? Both! Cross-platform DSLs in C#
Nativescript angular
Angular 2 introduction
Angular mix chrisnoring
Integrating React.js with PHP projects
React lecture
How to perform debounce in react
Firebase ng2 zurich
Typed? Dynamic? Both! Cross-platform DSLs in C#

What's hot (20)

PPTX
Typescript barcelona
PPTX
Test and profile your Windows Phone 8 App
PDF
Hidden Docs in Angular
PPT
Developing application for Windows Phone 7 in TDD
PDF
Redux vs Alt
KEY
SOLID Principles
PPT
JavaScript
PDF
GWT integration with Vaadin
PDF
Better Bullshit Driven Development [SeleniumCamp 2017]
PDF
Quick start with React | DreamLab Academy #2
KEY
Gwt and Xtend
PDF
Auto-GWT : Better GWT Programming with Xtend
PDF
SOLID PRINCIPLES
PDF
Oleksandr Tolstykh
KEY
Why ruby
PDF
Intro to Redux | DreamLab Academy #3
PDF
Mastering Oracle ADF Bindings
KEY
Ruby/Rails
KEY
Backbone js
PPTX
Open Source Ajax Solution @OSDC.tw 2009
Typescript barcelona
Test and profile your Windows Phone 8 App
Hidden Docs in Angular
Developing application for Windows Phone 7 in TDD
Redux vs Alt
SOLID Principles
JavaScript
GWT integration with Vaadin
Better Bullshit Driven Development [SeleniumCamp 2017]
Quick start with React | DreamLab Academy #2
Gwt and Xtend
Auto-GWT : Better GWT Programming with Xtend
SOLID PRINCIPLES
Oleksandr Tolstykh
Why ruby
Intro to Redux | DreamLab Academy #3
Mastering Oracle ADF Bindings
Ruby/Rails
Backbone js
Open Source Ajax Solution @OSDC.tw 2009
Ad

Similar to Graphql, REST and Apollo (20)

PDF
[2019-07] GraphQL in depth (serverside)
PDF
Nikita Galkin "Looking for the right tech stack for GraphQL application"
PDF
Next-generation API Development with GraphQL and Prisma
PPTX
GraphQL API Gateway and microservices
PPTX
PDF
GraphQL the holy contract between client and server
PDF
GraphQL with .NET Core Microservices.pdf
PDF
GraphQL in Symfony
PPTX
GraphQL - an elegant weapon... for more civilized age
PDF
GraphQL - A love story
PPTX
Building a GraphQL API in PHP
PDF
The Serverless GraphQL Backend Architecture
PDF
Managing GraphQL servers with AWS Fargate & Prisma Cloud
PDF
Let's start GraphQL: structure, behavior, and architecture
PPTX
GraphQL, Redux, and React
PDF
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
PDF
Graphql usage
PPTX
Introduction to GraphQL Presentation.pptx
ODP
GraphQL with Sangria
PPTX
GraphQl Introduction
[2019-07] GraphQL in depth (serverside)
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Next-generation API Development with GraphQL and Prisma
GraphQL API Gateway and microservices
GraphQL the holy contract between client and server
GraphQL with .NET Core Microservices.pdf
GraphQL in Symfony
GraphQL - an elegant weapon... for more civilized age
GraphQL - A love story
Building a GraphQL API in PHP
The Serverless GraphQL Backend Architecture
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Let's start GraphQL: structure, behavior, and architecture
GraphQL, Redux, and React
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Graphql usage
Introduction to GraphQL Presentation.pptx
GraphQL with Sangria
GraphQl Introduction
Ad

More from Christoffer Noring (20)

PPTX
Azure signalR
PPTX
Game dev 101 part 3
PPTX
Game dev 101 part 2
PPTX
Game dev workshop
PPTX
Deploying your static web app to the Cloud
PPTX
IaaS with ARM templates for Azure
PPTX
Learning Svelte
PPTX
PDF
Angular Schematics
PDF
Design thinking
PDF
Keynote ijs
PDF
Vue fundamentasl with Testing and Vuex
PDF
Ngrx slides
PDF
PDF
Rxjs vienna
PPTX
Rxjs marble-testing
PPTX
Rxjs ngvikings
PPTX
Rxjs swetugg
PPTX
Angular modules in depth
PPTX
Finjs - Angular 2 better faster stronger
Azure signalR
Game dev 101 part 3
Game dev 101 part 2
Game dev workshop
Deploying your static web app to the Cloud
IaaS with ARM templates for Azure
Learning Svelte
Angular Schematics
Design thinking
Keynote ijs
Vue fundamentasl with Testing and Vuex
Ngrx slides
Rxjs vienna
Rxjs marble-testing
Rxjs ngvikings
Rxjs swetugg
Angular modules in depth
Finjs - Angular 2 better faster stronger

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PDF
Encapsulation theory and applications.pdf
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
Teaching material agriculture food technology
PDF
Empathic Computing: Creating Shared Understanding
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KodekX | Application Modernization Development
Encapsulation theory and applications.pdf
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Advanced methodologies resolving dimensionality complications for autism neur...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Machine learning based COVID-19 study performance prediction
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
Review of recent advances in non-invasive hemoglobin estimation
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Weekly Chronicles - August'25 Week I
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Teaching material agriculture food technology
Empathic Computing: Creating Shared Understanding
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Unlocking AI with Model Context Protocol (MCP)
Agricultural_Statistics_at_a_Glance_2022_0.pdf

Graphql, REST and Apollo

  • 1. GraphQL vs REST Chris Noring Google Developer Expert Digital McKinsey @chris _noring
  • 2. Why should I care Presentation Structure How to wrap an API in GraphQL REST GraphQL comparison
  • 3. Why should I care?
  • 5. GET /user POST /user PUT /user DELETE /user GET /user/query.. Products New resources needs to be added Orders Categories … Number of endpoints becomes really large, really fast
  • 6. Resources needs to look different if we are dealing with mobile or desktop GET /users/1 data : { firstname : ‘chris’, } GET /mobile/users/1 data : { firstname : ‘chris’, region : { url : ‘/regions/1’ } } Only the linkEagerly loaded region : { id : 1, city : ‘Warsaw’, country : ‘Poland’ }
  • 7. Problem 2 Need for a unified way of asking for data Twitter Reddit Github Data Service GraphQL runtime Frontend Query
  • 8. Problem 3 Not the output I want
  • 9. Mismatch in response Mapping is needed { “data” : { “name”, “address” : “Warsaw” } } class Person { surname: string; city: string, } Need to rename to avoid remapping in Frontend
  • 10. Might need several endpoints class Person { fname : string; surname: string; address: string, friends : [], records : [] } Might lead to multiple requests api/people/1 api/people/1/friends api/people/1/records
  • 12. GraphQL Lets the client specify what they need, “content negotiation” Easier to aggregate data from many sources Uses a type system to describe data Application layer query language Multiple resources in a single request Open sourced by Facebook in 2015
  • 16. { resource { column, column2 } } Query data : { resource { column, column2 } } Response
  • 17. Query example Given these resources User ( id, name, age, address, orders) Order ( id, created, items ) OrderItem ( id, product, Quantity, Price ) Product ( id, Name ) Users { name, orders { created, items { Quantity, Price, product { Name } } } } data : [{ ‘John’, orders : [{ ‘2017-01-01’, items : [{ Quantity : 3, Price : 110, Product : { Name : ‘DVD’ } }] }] }]
  • 18. Query with parameter Users( email : ‘chris@chris.com’ ) { … } SELECT … FROM resource WHERE email =‘chris@chris.com’
  • 19. Query with operators Users( email__contains : ‘chris’ ) { } is, not, lt, lte, gt, gte, contains, icontains, startswith, endswith, iendswith, like, ilike
  • 21. Define a schema Resolving a query Building a runtime is about the following Define queries Define mutators Create Update Delete
  • 22. Runtime: hello world import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql'; var schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'RootQueryType', fields: { hello: { type: GraphQLString, resolve() { return 'world'; } } } }) }); Define a schema Define a query Define a queryable field Respond/Resolve what to answer var query = '{ hello }'; graphql(schema, query).then(result => { // prints { data : { “hello” : “world” } } console.log(result); }); Do the query
  • 23. Where to go from here?
  • 24. A more advanced schema var schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'RootQueryType', fields: { hello: { type: GraphQLString, resolve() { return 'world'; } }, human : { type : humanType, resolve : () => getHuman() } } }) }); function getHuman() { return Promise.resolve( return { id : ‘1’, description : ‘ a description’, name : ‘john’ }) } Our resolver should call a db ideally Resolver function var humanType = new GraphQLObjectType({ name : 'Human', fields : () => ({ id: { type: GraphQLString }, description : { type : GraphQLString }, name : { type : GraphQLString } }), }) } Complex type var query = '{ human { name, description } }'; graphql(schema, query).then(result => { // prints { data : { “human” : { “name” : “john”, “description” : “a description” } } } console.log(result); }); Do the query
  • 25. Define and query a list type var schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'RootQueryType', fields: { hello: { type: GraphQLString, resolve() { return 'world'; } }, human : { type : humanType, resolve : () => getHuman() }, humans : { type : new GraphQLList(humanType), resolve : () => getHumans() } } }) }); var query = '{ humans { name, description } }'; graphql(schema, query).then(result => { // prints { data : { “humans” : [ { id: 1, name : ‘Luke’, description: ‘anakins son’ }, { id: 2, name : ‘Vader’, description: ‘anakins?’}, { id: 3, name : ‘Palpatine’, description: ‘anakins boss’ }] } console.log(result); }); Do the query function getHumans() { return Promise.resolve( [{ id: 1, name : ‘Luke’, description: ‘anakins son’ }, { id: 2, name : ‘Vader’, description: ‘anakins?’ }, { id: 3, name : ‘Palpatine’, description: ‘anakins boss’ }] ) }
  • 26. Resolve dependencies part I Imagine the following schema humans : { type: new GraphQLList(humanType), resolve : (root, {}) => { return getHumans(); } } getHumans() { const humans = [ {id :'1', name: 'Luke', description: 'Anakins son', friends : ['2'] }, {id :'2', name: 'Darth', description: 'Anakin', friends : ['3'] }, {id :'3', name: 'Palpatine', description: 'Anakins master', friends : [] } ]; return Promise.resolve( humans ); } How to resolve these ids into objects?
  • 27. var humanType = new GraphQLObjectType({ name : 'Human', fields : () => ({ id: { type: GraphQLString }, description : { type : GraphQLString, description : 'desc' }, name : { type : GraphQLString, description : 'name of person' }, }), interfaces : [ characterInterface ] }) Resolve dependencies part II Resolve function getFriends(character) { return character.friends.map( f => getHuman(f) ); } Lookup by id friends : { type: new GraphQLList(humanType), resolve : human => getFriends( human ) }
  • 28. Query with an argument human : { type : humanType, args : { id: { description: 'id of the jedi', type: new GraphQLNonNull(GraphQLString) } }, resolve: (root, { id }) => getHumanById(id) } resolve, we dig out the id and use it to query our resolver var query = '{ human(id: 1) { name, description } }'; graphql(schema, query).then(result => { // prints { data : { “human( id: 1 )” : { “name” : “john”, “description” : “a description” } } } console.log(result); }); Do the query Resolver Define args function getHumanById(id) { let result = return Promise.resolve( [{ id: 1, name : ‘Luke’, description: ‘anakins son’ }, { id: 2, name : ‘Vader’, description: ‘anakins?’ }, { id: 3, name : ‘Palpatine’, description: ‘anakins boss’ }].filter( h => h.id === id ); return result.length === 0 ? null : result[0]; ) }
  • 30. Alias = rename field name in the query query Test { github { userchris: user(username:"softchris") { repos { name } } } } New value Old value “data” : { “github” : { “userchris” : { “repos” : [{ “name” : “…”, … }] } } }
  • 32. Fragment is about cleaning up the code and make part of it reusable fragment UserDetail on GithubUser { company: my_company, avatar_url, repos { name, commits { message } } } query Github($user: String!, $repo: Boolean!) { github { user(username :$user) { ...UserDetail } } } We don’t need to clutter the query Update in one place when a field needs to be added
  • 34. Directive - Conditionally include / exclude query ConditionalQuery($var: Boolean) { otherField, skipFieldPossibly @skip(if: $var) } Skip query Github($user: String!, $repo: Boolean!) { github { user(username :$user) { company, avatar_url, repos @include (if: $repo) { name, commits { message } } } Include
  • 36. Mutator - delete function deleteArticle(id) { return articleService.delete( id ) } Resolver export default new GraphQLSchema({ query: QueryType, mutation: MutationType }); Define in schema mutation “Delete Article” { deleteArticle(id:123) { status } } Response back Input argument Call var MutationType = new GraphQLObjectType({ name: ‘Deletetion Example', description: ‘removing article', fields: () => ({ deleteArticle: { type: ArticleType, description: 'Delete an article with id and return the article that was deleted.', args: { id: { type: new GraphQLNonNull(GraphQLInt) } }, resolve: (value, { id }) => { return deleteArticle(id); } } }), });
  • 37. Mutator - create var MutationType = new GraphQLObjectType({ name: 'GraphQL Mutations', description: 'Mutations', fields: () => ({ createArticle: { type: ArticleType, description: 'Create a new article', args: { article: { type: ArticleInputType } }, resolve: (value, { article }) => { return createArticle(article); } } }), }); function createArticle(article) { return articleService.create( article ) } Resolver mutation “Create Article” { createArticle(article: { title : “Tomato”, description : “Veggie” }) { status } Call
  • 38. We have learned Set up a schema To define different types Learned about resolvers Mutators Directives Fragments Aliases
  • 39. What about consuming the GraphQL?
  • 40. { "data": { "humans": [ { "name": “Luke", "description": "Anakins son”, "friends": [{ "name": “Darth" }],}, { "name": “Darth", "description": “Anakin", "friends": [ { "name": “Palpatine" }],}, { "name": "Palpatine","description": "Anakins master","friends": [],} ], } } Content-Type: application/graphql http://localhost:4000/graphql? query={humans{name,description,friends{name}}} GET
  • 42. Inrementally adoptable Universally compatible Simple to get started with Inspectable and understandable Built for interactive apps Small and flexible Community driven GraphQL Client with integrations to all major frameworks
  • 43. Also get Chrome plugin https://chrome.google.com/webstore/detail/apollo-client- developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm/related npm install apollo-client graphql-tag --save Install
  • 45. http://graphql.org/swapi-graphql/ Star wars API wrapped in GraphQL https://www.graphqlhub.com/ Social media such as Twitter, Github, Reddit etc.
  • 46. Links graphql-express Learn to build your own API https://github.com/softchris/graphql-express-demo Or cheat and check out my repo :) http://graphql.org/learn/ Official documentation
  • 47. Summing up Is GraphQL replacing REST? You can use both actually REST has many endpoints and HATEOAS GraphQL has one endpoint and content negotiation REST is an architecture concept GraphQL is query language + tools GraphQL only asks for fields it need REST responds with a whole object