SlideShare uma empresa Scribd logo
1 de 62
Baixar para ler offline
GraphQL in an Age of REST
Yos Riady
yos.io
goo.gl/prnEnz
Disclaimer
A step-by-step
walkthrough of building
a GraphQL server
Drawbacks to building
Web APIs with REST
Background REST GraphQL Code Next Steps
An overview of
GraphQL, with
examples
Further learning, future
improvements, and
conclusion
The current state of
Web APIs
An API is a user interface for
developers - so put some effort
into making it pleasant.
Background
Web APIs are eating the world
A step-by-step
walkthrough of building
a GraphQL server
Drawbacks to building
Web APIs with REST
Background REST GraphQL Code Next Steps
An overview of
GraphQL, with
examples
Further learning, future
improvements, and
conclusion
The current state of
Web APIs
Introduction to REST
Separate your API to logical resources. Map actions to HTTP methods and URIs.
● GET /posts - Retrieves a list of posts
● GET /posts/12 - Retrieves a specific post
● POST /posts - Creates a new post
● PUT /posts/12 - Updates post #12
● PATCH /posts/12 - Partially updates post #12
● DELETE /posts/12 - Deletes post #12
Posts
Posts
Users
Comments
A HackerNews-like Data Model
author_id
post_id
body
Comment
author_id
title
url
published_at
votes
Post
name
joined_at
UserPOST /posts
GET /posts/1
PUT /posts/1
DELETE /posts/1
GET /posts/1/author
GET /posts/1/comments
POST /users
GET /users/1
PUT /users/1
DELETE /users/1
GET /users/1/posts
GET /users/1/comments
POST /comments
GET /comments/1
PUT /comments/1
DELETE /comments/1
Let’s try using our API
Retrieve a list of posts
GET /posts
{
“posts”: [{
“id”: 1
“author_id”: 101,
“title”: “GraphQL in an Age of REST”,
“body”: “lorem ipsum”,
“votes”: 342,
“published_at”: “2016-10-11T16:53:28+00:00”
},
...
]
}
Retrieve a list of posts
GET /posts
GET /users/101
{
“user”: {
“id”: 101
“name”: “yosriady”,
“joined_at”: “2015-10-11T16:53:28+00:00”
}
}
Retrieve a list of posts
GET /posts
GET /users/101
GET /users/102
GET /users/103
...
Problem: Multiple roundtrips
There are many cases where an API consumer needs to load data related to the
resource being requested.
GET /posts/1?embed=author.name
{
“post”: {
“id”: 1
...
“author”: {
“name”: “yosriady”
}
}
}
Solution: Autoload related resources
Another Problem: Over-fetching of data
APIs often return a huge JSON object with many fields, even when we only use a
handful.
Solution: Clients should be able to specify the fields they only need.
GET /posts/1?fields=title,link,published_at
Solution: Custom Endpoints
Your API
DB 1
DB 2
v1
v2
v1
v2
v3
Problem: Custom Endpoints
/posts_with_everything_i_need
/posts_with_everything_i_need_with_author_v2
/posts_with_everything_for_samsung_smart_tv
/tightly_coupled_endpoint_for_a_specific_client
Whoa! We end up with a lot of endpoints.
An API is only as good as its
documentation.
Problem: How will users learn our API?
● Users
○ API consumers
○ Developers from other teams
○ New hires
● Documentation must cover:
○ What resources does the API manage?
○ What actions can I perform?
○ Endpoint parameters
■ Required
■ Optional
■ Attribute Types
● API Specification languages
○ OpenAPI (fka Swagger)
○ API Blueprint
○ JSON Schema
● Third-party services
● Benefits
○ Auto-generated documentation
○ Auto-generated Server stubs
○ Auto-generated Client code
Solution: API Specifications
Summary: Drawbacks of REST
APIs need to be documented
well enough for consumers to
be able to discover and learn it
on their own.
Documentation
/tightly_coupled_endpoi
nt_for_a_specific_clien
t
REST APIs are rigid.
Over-fetching. Custom
endpoints lead to bloat.
Custom endpoints
GET /posts/1
GET /comments/1001
GET /comments/1002
Getting the data you need can
require multiple REST calls
away.
Multiple round trips
A step-by-step
walkthrough of building
a GraphQL server
Drawbacks to building
Web APIs with REST
Background REST GraphQL Code Next Steps
An overview of
GraphQL, with
examples
Further learning, future
improvements, and
conclusion
The current state of
Web APIs
GraphQL
Introduction to GraphQL
● A declarative (1) query language, (2) type system, and (3) runtime for client
applications to fetch and mutate data.
● Devised to solve some of the problems with REST
○ Originally used by the Facebook Product team
● Data store independent
● Language and platform independent
It’s Graphs All the Way Down
It’s Graphs All the Way Down
Queries have the same shape as its result
Here is a (1) GraphQL Query and its response:
{
post(id: 1) {
title
url
author {
name
}
}
}
{
"post": {
"title": "GraphQL in an Age of REST",
"url”: “http://yos.io”,
“author”: {
“name”: “yosriady”
}
}
}
Power to the client instead of the server
The client specifies what data it
needs, and the server does only what
is necessary to return that data.
/graphql
goo.gl/nV3WJE goo.gl/nV3WJE
Great API documentation
drives adoption.
The (2) Type System makes all of
this possible
Schema Language
type Post {
title: String!
author: User!
comments:[Comment]!
}
type Query {
post(id: Int): Post
posts: Post
}
Types
● Scalar types
○ Boolean
○ Int
○ Float
○ String
○ Custom types i.e. Date
● Enums
● Lists
● Interfaces
● Unions
Summary: Benefits of GraphQL
API playground
Client-side validation
Self-documenting
Introspective
Adapts to different
requirements for different
clients
Client-specified
Query from multiple data
sources in a single network
request.
Single round trip
A step-by-step
walkthrough of building
a GraphQL server
Drawbacks to building
Web APIs with REST
Background REST GraphQL Code Next Steps
An overview of
GraphQL, with
examples
Further learning, future
improvements, and
conclusion
The current state of
Web APIs
Building a GraphQL Server
in Node.js
Preamble
A GraphQL service is created by providing (a) the schema and (b) resolver
functions.
● We’ll use
○ Node.js + Express
○ express-graphql
Preamble
● Bindings are available for all major languages
○ Javascript
○ Ruby
○ PHP
○ Python
○ Java
○ C/C++
○ Go
○ Scala
○ .NET
○ Elixir
○ Haskell
○ SQL
○ Lua
○ Elm
○ Clojure
yos-graphql.surge.sh
A GraphQL Schema Definition
const User = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLInt },
name: { type: GraphQLString }
})
});
Creates links between data sources and GraphQL fields
posts(id){
return request(`https://api.blog.io/posts/${id}`);
}
posts(id){
return sql.raw('SELECT * FROM posts WHERE id = %s',id);
}
posts(id){
return DB.Posts.getById(id);
}
GraphQL Resolvers
A step-by-step
walkthrough of building
a GraphQL server
Drawbacks to building
Web APIs with REST
Background REST GraphQL Code Next Steps
An overview of
GraphQL, with
examples
Further learning, future
improvements, and
conclusion
The current state of
Web APIs
● Give GraphQL a try, especially if
○ Your product is an API
○ You have many clients with flexible requirements
● Features not covered in this talk
○ Aliases,
○ Fragments,
○ Variables,
○ Directives, etc.
● Best practices still emerging
In Closing
meetup.com/API-Craft-Singapore
Thanks
Yos Riady
yos.io
Questions?
Yos Riady
yos.io
Appendix 0: Differences from REST
● A single endpoint `/graphql`
● Only HTTP verbs GET and POST are used
○ GET for queries
○ POST for mutations
● Support for other transport layers
○ MQTT for IOT domains
Appendix 1: Versioning
“We encourage GraphQL endpoints to take an add-only approach to schema
evolution over time instead of changing existing fields.”
GraphQL takes a strong opinion on avoiding versioning by providing the tools for
the continuous evolution of a GraphQL schema.
Appendix 2: Cons of GraphQL
● Initial investment may not make sense where
○ APIs are internal -> use RPC
○ API changes are rare (APIs are stable)
● Performance
○ Compared to RPC

