SlideShare uma empresa Scribd logo
1 de 52
Baixar para ler offline
Better APIs
with GraphQL
Josh Price
github.com/joshprice
@joshprice
Agenda
• Understand GraphQL and why you'd use it
• Build a simple schema
• Run queries against the schema
• Understand important GraphQL concepts
• Summarise client options
REST APIs
REST is great
REST is hard
Cargo Cults
Common Problems
Overfetching
Underfetching
Internal APIs have
strong contracts
between
client and server
GraphQL
What is GraphQL?
• Language for defining schemas, types & queries
• Developed by Facebook in 2012
• Used to improve mobile app performance
• Serves 300 billion+ requests per day
Open Source
• Open sourced in July 2015
• Specification
• facebook.github.io/graphql
• Reference Implementation
• github.com/graphql/graphql-js
• Relay released in August 2015
GraphQL Server Implementations
• JavaScript reference
• Ruby / Python / PHP
• Java / Scala (Sangria)
• .NET
• Elixir / Go / Haskell / OCaml
• etc...
GraphQL Misconceptions
• Not really about "graphs"
• A specification for client/server interaction
• Language independent
• Assumes nothing about:
• transport
• message protocol
• data store
Exhibit A: REST API
Fetch user name and friends names with 2 requests
GET /users/1
GET /users/1/friends
or a single request
GET /users/1/friends?include=user.name,friend.name
Exhibit B: GraphQL API
{ "data": {
user(id: 1) { "user": {
name "name": "Josh",
friends(first: 1) { "friends": [{
name "name": "James"
} }]
} }
} }
Better
Mental
Model
Strongly
typed
Single
Endpoint
Single
Unambiguous
Query
Consumer
Driven
Contracts
Less
Versioning
Self
Documenting
Performance
Let's build our
first Schema
Query and Mutation Roots
type Query {
me: User
user(id: Int): User
}
type Mutation {
createPost(title: String!): Post
createComment(message: String!): Comment
}
Object Types and Enums
type User {
name: String
profilePicture(size: Int = 50): ProfilePicture
friends(first: Int, orderBy: FriendOrder): [User]
}
enum FriendOrder { FIRST_NAME, LAST_NAME, IMPORTANCE }
More Types
type ProfilePicture {
width: Int
height: Int
url: String
}
type Event {
name: String
attendees(first: Int): [User]
}
Simplest Query
{
me {
name
}
}
{
"data": {
"me": {
"name": "Josh Price"
}
}
}
Deeply Nested Query
{ {
me { "data": {
name "name": "Josh Price",
profilePicture { "profilePicture": {
url "url": "http://cdn/josh_50x50.png"
} },
friends(first: 1) { "friends": [{
name "name": "James Sadler"
} }],
events(first: 1) { "events": [{
name "name": "Afterparty!",
attendees(first: 1) { "attendees": [{
name "name": "Jenny Savage"
} }]
} }]
} }
} }
How do we fetch
data?
Resolvers
• Your own functions
• Could use in memory data
• Call any data store
• Proxy REST APIs
• Call existing services
• GraphQL doesn't care
• Resolver "Middleware" is possible (Auth, Logging, etc)
User Type with JS Resolvers
new GraphQLObject({
type: "User",
fields: {
name(user) {
return user.name
},
profilePicture(user, {size}) {
return getProfilePicForUser(user, size);
},
friends(user) {
return user.friendIDs.map(id => getUser(id));
}
}
});
Mutations Modify Data
mutation {
acceptFriendRequest(userId: 345124) {
user {
friends { count }
}
}
}
mutation {
rsvpToEvent(eventId: 134624, status: ATTENDING) {
event {
invitees { count }
attendees { count }
}
}
}
Setup GraphQL Express
import { Schema } from './schema.js';
import graphqlHTTP from 'express-graphql';
import express from 'express';
const app = express();
app.get('/', function(req, res) {
res.redirect('/graphql');
});
app.use('/graphql', graphqlHTTP({ schema: Schema, graphiql: true }));
app.listen(3000);
Relay
• Each view component declares query fragment
• Relay batches all data req'ts for render tree
• Sends single query
• Handles caching using global IDs
• Relies on schema conventions for metadata
Client-Side Alternatives
• ApolloStack Client
• React + Native
• Angular 2
• Redux support
• Lokka
• Simple
Gotchas
• Arbitrary Queries
• Could be slow if deeply nested (friends of friends...)
• Complexity analysis
• Query depth
• Batching resolvers
• Data Loader (JS)
• GraphQL Batch (Ruby)
When to use?
• Use for internal APIs first, or limited external use
• Improve mobile (and desktop performance)
• Github has exposed their API externally
• Be careful exposing this to the world!
• Don't allow arbitrary queries from unknown clients
GraphQL Ecosystem
Evolving Quickly
GraphQL Backend as a Service
• reindex.io
• graph.cool
• scaphold.io
Future - GraphQL Spec
• Push: Apps should reflect current state of world
• Subscriptions + Reactive Backend + RethinkDB
• Defer
• Stream
• Live queries
• GraphQL CATS
Subscriptions
subscription {
createCommentSubscribe(storyId: $id) {
comment {
...FBCommentFragment
}
}
}
Warning!
Experimental
Defer Directive
{ {
feed { "feed": {
stories { "stories": [{
author { name } "author": { "name": "Lee Byron" },
title "title": "GraphQL is the Future"
comments @defer { }, {
author { name } "author": { "name": "Josh Price" },
comment "title": "REST is old school"
} }]
} }
} }
}
Defer - Comments arrive
{ {
feed { "path": ["feed", "stories", 0, "comment"],
stories { "data": [{
author { name } "author": { "name": "Joe Bloggs" },
title "comment": "That blew my mind!"
comments @defer { }, {
author { name } "author": { "name": "Jenny Savage" },
comment "comment": "I love it"
} }]
} }
}
}
Stream Directive
{ {
feed { "feed": {
stories @stream { "stories": []
author { name } }
title }
comments @defer {
author { name }
comment
}
}
}
}
Stream - First Story
{ {
feed { "path": ["feed", "stories", 0],
stories @stream { "data": [{
author { name } "author": { "name": "Joe Bloggs" },
title "title": "That blew my mind!"
comments @defer { }]
author { name } }
comment
}
}
}
}
Live Directive
{ {
feed { "feed": {
stories { "stories": [{
author { name } "author": { "name": "Lee Byron" },
title "title": "GraphQL is the Future",
likeCount @live "likeCount": 9
} }]
} }
} }
Live - Likes update on backend
{ {
feed { "path": ["feed", "stories", 0, "likeCount"],
stories { "data": 10
author { name } }
title
likeCount @live
}
}
}
Resources
• graphql.org
• Github
• graphql/graphql-js
• graphql/express-graphql
• Steve Luscher talk Zero to GraphQL
• Awesome GraphQL (chentsulin/awesome-graphql)
Questions?
Thanks!

