BackendNov 25, 202511 min read

GraphQL vs REST: Making the Right API Choice

A practical comparison for modern web applications

GraphQLRESTApolloNode.js
GraphQL vs REST: Making the Right API Choice

Key Takeaways

  • When GraphQL shines vs REST
  • Performance considerations
  • Implementation patterns
  • Caching strategies for both
  • Migration strategies

The GraphQL vs REST debate continues to evolve. Both have their place in modern architecture. Rather than picking sides, let's understand the tradeoffs and learn when each approach makes sense. The best API is the one that fits your specific use case.

Network connections representing APIs
APIs are the backbone of modern web applications

REST: The Tried and True

REST APIs use HTTP methods semantically and are resource-oriented. They're simple to understand, cache naturally with HTTP, and have excellent tooling. REST is ideal for CRUD operations, public APIs, and teams familiar with traditional web development patterns.

javascript
// Express REST API with proper patterns
import express from 'express';
import { rateLimit } from 'express-rate-limit';

const app = express();

// Resource-based routing
const usersRouter = express.Router();

// GET /api/users - List users with pagination
usersRouter.get('/', async (req, res) => {
  const { page = 1, limit = 20, sort = 'createdAt' } = req.query;
  
  const users = await User.find()
    .sort(sort)
    .skip((page - 1) * limit)
    .limit(parseInt(limit))
    .select('-password');
    
  const total = await User.countDocuments();
  
  res.json({
    data: users,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total,
      pages: Math.ceil(total / limit)
    }
  });
});

// GET /api/users/:id - Single user with related data
usersRouter.get('/:id', async (req, res) => {
  const { include } = req.query;
  
  let query = User.findById(req.params.id).select('-password');
  
  if (include?.includes('posts')) {
    query = query.populate('posts');
  }
  if (include?.includes('followers')) {
    query = query.populate('followers', 'name avatar');
  }
  
  const user = await query;
  if (!user) return res.status(404).json({ error: 'User not found' });
  
  res.json({ data: user });
});

GraphQL: Flexibility and Efficiency

GraphQL lets clients request exactly the data they need. It eliminates over-fetching and under-fetching, provides a strongly-typed schema, and enables powerful developer tools. GraphQL excels in complex UIs, mobile apps with bandwidth constraints, and rapidly evolving APIs.

typescript
// GraphQL schema and resolvers
import { gql } from 'apollo-server-express';

// Type definitions
const typeDefs = gql`
  type User {
    id: ID!
    name: String!
    email: String!
    avatar: String
    posts(limit: Int = 10): [Post!]!
    followers: [User!]!
    followersCount: Int!
  }

  type Post {
    id: ID!
    title: String!
    content: String!
    author: User!
    createdAt: String!
    likes: Int!
  }

  type Query {
    user(id: ID!): User
    users(page: Int = 1, limit: Int = 20): UserConnection!
    post(id: ID!): Post
  }

  type UserConnection {
    nodes: [User!]!
    pageInfo: PageInfo!
  }
`;

// Resolvers with DataLoader for N+1 prevention
const resolvers = {
  Query: {
    user: (_, { id }) => User.findById(id),
    users: async (_, { page, limit }) => {
      const skip = (page - 1) * limit;
      const [nodes, total] = await Promise.all([
        User.find().skip(skip).limit(limit),
        User.countDocuments()
      ]);
      return {
        nodes,
        pageInfo: { page, limit, total, hasNextPage: skip + nodes.length < total }
      };
    }
  },
  User: {
    posts: (user, { limit }, { loaders }) => 
      loaders.userPosts.load({ userId: user.id, limit }),
    followersCount: (user) => user.followers?.length || 0
  }
};
40%Less data transfer (GraphQL)
REST95% of public APIs
GraphQLGithub, Shopify, Stripe
BFFBest pattern: combine both
HR

Written by Hammas Rashid

Full-Stack Developer passionate about building scalable web applications and sharing knowledge with the developer community.

Chat on WhatsApp