skip to content
Home Image

RESTful vs GraphQL

/ 13 min read

Table of Contents

REST

REST (Representational State Transfer) is an architectural style for designing networked applications that has become the standard for web services.

RESTful APIs provide a flexible, lightweight way to integrate applications and enable communication between different systems.

Core Concepts:

Resources: Everything is a resource (user, product, order)

Representations: Resources can have multiple representations (JSON, XML, etc.)

Stateless: Each request contains all necessary information

Uniform Interface: Consistent way to access and manipulate resources

RESTful APIs use HTTP requests to perform CRUD operations (Create, Read, Update, Delete) on resources, which are represented as URLs.

REST is stateless, meaning each request from a client to a server must contain all the information needed to understand and process the request.

Core REST Principles

Understanding these principles is crucial for designing effective RESTful APIs.

They ensure your API is scalable, maintainable, and easy to use.

Key Principles in Practice:

a. Resource-Based: Focus on resources rather than actions
b. Stateless: Each request is independent and self-contained
c. Cacheable: Responses define their cacheability
d. Uniform Interface: Consistent resource identification and manipulation
e. Layered System: Client doesn't need to know about the underlying architecture

The core principles of REST architecture include:

a. Client-Server Architecture: Separation of concerns between the client and the server
b. Statelessness: No client context is stored on the server between requests
c. Cacheability: Responses must define themselves as cacheable or non-cacheable
d. Layered System: A client cannot tell whether it is connected directly to the end server
e. Uniform Interface: Resources are identified in requests, resources
are manipulated through representations, self-descriptive messages,
and HATEOAS (Hypertext As The Engine Of Application State)

HTTP Methods and Their Usage

RESTful APIs use standard HTTP methods to perform operations on resources.

Each method has specific semantics and should be used appropriately.

MethodActionExample
GETRetrieve resource(s)GET /api/users
POSTCreate a new resourcePOST /api/users
PUTUpdate a resource completelyPUT /api/users/123
PATCHUpdate a resource partiallyPATCH /api/users/123
DELETEDelete a resourceDELETE /api/users/123

Using Different HTTP Methods

const express = require('express');
const app = express();
// Middleware for parsing JSON
app.use(express.json());
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
// GET - Retrieve all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET - Retrieve a specific user
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: 'User not found' });
res.json(user);
});
// POST - Create a new user
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
email: req.body.email
};
users.push(newUser);
res.status(201).json(newUser);
});
// PUT - Update a user completely
app.put('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: 'User not found' });
user.name = req.body.name;
user.email = req.body.email;
res.json(user);
});
// DELETE - Remove a user
app.delete('/api/users/:id', (req, res) => {
const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
if (userIndex === -1) return res.status(404).json({ message: 'User not found' });
const deletedUser = users.splice(userIndex, 1);
res.json(deletedUser[0]);
});
app.listen(8080, () => {
console.log('REST API server running on port 8080');
});

RESTful API Structure and Design

A well-designed API follows consistent patterns that make it intuitive and easy to use. Good API design is crucial for developer experience and long-term maintainability.

Design Considerations:

a. Resource Naming: Use nouns, not verbs (e.g., /users not /getUsers)
b. Pluralization: Use plural for collections (/users/123 not /user/123)
c. Hierarchy: Nest resources to show relationships (/users/123/orders)
d. Filtering/Sorting: Use query parameters for optional operations
d. Versioning Strategy: Plan for API versioning from the start (e.g., /v1/users vs /v2/users).

A well-structured API follows these conventions:

a. Use nouns for resources: /users, /products, /orders (not /getUsers)
b. Use plurals for collections: /users instead of /user
c. Nest resources for relationships: /users/123/orders
d. Use query parameters for filtering: /products?category=electronics&min_price=100
e. Keep URLs consistent: Choose a convention (kebab-case, camelCase) and stick to it

Well-structured API Routes

// Good API structure
app.get('/api/products', getProducts);
app.get('/api/products/:id', getProductById);
app.get('/api/products/:id/reviews', getProductReviews);
app.get('/api/users/:userId/orders', getUserOrders);
app.post('/api/orders', createOrder);
// Filtering and pagination
app.get('/api/products?category=electronics&sort=price&limit=10&page=2');

