0
0
Expressframework~5 mins

REST vs GraphQL awareness in Express

Choose your learning style9 modes available
Introduction

REST and GraphQL are two ways to get data from a server. They help your app talk to the backend and show information to users.

You want to build a simple app that gets data from a server with fixed endpoints.
You need to let users ask for exactly the data they want to reduce extra information.
You want to support many different clients like web, mobile, or smart devices with one API.
You want to easily add or change data fields without breaking old clients.
You want to control how much data is sent to save bandwidth and speed up loading.
Syntax
Express
/* REST example: Express GET endpoint */
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  // fetch user by userId
  res.json(userData);
});

/* GraphQL example: Single endpoint with query */
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
  type Query {
    user(id: ID!): User
  }
  type User {
    id: ID
    name: String
    email: String
  }
`);

const root = {
  user: ({ id }) => {
    // fetch user by id
  }
};

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

REST uses multiple URLs for different data types and actions.

GraphQL uses one URL and lets clients specify what data they want in a query.

Examples
REST uses different URLs for different requests.
Express
/* REST: Get user by ID */
GET /users/123

/* REST: Get all users */
GET /users
GraphQL lets you ask for specific fields in one request.
Express
/* GraphQL: Query user by ID */
{
  user(id: "123") {
    id
    name
  }
}
REST uses HTTP methods like PUT to update data.
Express
/* REST: Update user email */
PUT /users/123
{
  "email": "new@example.com"
}
GraphQL uses mutations to change data with flexible responses.
Express
/* GraphQL: Mutation to update user email */
mutation {
  updateUser(id: "123", email: "new@example.com") {
    id
    email
  }
}
Sample Program

This program shows both REST and GraphQL ways to get user data by ID. You can try REST by visiting /users/1 or GraphQL by sending a query to /graphql.

Express
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express();
app.use(express.json());

// Sample data
const users = [
  { id: '1', name: 'Alice', email: 'alice@example.com' },
  { id: '2', name: 'Bob', email: 'bob@example.com' }
];

// REST endpoint to get user by ID
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  const user = users.find(u => u.id === userId);
  if (user) {
    res.json(user);
  } else {
    res.status(404).json({ error: 'User not found' });
  }
});

// GraphQL schema
const schema = buildSchema(`
  type User {
    id: ID
    name: String
    email: String
  }
  type Query {
    user(id: ID!): User
  }
`);

// Root resolver
const root = {
  user: ({ id }) => users.find(u => u.id === id)
};

// GraphQL endpoint
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true
}));

// Start server
app.listen(4000, () => {
  console.log('Server running on http://localhost:4000');
  console.log('Try REST: GET http://localhost:4000/users/1');
  console.log('Try GraphQL: http://localhost:4000/graphql');
});
OutputSuccess
Important Notes

REST is simple and works well for fixed data needs but can send extra data you don't want.

GraphQL lets clients ask for exactly what they need, reducing data transfer.

GraphQL requires learning query language and setting up a schema, which can be more complex.

Summary

REST uses multiple URLs and HTTP methods to get and change data.

GraphQL uses one URL and lets clients specify exactly what data they want.

Choose REST for simple APIs and GraphQL for flexible, efficient data fetching.