GraphQL vs. REST: which is the best for API development?

API, short for Application Programming Interface, is a software intermediary that allows two applications to communicate with each other. That could be a server, a client, or an application talking to a server. The following timeline illustrates how it has evolved over the years and lays a great foundation for how an API can be built. REST is still a popular tool for building APIs. However, in 2012, Facebook wanted something other than REST, and that’s when GraphQL (Graph Query Language) was introduced.

Source: https://blog.api.rakuten.net/graphql-vs-rest/

What is REST?

REST stands for Representational State Transfer, which means that each resource has its own endpoint. It was initially a dissertation published by Roy Fielding in 2000 and popularized by companies like Twitter in 2006. REST is an architectural concept for network-based software. It has no official set of tools, no specifications, doesn’t particularly care if you use HTTP, AMQP, etc., and is designed to decouple APIs from clients.

Top REST API Challenges

The REST API sometimes requires multiple round trips. This applies when we need to display some data that needs to be consumed from different endpoints, and consuming data from a single endpoint is not enough. The following table illustrates three endpoints:

GET /usersList all usersGET /users/:idGet the unique user with id: idGET /users/:id/projectsGet all projects for a user

What if in a client application we need to find projects related to that specific user and some tasks that may also be related to the project itself? Should the back-end team build something extra? There are the following possible ways to do it:

  1. To include a query and then return the tasks to each project: GET /users/:id/projects?include=tasks
  2. To have a separate endpoint, resource projects, and ask a client application for query filtering based on user id: GET /projects?userid=:id&include=tasks
  3. To include all possible data associated with the user in an endpoint: GET /tasks?userid=:id

Oversearch and undersearch. When too much data needs to be returned, the client application doesn’t need all of it. Customers will not be happy if they are asked to download additional information that they do not really need. On the other hand, by reducing the level of information on a server, you may experience the issue of insufficient fetching and will require another endpoint and additional resource on a server to fetch that data. The solution is: GET /users?fields=firstname,lastname.

Difficulty creating versions and discarding fields that are not needed for new versions. REST APIs are difficult to maintain when they grow over time and have different requirements to support different application versions and multiple clients. So usually v1 is left as is and v2 is generated with a newer data structure. With GraphQL, it could be done without version control. GraphQL only returns the explicitly requested data, so new capabilities can be added through new types and new fields on those types without causing a breaking change. This has led to a common practice of continually avoiding relevant changes and serving a versionless API.

See also  Introducing the Referral Program

Unpredictable data. With REST, you don’t know what data a server will return: which fields, how many of them, etc. With GraphQL, the client requests that specific fields be returned. It doesn’t matter if it’s a query or a mutation, you’re in control of what gets returned.

What is GraphQL?

GraphQL is a newer concept, publicly released by Facebook in 2015. As a new way to request data from a server, it is a query language, specification, and collection of tools designed to operate on a single endpoint over HTTP, optimized for performance and flexibility.

This table compares GraphQL and REST as two approaches to building an API. Generally speaking, it cannot be considered an apple-to-apple comparison, but rather an orange-to-apple parallel, since REST is a conventional standard for API planning and GraphQL is a query language that helps solve problems. with the APIs. However, both are still fruits. 🙂

The main difference here is that GraphQL is a client-facing language. It has an architecture where the front-end application decides what data to get and how much the server should return. Meanwhile, when using REST, everything is designed on the server, so the server drives the architecture.

GraphQLRESTA query language that offers efficiency and flexibility in solving common problems when integrating APIs An architectural style largely seen as a conventional standard for API design Implemented over HTTP using a single endpoint that provided all the capabilities of the exposed service Implemented over a set of URLs where each URL exposes a single resourceUses a client-driven architectureUser-server-based architectureLacks automatic caching mechanismUses automatic cachingNO API versionsSupports multiple API versionsJSON rendering onlySupports multiple data formatsOnly one tool predominantly used for documentation: GraphiQL Wide range of options for automated documentation, such as OpenAPI and API Blueprint Complicates handling of HTTP status codes to identify errors Uses HTTP status codes to identify and mistakes easily