Building REST APIs with Node.js and Express

Node.js with Express.js provides an excellent foundation for building RESTful APIs.

The following sections outline best practices and patterns for implementation.

Key Components:

a. Express Router: For organizing routes
b. Middleware: For cross-cutting concerns
c. Controllers: For handling request logic
d. Models: For data access and business logic
e. Services: For complex business logic

Express.js is the most popular framework for building REST APIs in Node.js.

Project Structure

- app.js # Main application file
- routes/ # Route definitions
- users.js
- products.js
- controllers/ # Request handlers
- userController.js
- productController.js
- models/ # Data models
- User.js
- Product.js
- middleware/ # Custom middleware
- auth.js
- validation.js
- config/ # Configuration files
- db.js
- env.js
- utils/ # Utility functions
- errorHandler.js
  1. Setting Up Express Router
routes/users.js
const express = require('express');
const router = express.Router();
const { getUsers, getUserById, createUser, updateUser, deleteUser } = require('../controllers/userController');
router.get('/', getUsers);
router.get('/:id', getUserById);
router.post('/', createUser);
router.put('/:id', updateUser);
router.delete('/:id', deleteUser);
module.exports = router;
// app.js
const express = require('express');
const app = express();
const userRoute// routes/users.js
const express = require('express');
const router = express.Router();
const { getUsers, getUserById, createUser, updateUser, deleteUser } = require('../controllers/userController');
router.get('/', getUsers);
router.get('/:id', getUserById);
router.post('/', createUser);
router.put('/:id', updateUser);
router.delete('/:id', deleteUser);
module.exports = router;
// app.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/users');
app.use(express.json());
app.use('/api/users', userRoutes);
app.listen(8080, () => {
console.log('Server is running on port 8080');
});s = require('./routes/users');
app.use(express.json());
app.use('/api/users', userRoutes);
app.listen(8080, () => {
console.log('Server is running on port 8080');
});
  1. Controllers and Models

Separating concerns between routes, controllers, and models improves code organization and maintainability:

controllers/userController.js
const User = require('../models/User');
const getUsers = async (req, res) => {
try {
const users = await User.findAll();
res.status(200).json(users);
} catch (error) {
res.status(500).json({ message: 'Error retrieving users', error: error.message });
}
};
const getUserById = async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json(user);
} catch (error) {
res.status(500).json({ message: 'Error retrieving user', error: error.message });
}
};
const createUser = async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (error) {
res.status(400).json({ message: 'Error creating user', error: error.message });
}
};
module.exports = { getUsers, getUserById, createUser };
  1. Request Validation

Always validate incoming requests to ensure data integrity and security.

Libraries like Joi or express-validator can help:

const express = require('express');
const Joi = require('joi');
const app = express();
app.use(express.json());
// Validation schema
const userSchema = Joi.object({
name: Joi.string().min(3).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(18).max(120)
});
app.post('/api/users', (req, res) => {
// Validate request body
const { error } = userSchema.validate(req.body);
if (error) {
return res.status(400).json({ message: error.details[0].message });
}
// Process valid request
// ...
res.status(201).json({ message: 'User created successfully' });
});
app.listen(8080);
  1. Error Handling

Implement consistent error handling to provide clear feedback to API consumers:

utils/errorHandler.js
class AppError extends Error {
constructor(statusCode, message) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = { AppError };
// middleware/errorMiddleware.js
const errorHandler = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
// Different error responses for development and production
if (process.env.NODE_ENV === 'development') {
res.status(err.statusCode).json({
status: err.status,
message: err.message,
stack: err.stack,
error: err
});
} else {
// Production: don't leak error details
if (err.isOperational) {
res.status(err.statusCode).json({
status: err.status,
message: err.message
});
} else {
// Programming or unknown errors
console.error('ERROR 💥', err);
res.status(500).json({
status: 'error',
message: 'Something went wrong'
});
}
}
};
module.exports = { errorHandler };
// Usage in app.js
const { errorHandler } = require('./middleware/errorMiddleware');
const { AppError } = require('./utils/errorHandler');
// This route throws a custom error
app.get('/api/error-demo', (req, res, next) => {
next(new AppError(404, 'Resource not found'));
});
// Error handling middleware (must be last)
app.use(errorHandler);
  1. API Versioning