Mais conteúdo relacionado

Mais procurados

The Apollo and GraphQL Stack
The Apollo and GraphQL StackThe Apollo and GraphQL Stack
The Apollo and GraphQL Stack
Sashko Stubailo
 

Mais procurados (20)

Graphql
GraphqlGraphql
Graphql
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
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
 
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)
 
Taking Control of your Data with GraphQL
Taking Control of your Data with GraphQLTaking Control of your Data with GraphQL
Taking Control of your Data with GraphQL
 
GraphQL With Relay Part Deux
GraphQL With Relay Part DeuxGraphQL With Relay Part Deux
GraphQL With Relay Part Deux
 
GraphQL Story: Intro To GraphQL
GraphQL Story: Intro To GraphQLGraphQL Story: Intro To GraphQL
GraphQL Story: Intro To GraphQL
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
 
GraphQL IndyJS April 2016
GraphQL IndyJS April 2016GraphQL IndyJS April 2016
GraphQL IndyJS April 2016
 
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/MeteorWhy UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
 
Performance optimisation with GraphQL
Performance optimisation with GraphQLPerformance optimisation with GraphQL
Performance optimisation with GraphQL
 
GraphQL Introduction
GraphQL IntroductionGraphQL Introduction
GraphQL Introduction
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentation
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherGraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
 
