GraphQL is a “Better Way”

 

After reading articles purporting the amazingness of GraphQL over RESTful, I decided to explore it with a “getting started” tutorial. It was a breeze to set up on the server side.

The beauty of GraphQL is that it allows the client to specify what data it requires whereas a RESTful API would deliver the entire contents of a table unless a custom endpoint were created and maintained.

It also allows for collation from multiple resources and delivers the results via a tidy JSON object.

My first reaction to hearing about it was that allowing for such specificity would involve learning a new query language. I was wrong. The format is elegant and intuitive. A request looks almost just like the JSON response without the values. Here’s an example of a request:

[pastacode lang=”javascript” manual=”%7B%0A%20%20user1%3A%20user(login%3A%20%22tj%22)%20%7B%0A%20%20%20%20name%0A%20%20%20%20email%0A%20%20%20%20about%0A%20%20%20%20following%0A%20%20%20%20followers%0A%20%20%7D%2C%0A%20%20user2%3A%20user(login%3A%20%22ekendra-nz%22)%20%7B%0A%20%20%20%20name%0A%20%20%20%20email%0A%20%20%20%20about%0A%20%20%20%20following%0A%20%20%20%20followers%0A%20%20%7D%0A%7D” message=”GraphQL Request” highlight=”” provider=”manual”/]

And here is the response. See how the query and response work like a Q and A? How smooth is that?

[pastacode lang=”javascript” manual=”%7B%0A%20%20%22data%22%3A%20%7B%0A%20%20%20%20%22user1%22%3A%20%7B%0A%20%20%20%20%20%20%22name%22%3A%20%22TJ%20Holowaychuk%22%2C%0A%20%20%20%20%20%20%22email%22%3A%20null%2C%0A%20%20%20%20%20%20%22about%22%3A%20%22Founder%20of%20Apex%5Cr%5Cnhttps%3A%2F%2Fapex.sh%5Cr%5Cn%40tjholowaychuk%20on%20Twitter%20%26%20Medium.%22%2C%0A%20%20%20%20%20%20%22following%22%3A%2048%2C%0A%20%20%20%20%20%20%22followers%22%3A%2030215%0A%20%20%20%20%7D%2C%0A%20%20%20%20%22user2%22%3A%20%7B%0A%20%20%20%20%20%20%22name%22%3A%20%22ekendra-nz%22%2C%0A%20%20%20%20%20%20%22email%22%3A%20null%2C%0A%20%20%20%20%20%20%22about%22%3A%20%22PHP%2FJS%20Webdev%22%2C%0A%20%20%20%20%20%20%22following%22%3A%200%2C%0A%20%20%20%20%20%20%22followers%22%3A%200%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D” message=”GraphQL Response” highlight=”” provider=”manual”/]

 

Leave a Reply

Your email address will not be published. Required fields are marked *