RESTful APIs are dead, long live GraphQL

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

We can argue whether RESTful APIs ever existed, since very few ever implemented HATEOAS. Ruby On Rails claimed it offered RESTful APIs, but it never offered HATEOAS. After 10 years of failure, the world is looking for something new.

Interesting:

Imagine we have a simple application that fetches a list of stories, and some details about each one. Here’s how that might look in resource-oriented REST:

// Fetch the list of story IDs but not their details:
rest.get('/stories').then(stories =>
  // This resolves to a list of items with linked resources:
  // `[ { href: "http://.../story/1" }, ... ]`
  Promise.all(stories.map(story =>
    rest.get(story.href) // Follow the links
  ))
).then(stories => {
  // This resolves to a list of story items:
  // `[ { id: "...", text: "..." } ]`
  console.log(stories);
});

Note that this approach requires n+1 requests to the server: 1 to fetch the list, and n to fetch each item. With GraphQL we can fetch the same data in a single network request to the server (without creating a custom endpoint that we’d then have to maintain):

graphql.get(`query { stories { id, text } }`).then(
  stories => {
    // A list of story items:
    // `[ { id: "...", text: "..." } ]`
    console.log(stories);
  }
);

So far we’re just using GraphQL as a more efficient version of typical REST approaches. Note two important benefits in the GraphQL version:

All data is fetched in a single round trip.

The client and server are decoupled: the client specifies the data needed instead of relying on the server endpoint to return the correct data.

Post external references

  1. 1
    https://facebook.github.io/relay/docs/thinking-in-graphql.html
Source