Versioning helps you evolve your API without breaking existing clients.

Common approaches include:

a. URI Path Versioning: /api/v1/users
b. Query Parameter: /api/users?version=1
c. Custom Header: X-API-Version: 1
d. Accept Header: Accept: application/vnd.myapi.v1+json
const express = require('express');
const app = express();
// Version 1 routes
const v1UserRoutes = require('./routes/v1/users');
app.use('/api/v1/users', v1UserRoutes);
// Version 2 routes with new features
const v2UserRoutes = require('./routes/v2/users');
app.use('/api/v2/users', v2UserRoutes);
app.listen(8080);
  1. API Documentation

Good documentation is essential for API adoption.

Tools like Swagger/OpenAPI can automatically generate documentation from code:

Swagger Documentation

const express = require('express');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const app = express();
// Swagger configuration
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'User API',
version: '1.0.0',
description: 'A simple Express User API'
},
servers: [
{
url: 'http://localhost:8080',
description: 'Development server'
}
]
},
apis: ['./routes/*.js'] // Path to the API routes folders
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
/**
* @swagger
* /api/users:
* get:
* summary: Returns a list of users
* description: Retrieve a list of all users
* responses:
* 200:
* description: A list of users
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* id:
* type: integer
* name:
* type: string
* email:
* type: string
*/
app.get('/api/users', (req, res) => {
// Handler implementation
});
app.listen(8080);
  1. Testing APIs

Testing is critical for API reliability.

Use libraries like Jest, Mocha, or Supertest:

tests/users.test.js
const request = require('supertest');
const app = require('../app');
describe('User API', () => {
describe('GET /api/users', () => {
it('should return all users', async () => {
const res = await request(app).get('/api/users');
expect(res.statusCode).toBe(200);
expect(Array.isArray(res.body)).toBeTruthy();
});
});
describe('POST /api/users', () => {
it('should create a new user', async () => {
const userData = {
name: 'Test User',
email: 'test@example.com'
};
const res = await request(app)
.post('/api/users')
.send(userData);
expect(res.statusCode).toBe(201);
expect(res.body).toHaveProperty('id');
expect(res.body.name).toBe(userData.name);
});
it('should validate request data', async () => {
const invalidData = {
email: 'not-an-email'
};
const res = await request(app)
.post('/api/users')
.send(invalidData);
expect(res.statusCode).toBe(400);
});
});
});

GraphQL

GraphQL is a query language for APIs and a runtime for executing those queries against your data. It was developed by Facebook in 2012 and publicly released in 2015.

Key Features

a. Client-specified queries: Request exactly what you need, nothing more
b. Single endpoint: Access all resources through one endpoint
c. Strongly typed: Clear schema defines available data and operations
d. Hierarchical: Queries match the shape of your data
e. Self-documenting: Schema serves as documentation

Note: Unlike REST, GraphQL lets clients specify exactly what data they need, reducing over-fetching and under-fetching of data.

Getting Started with GraphQL in Node.js

Prerequisites

a. Node.js installed (v14 or later recommended)
b. Basic knowledge of JavaScript and Node.js
c. npm or yarn package manager
  1. Set Up a New Project
mkdir graphql-server
cd graphql-server
npm init -y
  1. Install Required Packages
npm install express express-graphql graphql

This installs:

express: Web framework for Node.js express-graphql: Middleware for creating a GraphQL HTTP server graphql: The JavaScript reference implementation of GraphQL

  1. Create a Basic GraphQL Server

3.1 Define Your Data Model

Create a new file server.js and start by defining your data model using GraphQL’s Schema Definition Language (SDL):

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// Sample data
const books = [
{
id: '1',
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
year: 1925,
genre: 'Novel'
},
{
id: '2',
title: 'To Kill a Mockingbird',
author: 'Harper Lee',
year: 1960,
genre: 'Southern Gothic'
}
];

3.2 Define the GraphQL Schema

Add the schema definition to your server.js file:

