Upgrade to Pro — share decks privately, control downloads, hide ads and more …

GraphQL in an Age of REST

1b0ab2500efc1b91424fb49045312929?s=47 Yos Riady
October 29, 2016

GraphQL in an Age of REST

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?

https://goo.gl/prnEnz

1b0ab2500efc1b91424fb49045312929?s=128

Yos Riady

October 29, 2016
Tweet

Transcript

  1. GraphQL in an Age of REST Yos Riady yos.io goo.gl/prnEnz

  2. 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
  3. An API is a user interface for developers - so

    put some effort into making it pleasant.
  4. Background

  5. Web APIs are eating the world

  6. None
  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. 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. None
  10. Posts

  11. Posts Users Comments

  12. A HackerNews-like Data Model author_id post_id body Comment author_id title

    url published_at votes Post name joined_at User POST /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
  13. None
  14. None
  15. Let’s try using our API

  16. None
  17. 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” }, ... ] }
  18. Retrieve a list of posts GET /posts GET /users/101 {

    “user”: { “id”: 101 “name”: “yosriady”, “joined_at”: “2015-10-11T16:53:28+00:00” } }
  19. Retrieve a list of posts GET /posts GET /users/101 GET

    /users/102 GET /users/103 ...
  20. Problem: Multiple roundtrips

  21. None
  22. None
  23. 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
  24. 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
  25. Solution: Custom Endpoints Your API DB 1 DB 2 v1

    v2 v1 v2 v3
  26. 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.
  27. An API is only as good as its documentation.

  28. 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
  29. • 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
  30. 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
  31. 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
  32. GraphQL

  33. 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
  34. It’s Graphs All the Way Down

  35. It’s Graphs All the Way Down

  36. 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” } } }
  37. 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.
  38. /graphql

  39. None
  40. goo.gl/nV3WJE goo.gl/nV3WJE

  41. None
  42. Great API documentation drives adoption.

  43. The (2) Type System makes all of this possible

  44. Schema Language type Post { title: String! author: User! comments:[Comment]!

    } type Query { post(id: Int): Post posts: Post }
  45. Types • Scalar types ◦ Boolean ◦ Int ◦ Float

    ◦ String ◦ Custom types i.e. Date • Enums • Lists • Interfaces • Unions
  46. 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
  47. 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
  48. Building a GraphQL Server in Node.js

  49. Preamble A GraphQL service is created by providing (a) the

    schema and (b) resolver functions. • We’ll use ◦ Node.js + Express ◦ express-graphql
  50. Preamble • Bindings are available for all major languages ◦

    Javascript ◦ Ruby ◦ PHP ◦ Python ◦ Java ◦ C/C++ ◦ Go ◦ Scala ◦ .NET ◦ Elixir ◦ Haskell ◦ SQL ◦ Lua ◦ Elm ◦ Clojure
  51. yos-graphql.surge.sh

  52. A GraphQL Schema Definition const User = new GraphQLObjectType({ name:

    'User', fields: () => ({ id: { type: GraphQLInt }, name: { type: GraphQLString } }) });
  53. 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
  54. 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
  55. • 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
  56. meetup.com/API-Craft-Singapore

  57. Thanks Yos Riady yos.io

  58. Questions? Yos Riady yos.io

  59. 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
  60. 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.
  61. 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