Asked

REST or GraphQL?

WIP is providing a GraphQL API which is kind of new to me since i am used to REST APIs. What are the Pros/Cons of GraphQL compared to REST? When i should consider to use GraphQL?

I think the main benefit of REST is that it's straightforward. Most developers are familiar with it. It's relatively easy to build an API, and for developers to build on top of.

The downside, compared to GraphQL, is that for certain use cases you might end up needing a ton of API calls what could be done with just one in GraphQL.

Example: let's say we want to fetch all products of a user and the associated pending todos. With REST we might make a call to get all products of a user, and then for each product make a separate call to get their pending todos. The more products, the more API calls we're making. Now imagine todos had comments and we wanted to fetch those too. That would again exponentially increase the number of API calls needed.

Now we could create the API such that fetching a product always returns its todos as well, but that's overkill in many other use cases. Okay you think, what if we make it configurable? Maybe we can add a GET parameter to the URL to tell the API whether to include the nested resources such as todos/comments/etc.

Well, that's basically what GraphQL is. With GraphQL the developer can just make one request and say "I want all of Franz' products, for each product I want its completed todos, and of those todos I want the comments too". And you can even specify which attributes you want. Maybe you only need the product name and description, and not all the other stuff. GraphQL lets you specify all that in one API call.

GraphQL's flexibility comes with the cost of complexity. It's more complex to build an API, and for simple use cases it's more complex to use the API. So there's no clear winner. It really depends on how you expect developers to use your API.

Disclaimer: I have limited experience building APIs, especially GraphQL APIs. Even though that's what I decided to use for WIP.

Thank you for the detailed answer, this helps to consider GraphQL for future projects.

Sign in to answer πŸ˜ƒ