SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in AngularYadong Xie
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with VaadinPeter Lehto
 
Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]automician
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2DreamLab
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendSven Efftinge
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr TolstykhCodeFest
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF BindingsEuegene Fedorenko
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Backbone js
Backbone jsBackbone js
Backbone jsrstankov
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009Robbie Cheng
 

Was ist angesagt? (20)

Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in Angular
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
JavaScript
JavaScriptJavaScript
JavaScript
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with Vaadin
 
Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with Xtend
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
Mastering Oracle ADF Bindings
Mastering Oracle ADF BindingsMastering Oracle ADF Bindings
Mastering Oracle ADF Bindings
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
 

Ähnlich wie Graphql, REST and Apollo

[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)croquiscom
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Fwdays
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaMarcinStachniuk
 
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017Codemotion
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLAppier
 
Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...
Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...
Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...Codemotion
 
GraphQL, Redux, and React
GraphQL, Redux, and ReactGraphQL, Redux, and React
GraphQL, Redux, and ReactKeon Kim
 
Taller: Datos en tiempo real con GraphQL
Taller: Datos en tiempo real con GraphQLTaller: Datos en tiempo real con GraphQL
Taller: Datos en tiempo real con GraphQLSoftware Guru
 
Next-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and PrismaNext-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and PrismaNikolas Burk
 
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScriptMongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScriptMongoDB
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedMarcinStachniuk
 
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Managing GraphQL servers  with AWS Fargate & Prisma CloudManaging GraphQL servers  with AWS Fargate & Prisma Cloud
Managing GraphQL servers with AWS Fargate & Prisma CloudNikolas Burk
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchNikolas Burk
 
GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0Tobias Meixner
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Tools and Projects Dec 2018 Edition
Tools and Projects Dec 2018 EditionTools and Projects Dec 2018 Edition
Tools and Projects Dec 2018 EditionJesus Manuel Olivas
 
Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Mike Nakhimovich
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices - Michael HacksteinNoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices - Michael Hacksteindistributed matters
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
 

Ähnlich wie Graphql, REST and Apollo (20)

[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in Java
 
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
Tomer Elmalem - GraphQL APIs: REST in Peace - Codemotion Milan 2017
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...
Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...
Developing and maintaining a Java GraphQL back-end: The less obvious - Bojan ...
 
GraphQL, Redux, and React
GraphQL, Redux, and ReactGraphQL, Redux, and React
GraphQL, Redux, and React
 
Taller: Datos en tiempo real con GraphQL
Taller: Datos en tiempo real con GraphQLTaller: Datos en tiempo real con GraphQL
Taller: Datos en tiempo real con GraphQL
 
Next-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and PrismaNext-generation API Development with GraphQL and Prisma
Next-generation API Development with GraphQL and Prisma
 
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScriptMongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
MongoDB World 2019: Building a GraphQL API with MongoDB, Prisma, & TypeScript
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Managing GraphQL servers  with AWS Fargate & Prisma CloudManaging GraphQL servers  with AWS Fargate & Prisma Cloud
Managing GraphQL servers with AWS Fargate & Prisma Cloud
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from Scratch
 
GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Tools and Projects Dec 2018 Edition
Tools and Projects Dec 2018 EditionTools and Projects Dec 2018 Edition
Tools and Projects Dec 2018 Edition
 
Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017Intro to GraphQL on Android with Apollo DroidconNYC 2017
Intro to GraphQL on Android with Apollo DroidconNYC 2017
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices - Michael HacksteinNoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
 

Mehr von Christoffer Noring (20)

Azure signalR
Azure signalRAzure signalR
Azure signalR
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
 
Game dev 101 part 2
Game dev 101   part 2Game dev 101   part 2
Game dev 101 part 2
 
Game dev workshop
Game dev workshopGame dev workshop
Game dev workshop
 
Deploying your static web app to the Cloud
Deploying your static web app to the CloudDeploying your static web app to the Cloud
Deploying your static web app to the Cloud
 
IaaS with ARM templates for Azure
IaaS with ARM templates for AzureIaaS with ARM templates for Azure
IaaS with ARM templates for Azure
 
Learning Svelte
Learning SvelteLearning Svelte
Learning Svelte
 
Ng spain
Ng spainNg spain
Ng spain
 
Angular Schematics
Angular SchematicsAngular Schematics
Angular Schematics
 
Design thinking
Design thinkingDesign thinking
Design thinking
 
Keynote ijs
Keynote ijsKeynote ijs
Keynote ijs
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and Vuex
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
Kendoui
KendouiKendoui
Kendoui
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Finjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster strongerFinjs - Angular 2 better faster stronger
Finjs - Angular 2 better faster stronger
 

Kürzlich hochgeladen

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Kürzlich hochgeladen (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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