DEV Community

Cover image for REST vs. GraphQL: A Detailed Comparison of API Architectures for Developers
Sophia Iroegbu for Studio1

Posted on • Edited on • Originally published at sophyia.me

REST vs. GraphQL: A Detailed Comparison of API Architectures for Developers

Introduction

APIs (Application Programming Interfaces) are the backbone of software development, creating a bridge or a link for applications to communicate and share data with a database or a server seamlessly. While there are so many API architectures, two styles stand out: REST (Representational State Transfer) and GraphQL. Both have merits and demerits, and developers often have difficulty deciding which architecture to explore in their projects.

This article guide will teach you about these API architectures, their principles, pros, drawbacks, and use cases. By the end of this article, you'll gain insights to make better-informed decisions about API architectures to use in your projects.

So, let's dive into REST and GraphQL, comparing their strengths and weaknesses to help you make the right choices as a developer!

Understanding REST APIs

REST is an acronym for REpresentational State Transfer. It is the most common API architectural style used on most servers and websites today. APIs built using the REST style are called RESTful APIs.

A RESTful API organizes resources into Uniform Resource Identifiers(URIs). Resources are entities or objects that the API represents or interacts with. The URI differentiates resources on a server: it could be a user resource, product resource, or image resource, depending on what you are building on your backend server.

The resources are ALWAYS grouped in nouns and not verbs - example/com/api/v1/user, not example/com/api/v1/getauser.

Why are Resources important? If a client wants to retrieve user details from the server, the client sends a request using HTTP codes to the server, targeting the user resources. The resource in question is like a table of users on the server.

Use Cases of REST

Web Services:

REST is widely used To build web services that provide functionalities. Popular examples are payment gateways, weather services, public API, and more.

Mobile App Services:

REST APIs are used to build mobile applications that access remote servers, making it easy to authenticate users, handle transactions, share content, and much more.

IoT servers:

RESTful APIs are used for IoT devices to communicate with remote servers, enabling the servers to share data and receive commands from a centralized network.

Third-Party Integrations:

RESTful APIs simplify integration between different systems or servers, making them fit for data exchange, cloud service, and enterprise applications.

Security:

RESTful API has a layered REST system, making it scalable and able to handle numerous requests without storing the client state.

API Documentation:

RESTful APIs allow clients to request a specific resource or representation of that resource, such as JSON or XML, making it adaptable to different client or end-user needs.

Pros of REST

  • REST is easy to understand and use. It follows a standard HTTP method and is widely used by many.

  • Caching in REST reduces server load and improves performance on the server and client side.

  • REST supports lots of tools and libraries.

  • REST endpoints have a clear, predictable structure for API interactions.

Cons of REST

  • RESTful APIs rely on HTTP, which may result in many connections to multiple sites over time.

  • RESTful APIs may not be suitable for complex activities due to several round trips between client and server and complex server-side logic.

  • RESTful API relies on HTTP security, which may not fit all security requirements; this would cause an additional security layer to be added.

  • RESTful API may be difficult to handle complex queries, searching, and filtering, unlike a query language like GraphQL.

Exploring GraphQL APIs

GraphQL is a Query architectural style language built by Meta. It provides the schema of the data of an API and lets the client ask for specific data. It's like a link between the client and the backend servers or services.

Here are some core concepts in GraphQL:

Schema:

GraphQL uses schemas to define the operations or queries that can be performed. The schema acts as an interface between the client and the server to fetch or modify data.

Types:

GraphQL, like REST, has various data types in an API. These include the developer defines String, Int, Boolean, or custom object types. Each field of a GraphQL type has its type. For example, in your GraphQL, the book_name field of the Book type is a String, and the publish_date field is an Int. Is that clear?

Queries:

GraphQL is a query language that lets clients specify the shape and content of the data they want from the server. Clients can use GraphQL to request specific fields and nested data in their queries, and the server will respond with data that matches the structure of the queries. This enables clients to fetch only the needed data, avoiding unnecessary or excessive requests to the server.

Mutations:

Mutations are a way of modifying data with GraphQL. Unlike queries, which are mainly for retrieving data from the server, mutations are for creating, updating, or deleting data on the server. Mutations ensure that the data written to the server is predictable.

Subscriptions:

Subscriptions in GraphQL enable real-time updates such as notifications. Clients can use subscriptions to listen for specific events or actions on the server. When those events or actions occur, the server sends notifications to the subscribed clients.

Resolvers:

A resolver is a function that connects a schema field to a data source, where it can fetch or modify data according to the query. Resolvers are the bridge between the schema and the data, and they handle the logic for data manipulation and retrieval.