GraphQL Search
GraphQL SearchGraphQL Search
GraphQL Search
 
Modular GraphQL with Schema Stitching
Modular GraphQL with Schema StitchingModular GraphQL with Schema Stitching
Modular GraphQL with Schema Stitching
 
The Apollo and GraphQL Stack
The Apollo and GraphQL StackThe Apollo and GraphQL Stack
The Apollo and GraphQL Stack
 
GraphQL, Redux, and React
GraphQL, Redux, and ReactGraphQL, Redux, and React
GraphQL, Redux, and React
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQL
 

Destaque

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
Michael Petychakis
 

Destaque (18)

GraphQL - APIs mais robustas e flexíveis
GraphQL - APIs mais robustas e flexíveisGraphQL - APIs mais robustas e flexíveis
GraphQL - APIs mais robustas e flexíveis
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
 
Lists
ListsLists
Lists
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
GraphQL: The Missing Link Between Frontend and Backend Devs
GraphQL: The Missing Link Between Frontend and Backend DevsGraphQL: The Missing Link Between Frontend and Backend Devs
GraphQL: The Missing Link Between Frontend and Backend Devs
 
Work with V8 memory leaks
Work with V8 memory leaksWork with V8 memory leaks
Work with V8 memory leaks
 
Enterprise API deployment best practice
Enterprise API deployment best practiceEnterprise API deployment best practice
Enterprise API deployment best practice
 
Why UI developers love GraphQL
Why UI developers love GraphQLWhy UI developers love GraphQL
Why UI developers love GraphQL
 
Building a Big Data Pipeline
Building a Big Data PipelineBuilding a Big Data Pipeline
Building a Big Data Pipeline
 
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
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
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
 
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
 

Semelhante a GraphQL in an Age of REST

Semelhante a GraphQL in an Age of REST (20)

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 usage
Graphql usageGraphql usage
Graphql usage
 
Modern APIs with GraphQL
Modern APIs with GraphQLModern APIs with GraphQL
Modern APIs with GraphQL
 
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
 
JSON API Specificiation
JSON API SpecificiationJSON API Specificiation
JSON API Specificiation
 
Exposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIsExposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIs
 
Hands On - GraphQL
Hands On - GraphQLHands On - GraphQL
Hands On - GraphQL
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
GraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessGraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database access
 
GraphQL the holy contract between client and server
GraphQL the holy contract between client and serverGraphQL the holy contract between client and server
GraphQL the holy contract between client and server
 
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
 
GraphQL API Crafts presentation
GraphQL API Crafts presentationGraphQL API Crafts presentation
GraphQL API Crafts presentation
 
Introduction to Graph QL
Introduction to Graph QLIntroduction to Graph QL
Introduction to Graph QL
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPC
 
CONDG April 23 2020 - Baskar Rao - GraphQL
CONDG April 23 2020 - Baskar Rao - GraphQLCONDG April 23 2020 - Baskar Rao - GraphQL
CONDG April 23 2020 - Baskar Rao - GraphQL
 
Exploring Relay land
Exploring Relay landExploring Relay land
Exploring Relay land
 
GDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJSGDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJS
 
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...
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
 
GraphQL @ Manc.JS (March 2018)
GraphQL @ Manc.JS (March 2018)GraphQL @ Manc.JS (March 2018)
GraphQL @ Manc.JS (March 2018)
 

Mais de Yos Riady

Mais de Yos Riady (9)

Brief introduction to Serverless (2018)
Brief introduction to Serverless (2018)Brief introduction to Serverless (2018)
Brief introduction to Serverless (2018)
 