Reasons to use GraphQL

There are three main reasons why we might want to consider using GraphQL instead of REST:

  • Network performance. Whether we want to increase network performance by sending less data or sending only the information we need to clients.
  • The design choice “Include vs. Endpoint”. There is a difficult choice between include the request either create an additional endpoint. With GraphQL, that problem is solved thanks to the functions of scheme Y resolution. So the client is in control of what data should be returned.
  • Management of different types of clients. Imagine that you have an API and all the clients (iOS app, Android app, web app, etc.) are completely different from each other: they need a completely different structure or amount of data that is returned by the server. With the REST approach, you may need to build a separate API. In contrast, with GraphQL, you won’t need to because you can have everything returned from a single endpoint.
See also  PHP 8.0: An introduction to the new version of PHP

How to start?

This is a breakdown of how a query is created. Three main parts are considered: 1) type of operation, 2) end point of the operation, 3) requested fields.

terms to learn

Regardless of the implementation you choose, since there are many languages, GraphQL is not only available in JavaScript or Node: you can use PHP, Python, JAVA, Go and others. Each language has its own implementation of GraphQL, so you don’t need to create everything from scratch. There are tools and packages you can use, and those terms are pretty much the same across all of them, so it might be worth learning them if you want to build an API using GraphQL:

Types. The data model in GraphQL is represented in types, which are strongly typed. There should be a 1-to-1 mapping between your models and the GraphQL codes. You can think of this as a database table where the user table has fields like id, firstname, lastname, email, projects. So things to remember include that exclamation mark that says an id can’t be nullable, or in other words, something has to be there since it’s a required field.

Consultations. Queries define which queries you can run against your GraphQL API. By convention, there should be a RootQuery, which contains all existing queries. In the example, the comment here shows what it looks like in a REST API. In parentheses in square brackets, we see an argument that has to be a unique identifier, and after the colon is the user type. Shows what should be returned when we perform this query, so it returns the user. The project query will return the project, the task query will change the list of tasks, etc.

See also  How to Fix HTTP 302 Found Error (5 Methods)

Mutations. If the queries are GET requests, the mutations can be seen as POST | PATCH | PUT | DELETE requests that modify data. The example includes mutations of “createUser”, “updateUser”, “removeUser”.

Input. The user input type is a user type without the id and projects fields. Look at the keyword input instead of type. You can think of this as a form on a page where you need to enter some data and the type of information that needs to be entered to create that user profile.

resolvers. The resolve function provides a specific set of instructions for converting GraphQL operations to data. It’s basically a controller function, the logic of what should be returned (query resolvers) when that query occurs and a user requests data, and mutation resolvers are used when a user seeks to update or delete data.

Scheme. With types, queries, and mutations, we define a GraphQL schema, which is what the GraphQL endpoint exposes to the world.

Resources to review

Here are two main resources to dive deeper into GraphQL:

  • . Dedicated to learning all the basics and the actual specification of GraphQL.
  • Dedicated to learning about implementations. For example, if you’re looking for information about the Apollo server, this will give you an idea of ​​what front-end frameworks can be used to consume the data from that API. You don’t need to use any of the tools or libraries for the front-end to consume the API; you can make a regular XmlHttp request, but you must make a POST request to that endpoint and provide the query in the body, which is the GraphQL.

The GraphQL server API can be used as a gateway to other micro-services, talking directly to the database or other REST APIs. So you could have multiple REST APIs, get that data, and turn it into a single source of information.

This article is inspired by front-end developer Gediminas Survila’s presentation on “GraphQL vs. REST: which is the best for API development?»

Carlos is a professional in digital marketing, eCommerce and website builders. He loves helping businesses grow online through his tips. In his free time, he is surely singing or practicing martial arts.

Loading Facebook Comments ...
Loading Disqus Comments ...