Mais conteúdo relacionado

Mais procurados

Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Hafiz Ismail
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQLTomasz Bak
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentationVibhor Grover
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQLMuhilvarnan V
 
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...luisw19
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaMarcinStachniuk
 
How to GraphQL: React Apollo
How to GraphQL: React ApolloHow to GraphQL: React Apollo
How to GraphQL: React ApolloTomasz Bak
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLRodrigo Prates
 
Building Modern APIs with GraphQL
Building Modern APIs with GraphQLBuilding Modern APIs with GraphQL
Building Modern APIs with GraphQLAmazon Web Services
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservicesMohammed Shaban
 
Introduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SFIntroduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SFAmazon Web Services
 
GraphQL vs REST
GraphQL vs RESTGraphQL vs REST
GraphQL vs RESTGreeceJS
 

Mais procurados (20)

Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
Introduction to GraphQL (or How I Learned to Stop Worrying about REST APIs)
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQL
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentation
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQL
 
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
GraphQL as an alternative approach to REST (as presented at Java2Days/CodeMon...
 
React & GraphQL
React & GraphQLReact & GraphQL
React & GraphQL
 
Intro GraphQL
Intro GraphQLIntro GraphQL
Intro GraphQL
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in Java
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
How to GraphQL: React Apollo
How to GraphQL: React ApolloHow to GraphQL: React Apollo
How to GraphQL: React Apollo
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Building Modern APIs with GraphQL
Building Modern APIs with GraphQLBuilding Modern APIs with GraphQL
Building Modern APIs with GraphQL
 
GraphQL
GraphQLGraphQL
GraphQL
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservices
 
GraphQL Fundamentals
GraphQL FundamentalsGraphQL Fundamentals
GraphQL Fundamentals
 
Introduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SFIntroduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SF
 
Graphql
GraphqlGraphql
Graphql
 
GraphQL vs REST
GraphQL vs RESTGraphQL vs REST
GraphQL vs REST
 

Destaque

GraphQL Story: Intro To GraphQL
GraphQL Story: Intro To GraphQLGraphQL Story: Intro To GraphQL
GraphQL Story: Intro To GraphQLRiza Fahmi
 
GraphQL in an Age of REST
GraphQL in an Age of RESTGraphQL in an Age of REST
GraphQL in an Age of RESTYos Riady
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLBrainhub
 
Enterprise API deployment best practice
Enterprise API deployment best practiceEnterprise API deployment best practice
Enterprise API deployment best practiceSanjay Roy
 
API Introduction - API Management Workshop Munich from Ronnie Mitra
API Introduction - API Management Workshop Munich from Ronnie MitraAPI Introduction - API Management Workshop Munich from Ronnie Mitra
API Introduction - API Management Workshop Munich from Ronnie MitraCA API Management
 
API Athens Meetup - API standards 25-6-2014
API Athens Meetup - API standards   25-6-2014API Athens Meetup - API standards   25-6-2014
API Athens Meetup - API standards 25-6-2014Michael Petychakis
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API DesignLorna Mitchell
 
Migration microservices to GraphQL
Migration microservices to GraphQLMigration microservices to GraphQL
Migration microservices to GraphQLRoman Krivtsov
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JSEueung Mulyana
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.jsTechExeter
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to VuejsPaddy Lock
 
Groovier testing with Spock
Groovier testing with SpockGroovier testing with Spock
Groovier testing with SpockRobert Fletcher
 
Another API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger ComparisonAnother API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger ComparisonSmartBear
 
API Athens Meetup - API standards 22.03.2016
API Athens Meetup - API standards 22.03.2016API Athens Meetup - API standards 22.03.2016
API Athens Meetup - API standards 22.03.2016Ivan Goncharov
 
Enhance existing REST APIs (e.g. Facebook Graph API) with code completion us...
Enhance existing REST APIs  (e.g. Facebook Graph API) with code completion us...Enhance existing REST APIs  (e.g. Facebook Graph API) with code completion us...
Enhance existing REST APIs (e.g. Facebook Graph API) with code completion us...johannes_fiala
 

Destaque (18)

GraphQL Story: Intro To GraphQL
GraphQL Story: Intro To GraphQLGraphQL Story: Intro To GraphQL
GraphQL Story: Intro To GraphQL
 
GraphQL in an Age of REST
GraphQL in an Age of RESTGraphQL in an Age of REST
GraphQL in an Age of REST
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Enterprise API deployment best practice
Enterprise API deployment best practiceEnterprise API deployment best practice
Enterprise API deployment best practice
 
API Introduction - API Management Workshop Munich from Ronnie Mitra
API Introduction - API Management Workshop Munich from Ronnie MitraAPI Introduction - API Management Workshop Munich from Ronnie Mitra
API Introduction - API Management Workshop Munich from Ronnie Mitra
 
API Athens Meetup - API standards 25-6-2014
API Athens Meetup - API standards   25-6-2014API Athens Meetup - API standards   25-6-2014
API Athens Meetup - API standards 25-6-2014
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
Migration microservices to GraphQL
Migration microservices to GraphQLMigration microservices to GraphQL
Migration microservices to GraphQL
 
Vue JS Intro
Vue JS IntroVue JS Intro
Vue JS Intro
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
Why Vue.js?
Why Vue.js?Why Vue.js?
Why Vue.js?
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to Vuejs
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 
Groovier testing with Spock
Groovier testing with SpockGroovier testing with Spock
Groovier testing with Spock
 
Another API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger ComparisonAnother API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger Comparison
 
API Athens Meetup - API standards 22.03.2016
API Athens Meetup - API standards 22.03.2016API Athens Meetup - API standards 22.03.2016
API Athens Meetup - API standards 22.03.2016
 
Enhance existing REST APIs (e.g. Facebook Graph API) with code completion us...
Enhance existing REST APIs  (e.g. Facebook Graph API) with code completion us...Enhance existing REST APIs  (e.g. Facebook Graph API) with code completion us...
Enhance existing REST APIs (e.g. Facebook Graph API) with code completion us...
 

Semelhante a Better APIs with GraphQL

Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)Shift Conference
 
