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

GraphQL in an Age of REST

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

Yos Riady

October 29, 2016
Tweet

More Decks by Yos Riady

Other Decks in Programming

Transcript

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

    put some effort into making it pleasant.
  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. 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
  5. 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
  6. 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” }, ... ] }
  7. Retrieve a list of posts GET /posts GET /users/101 {

    “user”: { “id”: 101 “name”: “yosriady”, “joined_at”: “2015-10-11T16:53:28+00:00” } }
  8. 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
  9. 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
  10. 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
  11. • 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
  12. 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
  13. 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
  14. 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
  15. 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” } } }
  16. 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.
  17. Schema Language type Post { title: String! author: User! comments:[Comment]!

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

    ◦ String ◦ Custom types i.e. Date • Enums • Lists • Interfaces • Unions
  19. 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
  20. 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
  21. Preamble A GraphQL service is created by providing (a) the

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

    Javascript ◦ Ruby ◦ PHP ◦ Python ◦ Java ◦ C/C++ ◦ Go ◦ Scala ◦ .NET ◦ Elixir ◦ Haskell ◦ SQL ◦ Lua ◦ Elm ◦ Clojure
  23. A GraphQL Schema Definition const User = new GraphQLObjectType({ name:

    'User', fields: () => ({ id: { type: GraphQLInt }, name: { type: GraphQLString } }) });
  24. 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
  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. • 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
  27. 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
  28. 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.
  29. 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