SlideShare une entreprise Scribd logo
1  sur  52
Télécharger pour lire hors ligne
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!

Contenu connexe

Tendances

GraphQL Introduction
GraphQL IntroductionGraphQL Introduction
GraphQL IntroductionSerge Huber
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentationVibhor Grover
 
REST vs GraphQL
REST vs GraphQLREST vs GraphQL
REST vs GraphQLSquareboat
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Rafael Wilber Kerr
 
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
 
Building Modern APIs with GraphQL
Building Modern APIs with GraphQLBuilding Modern APIs with GraphQL
Building Modern APIs with GraphQLAmazon Web Services
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQLTomasz Bak
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservicesMohammed Shaban
 
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 GraphQLAppier
 
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
 

Tendances (20)

Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
GraphQL Introduction
GraphQL IntroductionGraphQL Introduction
GraphQL Introduction
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentation
 
REST vs GraphQL
REST vs GraphQLREST vs GraphQL
REST vs GraphQL
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)
 
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...
 
Intro GraphQL
Intro GraphQLIntro GraphQL
Intro GraphQL
 
Graphql
GraphqlGraphql
Graphql
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in Java
 
Building Modern APIs with GraphQL
Building Modern APIs with GraphQLBuilding Modern APIs with GraphQL
Building Modern APIs with GraphQL
 
GraphQL Fundamentals
GraphQL FundamentalsGraphQL Fundamentals
GraphQL Fundamentals
 
React & GraphQL
React & GraphQLReact & GraphQL
React & GraphQL
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQL
 
GraphQL
GraphQLGraphQL
GraphQL
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservices
 
How to GraphQL: React Apollo
How to GraphQL: React ApolloHow to GraphQL: React Apollo
How to GraphQL: React Apollo
 
Spring GraphQL
Spring GraphQLSpring GraphQL
Spring GraphQL
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Introduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SFIntroduction to GraphQL: Mobile Week SF
Introduction to GraphQL: Mobile Week SF
 

En vedette

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
 
GraphQL vs REST
GraphQL vs RESTGraphQL vs REST
GraphQL vs RESTGreeceJS
 
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
 

En vedette (19)

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?
 
GraphQL vs REST
GraphQL vs RESTGraphQL vs REST
GraphQL vs REST
 
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...
 

Similaire à 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
 

Similaire à 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
 

Dernier

WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 

Dernier (20)

WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 

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)