// Define the schema using GraphQL schema language
const schema = buildSchema(`
# A book has a title, author, and publication year
type Book {
id: ID!
title: String!
author: String!
year: Int
genre: String
}
# The "Query" type is the root of all GraphQL queries
type Query {
# Get all books
books: [Book!]!
# Get a specific book by ID
book(id: ID!): Book
# Search books by title or author
searchBooks(query: String!): [Book!]!
}
`);

3.3 Implement Resolvers

Add resolver functions to fetch the actual data:

// Define resolvers for the schema fields
const root = {
// Resolver for fetching all books
books: () => books,
// Resolver for fetching a single book by ID
book: ({ id }) => books.find(book => book.id === id),
// Resolver for searching books
searchBooks: ({ query }) => {
const searchTerm = query.toLowerCase();
return books.filter(
book =>
book.title.toLowerCase().includes(searchTerm) ||
book.author.toLowerCase().includes(searchTerm)
);
}
};

3.4 Set Up the Express Server

// Create an Express app
const app = express();
// Set up the GraphQL endpoint
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
// Enable the GraphiQL interface for testing
graphiql: true,
}));
// Start the server
const PORT = 4000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/graphql`);
});
  1. Run and Test Your GraphQL Server

4.1 Start the Server

node server.js

You should see the message: Server running at http://localhost:4000/graphql

4.2 Test with GraphiQL

Open your browser and navigate to http://localhost:4000/graphql to access the GraphiQL interface.

Get All Books:
{
books {
id
title
author
year
}
}
Get a Single Book:
{
book(id: "1") {
title
author
genre
}
}
Search Books:
{
searchBooks(query: "Gatsby") {
title
author
year
}
}
  1. Handling Mutations

Mutations are used to modify data on the server. Let’s add the ability to add, update, and delete books.

5.1 Update the Schema

const schema = buildSchema(`
# ... (previous types remain the same) ...
# Input type for adding/updating books
input BookInput {
title: String
author: String
year: Int
genre: String
}
type Mutation {
# Add a new book
addBook(input: BookInput!): Book!
# Update an existing book
updateBook(id: ID!, input: BookInput!): Book
# Delete a book
deleteBook(id: ID!): Boolean
}
`);

5.2 Implement Mutation Resolvers

const root = {
// ... (previous query resolvers remain the same) ...
// Mutation resolvers
addBook: ({ input }) => {
const newBook = {
id: String(books.length + 1),
...input
}
books.push(newBook);
return newBook;
},
updateBook: ({ id, input }) => {
const bookIndex = books.findIndex(book => book.id === id);
if (bookIndex === -1) return null;
const updatedBook = {
...books[bookIndex],
...input
}
books[bookIndex] = updatedBook;
return updatedBook;
},
deleteBook: ({ id }) => {
const bookIndex = books.findIndex(book => book.id === id);
if (bookIndex === -1) return false;
books.splice(bookIndex, 1);
return true;
}
};

5.3 Testing Mutations

Add Book:
mutation {
addBook(input: {
title: "1984"
author: "George Orwell"
year: 1949
genre: "Dystopian"
}) {
id
title
author
}
}
Update Book:
mutation {
updateBook(
id: "1"
input: { year: 1926 }
) {
title
year
}
}
Delete Book:
mutation {
deleteBook(id: "2")
}

Best Practices

  1. Error Handling
const root = {
book: ({ id }) => {
const book = books.find(book => book.id === id);
if (!book) {
throw new Error('Book not found');
}
return book;
},
// ... other resolvers
}
  1. Data Validation
const { GraphQLError } = require('graphql');
const root = {
addBook: ({ input }) => {
if (input.year && (input.year < 0 || input.year > new Date().getFullYear() + 1)) {
throw new GraphQLError('Invalid publication year', {
extensions: { code: 'BAD_USER_INPUT' }
}
}
// ... rest of the resolver
}
};
  1. N+1 Problem

Use DataLoader to batch and cache database queries:

npm install dataloader
const DataLoader = require('dataloader');
// Create a loader for books
const bookLoader = new DataLoader(async (ids) => {
// This would be a database query in a real app
return ids.map(id => books.find(book => book.id === id));
});
const root = {
book: ({ id }) => bookLoader.load(id),
// ... other resolvers
};