Overview of GraphQL & Clients
Overview of GraphQL & ClientsOverview of GraphQL & Clients
Overview of GraphQL & ClientsPokai Chang
 
Data Driven Application with GraphQL and AWS App Sync
Data Driven Application with GraphQL and AWS App SyncData Driven Application with GraphQL and AWS App Sync
Data Driven Application with GraphQL and AWS App SyncAmazon Web Services
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responsesdarrelmiller71
 
Building Serverless GraphQL Backends
Building Serverless GraphQL BackendsBuilding Serverless GraphQL Backends
Building Serverless GraphQL BackendsNikolas Burk
 
Build Data Driven Apps with Real-time and Offline Capabilities
Build Data Driven Apps with Real-time and Offline CapabilitiesBuild Data Driven Apps with Real-time and Offline Capabilities
Build Data Driven Apps with Real-time and Offline CapabilitiesAmazon Web Services
 
London React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparLondon React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparReact London Community
 
Diving into GraphQL, React & Apollo
Diving into GraphQL, React & ApolloDiving into GraphQL, React & Apollo
Diving into GraphQL, React & ApolloNikolas Burk
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionVMware Tanzu
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB
 
The Serverless GraphQL Backend Architecture
The Serverless GraphQL Backend ArchitectureThe Serverless GraphQL Backend Architecture
The Serverless GraphQL Backend ArchitectureNikolas Burk
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPAndrew Rota
 
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
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009Jason Davies
 
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 - an elegant weapon... for more civilized age
GraphQL - an elegant weapon... for more civilized ageGraphQL - an elegant weapon... for more civilized age
GraphQL - an elegant weapon... for more civilized ageBartosz Sypytkowski
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHPAndrew Rota
 

