Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

GraphQL in an Age of REST

650 views

Published on

GraphQL is an application layer query language from Facebook. With GraphQL, you can define your backend as a well-defined graph-based schema. Then client applications can query your dataset as they are needed. GraphQL’s power comes from a simple idea — instead of defining the structure of responses on the server, the flexibility is given to the client. Will GraphQL do to REST what REST did to SOAP?

Published in: Technology
  • Be the first to comment

GraphQL in an Age of REST

  1. 1. GraphQL in an Age of REST Yos Riady yos.io goo.gl/prnEnz
  2. 2. Disclaimer
  3. 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. 4. An API is a user interface for developers - so put some effort into making it pleasant.
  5. 5. Background
  6. 6. Web APIs are eating the world
  7. 7. 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
  8. 8. 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
  9. 9. Posts
  10. 10. Posts Users Comments
  11. 11. 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
  12. 12. Let’s try using our API
  13. 13. 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” }, ... ] }
  14. 14. Retrieve a list of posts GET /posts GET /users/101 { “user”: { “id”: 101 “name”: “yosriady”, “joined_at”: “2015-10-11T16:53:28+00:00” } }
  15. 15. Retrieve a list of posts GET /posts GET /users/101 GET /users/102 GET /users/103 ...
  16. 16. Problem: Multiple roundtrips
  17. 17. 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
  18. 18. 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
  19. 19. Solution: Custom Endpoints Your API DB 1 DB 2 v1 v2 v1 v2 v3
  20. 20. 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.
  21. 21. An API is only as good as its documentation.
  22. 22. 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
  23. 23. ● 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
  24. 24. 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
  25. 25. 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
  26. 26. GraphQL
  27. 27. 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
  28. 28. It’s Graphs All the Way Down
  29. 29. It’s Graphs All the Way Down
  30. 30. 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” } } }
  31. 31. 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.
  32. 32. /graphql
  33. 33. goo.gl/nV3WJE goo.gl/nV3WJE
  34. 34. Great API documentation drives adoption.
  35. 35. The (2) Type System makes all of this possible
  36. 36. Schema Language type Post { title: String! author: User! comments:[Comment]! } type Query { post(id: Int): Post posts: Post }
  37. 37. Types ● Scalar types ○ Boolean ○ Int ○ Float ○ String ○ Custom types i.e. Date ● Enums ● Lists ● Interfaces ● Unions
  38. 38. 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
  39. 39. 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
  40. 40. Building a GraphQL Server in Node.js
  41. 41. Preamble A GraphQL service is created by providing (a) the schema and (b) resolver functions. ● We’ll use ○ Node.js + Express ○ express-graphql
  42. 42. Preamble ● Bindings are available for all major languages ○ Javascript ○ Ruby ○ PHP ○ Python ○ Java ○ C/C++ ○ Go ○ Scala ○ .NET ○ Elixir ○ Haskell ○ SQL ○ Lua ○ Elm ○ Clojure
  43. 43. yos-graphql.surge.sh
  44. 44. A GraphQL Schema Definition const User = new GraphQLObjectType({ name: 'User', fields: () => ({ id: { type: GraphQLInt }, name: { type: GraphQLString } }) });
  45. 45. 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
  46. 46. 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
  47. 47. ● 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
  48. 48. meetup.com/API-Craft-Singapore
  49. 49. Thanks Yos Riady yos.io
  50. 50. Questions? Yos Riady yos.io
  51. 51. 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
  52. 52. 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.
  53. 53. 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

×