Until GraphQL came out, RESTful API was the most popular choice for client-server communication. REST has been defined about 20 years ago, in context of problems from that time. As applications became more complex and new devices came around, new problems has emerged and REST wasn’t able to solve them in a performant way. One common scenario is: we want to display on homepage a list of articles and for each article we want to have it’s author name and avatar or email. With REST api we need to make few requests to achieve this: one to get the list of articles with author IDs and then other few requests to get information about each author. With GraphQL this can be done in single query:
In order to understand better how GraphQL works, I made a simple app. GraphQL Apollo Server is acting like an interface between MongoDB plus external API and the client. As client-side consumer I’ve chosen Angular, but it can be any other solution which Apollo Client is supporting. Here is how GraphQL works:
On server I have defined schema:
On client we consume GraphQL via queries and mutations:
All code is available here.