Semelhante a Better APIs with GraphQL (20)

Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
Shift Remote: WEB - GraphQL and React – Quick Start - Dubravko Bogovic (Infobip)
 
Overview of GraphQL & Clients
Overview of GraphQL & ClientsOverview of GraphQL & Clients
Overview of GraphQL & Clients
 
Data Driven Application with GraphQL and AWS App Sync
Data Driven Application with GraphQL and AWS App SyncData Driven Application with GraphQL and AWS App Sync
Data Driven Application with GraphQL and AWS App Sync
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Building Serverless GraphQL Backends
Building Serverless GraphQL BackendsBuilding Serverless GraphQL Backends
Building Serverless GraphQL Backends
 
Graphql usage
Graphql usageGraphql usage
Graphql usage
 
Build Data Driven Apps with Real-time and Offline Capabilities
Build Data Driven Apps with Real-time and Offline CapabilitiesBuild Data Driven Apps with Real-time and Offline Capabilities
Build Data Driven Apps with Real-time and Offline Capabilities
 
London React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparLondon React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor Charypar
 
Diving into GraphQL, React & Apollo
Diving into GraphQL, React & ApolloDiving into GraphQL, React & Apollo
Diving into GraphQL, React & Apollo
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
 
The Serverless GraphQL Backend Architecture
The Serverless GraphQL Backend ArchitectureThe Serverless GraphQL Backend Architecture
The Serverless GraphQL Backend Architecture
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHP
 
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
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009
 
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
 
Hands On - GraphQL
Hands On - GraphQLHands On - GraphQL
Hands On - GraphQL
 
GraphQL - an elegant weapon... for more civilized age
GraphQL - an elegant weapon... for more civilized ageGraphQL - an elegant weapon... for more civilized age
GraphQL - an elegant weapon... for more civilized age
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHP
 

