🚀 Rest vs GraphQL APIs
Published 2 years ago
|
As someone who has worked with GraphQL in many projects, I fell into the trap of assuming that everyone is familiar with it. I was quite surprised that the reality is far from what I expected. During JSDay Canarias, Roy talked about the GraphQL performance, and when the audience was asked if they are familiar with GraphQL, only ~20% raised their hands. That’s why in this issue, we will dive deeper into the differences between Rest and GraphQL APIs, their pros and cons, and best practices when it comes to building a scalable and performant API. This issue is sponsored by StepZenStepZen is a GraphQL server with a unique architecture that helps you build APIs fast and with less code. All you have to do is write a few lines of declarative code and let StepZen do the hard work related to building scalable and performant GraphQL APIs. Sign up for a free StepZen account: https://bit.ly/3IPdQl0 What’s a REST API?REST APIs have been the go-to architecture decision for the last years for building decoupled client-server applications. It serves as the communication protocol between the client (a web, mobile, desktop app, etc.) and the backend. The communication happens over HTTP, and all the resources live under a specific URL. For example, to get the list of posts from the dev.to REST API, we have to send a GET request to /articles URL. $ curl -X GET https://dev.to/api/articles JSON is the most common data format used with REST Apis. The above query will return a JSON array of articles. What’s a GraphQL API?GraphQL is a query language for APIs and is used to load data from the server to a client. The best thing about it is that you can specify exactly what data you need to query for a specific use case. For example, if you want to display only the title and the description of the posts on the home page, with GraphQL you can query the posts, and specify only these 2 fields that you need. The response will only include these fields, which will lead to faster and lighter responses. The communication also happens over HTTP, however, instead of many endpoints exposed by a REST API, a GraphQL API exposes only 1 endpoint that accepts only POST requests. The body of the POST request contains the details about the query: what entities and what fields should be returned. As we can see, on the left we wrote the query definition and asked for a list of articles with only the id, title, and description. On the right, we see the response, and indeed it only has these fields. CRUD operationsThe most common operations that an API is responsible for are the CRUD operations (Create, Read, Update, Delete). A REST API implements these operations using different HTTP methods (GET, POST, etc). With a GraphQL API, all the operations are sent as a POST request. This allows us to send the details about the operation inside the body of the request. In GraphQL, There are 3 operations:
To visualize better how CRUD operations are handled in a REST vs a GraphQL API, here is a short comparison. Problems solved by GraphQLNew technologies are introduced to solve some problems with existing solutions. Let’s explore some of the problems with Rest API that GraphQL solves. Over-fetchingIf you worked with REST APIs, you know very well that in 99% of cases, the API returns more data than we actually need. It feels like the API just spits out all the information it knows about the entities requested. This issue cannot be optimized, because if you would adjust the backend to return only the fields you need on a specific screen, then in other parts of the application, you will not receive the fields that you might need. So, you would either add again those fields or create a completely separate API endpoint for that screen. With the first solution, we arrive at the initial problem - over fetching, and in the second case we have code that repeats, and that’s not DRY 😀 But what’s the big deal with more data than we need? Well, first of all, it’s about the size of the requests. More data being sent over the internet leads to longer requests and higher internet usage. This might not be a problem in countries with fast internet and unlimited bandwidth, but it’s a huge problem everywhere else. As a comparison, I fetched 30 articles from dev.to with a REST API with all their fields, and over GraphQL with only the fields I needed. The amount of data sent over the network was:
That might seem like only 4kB saved, but that’s already 38% less data. If you take into consideration all the data that is requested while using an app, this can become hundred of MBs of wasted bandwidth. Under-fetchingOn the other hand, a more painful problem is under-fetching. It’s funny how the Rest API has both over-fetching and under-fetching issues at the same time, but let me explain using an example. Let’s say you are working on the Instagram feed, and have to display all the posts in the feed. If we look at what data we need for every post in the feed, we will see that it’s a mix of data from different tables. As we can see, the feed does not only display information about posts, but also the post user, who liked it, and also includes a couple of comments. If we are working with a REST API, we would have to send the next queries:
That’s a lot of queries. Let’s do some quick math, how many requests, back-and-forth, do we have to send to display a feed with 10 posts? 1 to get all the posts and 3 queries for every single post: 3 queries x 10 posts = 30 requests. In total, that’s 31 requests to display 10 posts on a feed. In a real scenario, that kind of query would most probably be optimized to include some of the needed data. But these optimizations are impossible to be done for every scenario, and in most cases, you would end up doing these additional requests to get the missing data. That’s why it’s called under-fetching. GraphQL solves this problem, by allowing us to specify what fields we have to query. This is also possible because of the defined relationships between our entities. For example, if the Post will be connected to a User (through userId), then we would be able to query the Post data and the Post Owners data in one single query. That allows us to get ALL the data that we need to display the Instagram Feed, in one single query Does GraphQL replace REST?That’s the ultimate question. Even though GraphQL is considered an alternative to REST, it doesn’t mean that they cannot co-exist together in the same stack. For example, you can add a thin GraphQL layer on top of your REST API. This solution comes with a lot of benefits, especially for brownfield projects, where you already have a REST API. What I found out from talking with multiple developers, is that Frontend devs LOVE 😍 GraphQL, because it makes their lives easier. On the other hand, Backend devs tend to dislike GraphQL, because it’s more technical and harder to implement. In that case, I always point them in the direction of StepZen. With StepZen, you can convert a REST API to GraphQL, by simply running one command: $ stepzen import curl That simple command, will introspect the backend and automatically generate the GraphQL schema with all the types, queries, mutations, and also all the resolvers that will get the data from the REST API. The next step is to deploy the GraphQL API by running stepzen start and you are good to go. From now on, you can continue developing your backend as a REST API but have the benefits of GraphQL on your frontend side. ConclusionTo wrap up this topic, let’s summarise the pros and cons of GraphQL and REST Apis. Graphql:
Rest:
🔴 Join me liveThis Friday we will build a StackOverflow mobile client by integrating with their API. It's going to be a tutorial packed with value, so set a reminder and don't miss it out 👇 🔁 In case you missed it
🔥 Press worthy🥳 Happy Birthday to React. It just turned 10 💰 22/100 top Finance apps are using React Native 🍕 24/100 top Food and Drink apps are using React Native 🎙️ RNR 266 - Chain React Roundup Did you learn something new today?If you found this email valuable, forward it to one friend or coworker that can benefit from it as well. That would be much appreciated 🙏
|