Features of GraphQL

  • GraphQL lets clients request only the data they need and combines multiple queries into a single request, reducing the number of network calls and the load on the server.

  • GraphQL schema is easy to use and understand. It clearly documents what a GraphQL API can and can't do.

  • GraphQL supports real-time updates of data, which makes this API architecture style fit for real-time applications such as chat, live feeds, collaborative tools, etc.

  • GraphQL uses the HTTP methods(POST, GET, PUT, PATCH) but has one single endpoint, making it easy for the API surface. This means only one endpoint can be used to query a resource. It doesn't use URLs to specify resources; it uses schema.

  • GraphQL sends complex queries using the relationships defined on the schema. Clients can query the schema to understand the available types, fields, and API documentation. This helps in client development.

Pros of GraphQL

  • GraphQL lets clients request only data they need to reduce overload on the server side.

  • GraphQL lets clients define the structure of their response by customizing the request query.

  • GraphQL has a single endpoint that simplifies API management and reduces network requests.

  • GraphQL schemas support real-time features through subscriptions.

Drawbacks of GraphQL

  • In GraphQL, writing complex queries may be difficult and requires deep knowledge of data schema.

  • GraphQL APIs make it harder to cache data since it uses a single point of entry and POST HTTP method to query the server. This prevents the use of the GET HTTP caching method.

  • Poorly implemented GraphQL APIs can expose data and become vulnerable to deceitful queries.

  • For a basic web app or server that performs CRUD operations, GraphQL is a more costly option.

  • GraphQL has a steep learning curve for developers and clients due to its syntax and implementations.

  • GraphQL has fewer tools and libraries than REST.

  • GraphQL queries can cause over-fetching if they are not designed well.

Key Differences between REST and GraphQL

Data Retrieval and Manipulation:

A key difference between REST and GraphQL is how they handle data retrieval and manipulation. REST uses predefined endpoints that map to specific resources, while GraphQL allows clients to request specific data and get a response that matches the data structure of the request.

Flexibility and Efficiency:

REST handles multiple queries because each entity is accessed by a different endpoint which leads to over-fetching from the client side, while GraphQL has customizable queries that help tailor responses to client needs or requests. It prevents over-fetching or under-fetching.

Network Requests:

REST has multiple endpoints due to multiple results because each resource is accessed through a separate endpoint, which increases network round-trips, especially when gathering related data from various endpoints, while GraphQL has a single endpoint for all queries, reducing network round-trips. This helps clients query the endpoint targeting the data they need.

Cost & Maintenance:

REST is cost-efficient and easy to maintain since it is a common API architecture style best used for hobby projects or small projects, while GraphQL costs more to use and maintain. It offers fewer tools, so maintaining it would be a challenge.

Coding Examples

This is an example of GraphQL (using Node.JS and Apollo Server):

const { ApolloServer, gql } = require('apollo-server');

// Query Schema
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Endpoints
const resolvers = {
  Query: {
    hello: () => 'Hello, World!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

Enter fullscreen mode Exit fullscreen mode

This is an example of REST (using Django):

# REST VIEWS
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookList(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

class BookDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

# REST Endpoints
from django.urls import path
from . import views

urlpatterns = [
    path('books/', views.BookList.as_view(), name='book-list'),
    path('books/<int:pk>/', views.BookDetail.as_view(), name='book-detail'),
]

Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, choosing the right API architecture depends on your project's needs and goals.

REST and GraphQL have advantages, drawbacks, and use cases for different environments. REST is for simple logic and a more structured architecture, while GraphQL is for a more tailored response and flexible request.

Now that you've understood the differences, you can make decisions to fit your project's needs.

Top comments (6)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

GraphQL isn't good at caching??? Did you ever use it or did an AI generate this? GraphQL with any decent client is exceptional at caching. A con - using GraphQL without a client may lead to poor performance, it's overhead choosing one.

How about a pro being it's self documenting and the developer can use tools to build their queries, rather than hoping a API author has built a REST API right - many haven't.

Collapse
 
sophyia profile image
Sophia Iroegbu

Thanks for this. I haven't used GraphQL in-depth, and I wrote this article based on my research on GraphQL and my knowledge of REST.

Collapse
 
610470416 profile image
NotFound404

Summary

1. VIG API

For simple business logic data, easy to be designed and be understood, universal for companies, human understandable

2. REST API

For date as representational resources' states, hard to be designed and be understood, fit for big companies, hard for human to comprehend

3. GraphQL

For complex/inegrated data fetching, very hard to be designed and be understood, fit for giant companies, more suitable for machine data exchange

Collapse
 
sophyia profile image
Sophia Iroegbu

This is the first time I am hearing of VIG. Thanks for sharing this.

Collapse
 
ricardogesteves profile image
Ricardo Esteves

nice article @sophyia ! thank you for sharing it.

Collapse
 
sophyia profile image
Sophia Iroegbu

Thanks.