Último

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Último (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

Better APIs with GraphQL

  • 1. Better APIs with GraphQL Josh Price github.com/joshprice @joshprice
  • 2. Agenda • Understand GraphQL and why you'd use it • Build a simple schema • Run queries against the schema • Understand important GraphQL concepts • Summarise client options
  • 8. Internal APIs have strong contracts between client and server
  • 10. What is GraphQL? • Language for defining schemas, types & queries • Developed by Facebook in 2012 • Used to improve mobile app performance • Serves 300 billion+ requests per day
  • 11. Open Source • Open sourced in July 2015 • Specification • facebook.github.io/graphql • Reference Implementation • github.com/graphql/graphql-js • Relay released in August 2015
  • 12. GraphQL Server Implementations • JavaScript reference • Ruby / Python / PHP • Java / Scala (Sangria) • .NET • Elixir / Go / Haskell / OCaml • etc...
  • 13. GraphQL Misconceptions • Not really about "graphs" • A specification for client/server interaction • Language independent • Assumes nothing about: • transport • message protocol • data store
  • 14. Exhibit A: REST API Fetch user name and friends names with 2 requests GET /users/1 GET /users/1/friends or a single request GET /users/1/friends?include=user.name,friend.name
  • 15. Exhibit B: GraphQL API { "data": { user(id: 1) { "user": { name "name": "Josh", friends(first: 1) { "friends": [{ name "name": "James" } }] } } } }
  • 25. Query and Mutation Roots type Query { me: User user(id: Int): User } type Mutation { createPost(title: String!): Post createComment(message: String!): Comment }
  • 26. Object Types and Enums type User { name: String profilePicture(size: Int = 50): ProfilePicture friends(first: Int, orderBy: FriendOrder): [User] } enum FriendOrder { FIRST_NAME, LAST_NAME, IMPORTANCE }
  • 27. More Types type ProfilePicture { width: Int height: Int url: String } type Event { name: String attendees(first: Int): [User] }
  • 28. Simplest Query { me { name } } { "data": { "me": { "name": "Josh Price" } } }
  • 29. Deeply Nested Query { { me { "data": { name "name": "Josh Price", profilePicture { "profilePicture": { url "url": "http://cdn/josh_50x50.png" } }, friends(first: 1) { "friends": [{ name "name": "James Sadler" } }], events(first: 1) { "events": [{ name "name": "Afterparty!", attendees(first: 1) { "attendees": [{ name "name": "Jenny Savage" } }] } }] } } } }
  • 30. How do we fetch data?
  • 31. Resolvers • Your own functions • Could use in memory data • Call any data store • Proxy REST APIs • Call existing services • GraphQL doesn't care • Resolver "Middleware" is possible (Auth, Logging, etc)
  • 32. User Type with JS Resolvers new GraphQLObject({ type: "User", fields: { name(user) { return user.name }, profilePicture(user, {size}) { return getProfilePicForUser(user, size); }, friends(user) { return user.friendIDs.map(id => getUser(id)); } } });
  • 33. Mutations Modify Data mutation { acceptFriendRequest(userId: 345124) { user { friends { count } } } } mutation { rsvpToEvent(eventId: 134624, status: ATTENDING) { event { invitees { count } attendees { count } } } }
  • 34. Setup GraphQL Express import { Schema } from './schema.js'; import graphqlHTTP from 'express-graphql'; import express from 'express'; const app = express(); app.get('/', function(req, res) { res.redirect('/graphql'); }); app.use('/graphql', graphqlHTTP({ schema: Schema, graphiql: true })); app.listen(3000);
  • 35. Relay • Each view component declares query fragment • Relay batches all data req'ts for render tree • Sends single query • Handles caching using global IDs • Relies on schema conventions for metadata
  • 36. Client-Side Alternatives • ApolloStack Client • React + Native • Angular 2 • Redux support • Lokka • Simple
  • 37. Gotchas • Arbitrary Queries • Could be slow if deeply nested (friends of friends...) • Complexity analysis • Query depth • Batching resolvers • Data Loader (JS) • GraphQL Batch (Ruby)
  • 38. When to use? • Use for internal APIs first, or limited external use • Improve mobile (and desktop performance) • Github has exposed their API externally • Be careful exposing this to the world! • Don't allow arbitrary queries from unknown clients
  • 40. GraphQL Backend as a Service • reindex.io • graph.cool • scaphold.io
  • 41. Future - GraphQL Spec • Push: Apps should reflect current state of world • Subscriptions + Reactive Backend + RethinkDB • Defer • Stream • Live queries • GraphQL CATS
  • 44. Defer Directive { { feed { "feed": { stories { "stories": [{ author { name } "author": { "name": "Lee Byron" }, title "title": "GraphQL is the Future" comments @defer { }, { author { name } "author": { "name": "Josh Price" }, comment "title": "REST is old school" } }] } } } } }
  • 45. Defer - Comments arrive { { feed { "path": ["feed", "stories", 0, "comment"], stories { "data": [{ author { name } "author": { "name": "Joe Bloggs" }, title "comment": "That blew my mind!" comments @defer { }, { author { name } "author": { "name": "Jenny Savage" }, comment "comment": "I love it" } }] } } } }
  • 46. Stream Directive { { feed { "feed": { stories @stream { "stories": [] author { name } } title } comments @defer { author { name } comment } } } }
  • 47. Stream - First Story { { feed { "path": ["feed", "stories", 0], stories @stream { "data": [{ author { name } "author": { "name": "Joe Bloggs" }, title "title": "That blew my mind!" comments @defer { }] author { name } } comment } } } }
  • 48. Live Directive { { feed { "feed": { stories { "stories": [{ author { name } "author": { "name": "Lee Byron" }, title "title": "GraphQL is the Future", likeCount @live "likeCount": 9 } }] } } } }
  • 49. Live - Likes update on backend { { feed { "path": ["feed", "stories", 0, "likeCount"], stories { "data": 10 author { name } } title likeCount @live } } }
  • 50. Resources • graphql.org • Github • graphql/graphql-js • graphql/express-graphql • Steve Luscher talk Zero to GraphQL • Awesome GraphQL (chentsulin/awesome-graphql)