GraphQL is a query language for APIs invented and open-sourced by Facebook. It can be used as an alternative to REST and boasts a lot of advantages. GraphQL was originally made to keep up with the increase in mobile device usage because it helps limit the amount of data sent. Normally we use different endpoints to get data from a server and display it to the client and we are forced to accept whatever data the endpoint gives us. GraphQL uses declarative data fetching meaning the client can define exactly what they want from the API. GraphQL has a lot of moving pieces so my goal with this series of posts is to break them down into manageable chunks.
GraphQL vs REST
REST has been around for a while and most websites on the internet follow RESTful patterns. If you want something different from the traditional paths you'll have to create your own custom endpoint and continue to create and change these depending on the needs of the client. REST APIs have multiple different endpoints, such as your typical Create, Read, Update, and Delete(CRUD), whereas GraphQL only has one endpoint.
Benefits of GraphQL
A major benefit of GraphQL goes back to declarative data fetching. Because you can create a request for exactly what you need, the client isn't stuck with any unnecessary data nor is it lacking information. This can save you requests, as sometimes we need to find the id of a specific model and then ask the API again for all the information about the object with that particular id. In a RESTful API, this can take 2 different requests but with GraphQL we only need to send one query.
Another nice feature is that declarative data fetching defines what the response will look like as well. When you send a query to the GraphQL API the response will be in the same exact shape. This was a breath of fresh air for me because it meant I didn't have to spend time toggling between my code and the response to make sure I was accessing the data correctly.
GraphQL can be used to combine multiple APIs into one GraphQL endpoint. Sometimes clients need to talk to multiple different APIs and with GraphQL you can stitch these APIs together. GraphQL can be wrapped around existing REST APIs and secured under one endpoint.
One of my favorite things about GraphQL is the playground that comes with it. The playground makes it easy to test out requests to the API and comes with a ton of information about your specific GraphQL project.
GraphQL has become extremely popular and is definitely picking up speed. I hope this article gives you a small insight into this cool technology. Be sure to look out for more articles in the series that will cover GraphQL Schema, Resolvers, and Apollo!