Type Checking in Javascript with Flow
Type Checking in Javascript with FlowType Checking in Javascript with Flow
Type Checking in Javascript with Flow
 
Schema-First API Design
Schema-First API DesignSchema-First API Design
Schema-First API Design
 
Writing Domain Specific Languages with JSON Schema
Writing Domain Specific Languages with JSON SchemaWriting Domain Specific Languages with JSON Schema
Writing Domain Specific Languages with JSON Schema
 
Ruby on Rails Workshop
Ruby on Rails WorkshopRuby on Rails Workshop
Ruby on Rails Workshop
 
Online Payments and You
Online Payments and YouOnline Payments and You
Online Payments and You
 
Entity Component Systems
Entity Component SystemsEntity Component Systems
Entity Component Systems
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
Intro to Web Map APIs
Intro to Web Map APIsIntro to Web Map APIs
Intro to Web Map APIs
 

Último

Último (20)

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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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)
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

GraphQL in an Age of REST

  • 1. GraphQL in an Age of REST Yos Riady yos.io goo.gl/prnEnz
  • 3. A step-by-step walkthrough of building a GraphQL server Drawbacks to building Web APIs with REST Background REST GraphQL Code Next Steps An overview of GraphQL, with examples Further learning, future improvements, and conclusion The current state of Web APIs
  • 4. An API is a user interface for developers - so put some effort into making it pleasant.
  • 6. Web APIs are eating the world
  • 7.
  • 8. A step-by-step walkthrough of building a GraphQL server Drawbacks to building Web APIs with REST Background REST GraphQL Code Next Steps An overview of GraphQL, with examples Further learning, future improvements, and conclusion The current state of Web APIs
  • 9. Introduction to REST Separate your API to logical resources. Map actions to HTTP methods and URIs. ● GET /posts - Retrieves a list of posts ● GET /posts/12 - Retrieves a specific post ● POST /posts - Creates a new post ● PUT /posts/12 - Updates post #12 ● PATCH /posts/12 - Partially updates post #12 ● DELETE /posts/12 - Deletes post #12
  • 10.
  • 11. Posts
  • 13. A HackerNews-like Data Model author_id post_id body Comment author_id title url published_at votes Post name joined_at UserPOST /posts GET /posts/1 PUT /posts/1 DELETE /posts/1 GET /posts/1/author GET /posts/1/comments POST /users GET /users/1 PUT /users/1 DELETE /users/1 GET /users/1/posts GET /users/1/comments POST /comments GET /comments/1 PUT /comments/1 DELETE /comments/1
  • 14.
  • 15.
  • 16. Let’s try using our API
  • 17.
  • 18. Retrieve a list of posts GET /posts { “posts”: [{ “id”: 1 “author_id”: 101, “title”: “GraphQL in an Age of REST”, “body”: “lorem ipsum”, “votes”: 342, “published_at”: “2016-10-11T16:53:28+00:00” }, ... ] }
  • 19. Retrieve a list of posts GET /posts GET /users/101 { “user”: { “id”: 101 “name”: “yosriady”, “joined_at”: “2015-10-11T16:53:28+00:00” } }
  • 20. Retrieve a list of posts GET /posts GET /users/101 GET /users/102 GET /users/103 ...
  • 22.
  • 23.
  • 24. There are many cases where an API consumer needs to load data related to the resource being requested. GET /posts/1?embed=author.name { “post”: { “id”: 1 ... “author”: { “name”: “yosriady” } } } Solution: Autoload related resources
  • 25. Another Problem: Over-fetching of data APIs often return a huge JSON object with many fields, even when we only use a handful. Solution: Clients should be able to specify the fields they only need. GET /posts/1?fields=title,link,published_at
  • 26. Solution: Custom Endpoints Your API DB 1 DB 2 v1 v2 v1 v2 v3
  • 28. An API is only as good as its documentation.
  • 29. Problem: How will users learn our API? ● Users ○ API consumers ○ Developers from other teams ○ New hires ● Documentation must cover: ○ What resources does the API manage? ○ What actions can I perform? ○ Endpoint parameters ■ Required ■ Optional ■ Attribute Types
  • 30. ● API Specification languages ○ OpenAPI (fka Swagger) ○ API Blueprint ○ JSON Schema ● Third-party services ● Benefits ○ Auto-generated documentation ○ Auto-generated Server stubs ○ Auto-generated Client code Solution: API Specifications
  • 31. Summary: Drawbacks of REST APIs need to be documented well enough for consumers to be able to discover and learn it on their own. Documentation /tightly_coupled_endpoi nt_for_a_specific_clien t REST APIs are rigid. Over-fetching. Custom endpoints lead to bloat. Custom endpoints GET /posts/1 GET /comments/1001 GET /comments/1002 Getting the data you need can require multiple REST calls away. Multiple round trips
  • 32. A step-by-step walkthrough of building a GraphQL server Drawbacks to building Web APIs with REST Background REST GraphQL Code Next Steps An overview of GraphQL, with examples Further learning, future improvements, and conclusion The current state of Web APIs
  • 34. Introduction to GraphQL ● A declarative (1) query language, (2) type system, and (3) runtime for client applications to fetch and mutate data. ● Devised to solve some of the problems with REST ○ Originally used by the Facebook Product team ● Data store independent ● Language and platform independent
  • 35. It’s Graphs All the Way Down
  • 36. It’s Graphs All the Way Down
  • 37. Queries have the same shape as its result Here is a (1) GraphQL Query and its response: { post(id: 1) { title url author { name } } } { "post": { "title": "GraphQL in an Age of REST", "url”: “http://yos.io”, “author”: { “name”: “yosriady” } } }
  • 38. Power to the client instead of the server The client specifies what data it needs, and the server does only what is necessary to return that data.
  • 40.
  • 42.
  • 44. The (2) Type System makes all of this possible
  • 45. Schema Language type Post { title: String! author: User! comments:[Comment]! } type Query { post(id: Int): Post posts: Post }
  • 46. Types ● Scalar types ○ Boolean ○ Int ○ Float ○ String ○ Custom types i.e. Date ● Enums ● Lists ● Interfaces ● Unions
  • 47. Summary: Benefits of GraphQL API playground Client-side validation Self-documenting Introspective Adapts to different requirements for different clients Client-specified Query from multiple data sources in a single network request. Single round trip
  • 48. A step-by-step walkthrough of building a GraphQL server Drawbacks to building Web APIs with REST Background REST GraphQL Code Next Steps An overview of GraphQL, with examples Further learning, future improvements, and conclusion The current state of Web APIs
  • 49. Building a GraphQL Server in Node.js
  • 50. Preamble A GraphQL service is created by providing (a) the schema and (b) resolver functions. ● We’ll use ○ Node.js + Express ○ express-graphql
  • 51. Preamble ● Bindings are available for all major languages ○ Javascript ○ Ruby ○ PHP ○ Python ○ Java ○ C/C++ ○ Go ○ Scala ○ .NET ○ Elixir ○ Haskell ○ SQL ○ Lua ○ Elm ○ Clojure
  • 53. A GraphQL Schema Definition const User = new GraphQLObjectType({ name: 'User', fields: () => ({ id: { type: GraphQLInt }, name: { type: GraphQLString } }) });
  • 54. Creates links between data sources and GraphQL fields posts(id){ return request(`https://api.blog.io/posts/${id}`); } posts(id){ return sql.raw('SELECT * FROM posts WHERE id = %s',id); } posts(id){ return DB.Posts.getById(id); } GraphQL Resolvers
  • 55. A step-by-step walkthrough of building a GraphQL server Drawbacks to building Web APIs with REST Background REST GraphQL Code Next Steps An overview of GraphQL, with examples Further learning, future improvements, and conclusion The current state of Web APIs
  • 56. ● Give GraphQL a try, especially if ○ Your product is an API ○ You have many clients with flexible requirements ● Features not covered in this talk ○ Aliases, ○ Fragments, ○ Variables, ○ Directives, etc. ● Best practices still emerging In Closing
  • 60. Appendix 0: Differences from REST ● A single endpoint `/graphql` ● Only HTTP verbs GET and POST are used ○ GET for queries ○ POST for mutations ● Support for other transport layers ○ MQTT for IOT domains
  • 61. Appendix 1: Versioning “We encourage GraphQL endpoints to take an add-only approach to schema evolution over time instead of changing existing fields.” GraphQL takes a strong opinion on avoiding versioning by providing the tools for the continuous evolution of a GraphQL schema.
  • 62. Appendix 2: Cons of GraphQL ● Initial investment may not make sense where ○ APIs are internal -> use RPC ○ API changes are rare (APIs are stable) ● Performance ○ Compared to RPC