DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on

GraphQL Vs. REST API

Image description
REST (Representational State Transfer) is an architectural style that defines a set of constraints for creating web services. It uses HTTP requests to access and manipulate data, and it typically relies on JSON (JavaScript Object Notation) as the data format. RESTful APIs are characterized by having well-defined endpoints that correspond to resources, and by being stateless, meaning that each request contains all the information needed to process it.
Example:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// Middleware to parse request body as JSON
app.use(bodyParser.json());

// Sample data
const users = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 },
];

// GET /users - get all users
app.get('/users', (req, res) => {
  res.json(users);
});

// GET /users/:id - get user by ID
app.get('/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 /users - create a new user
app.post('/users', (req, res) => {
  const user = {
    id: users.length + 1,
    name: req.body.name,
    age: req.body.age,
  };
  users.push(user);
  res.status(201).json(user);
});

// PUT /users/:id - update user by ID
app.put('/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.age = req.body.age;
  res.json(user);
});

// DELETE /users/:id - delete user by ID
app.delete('/users/:id', (req, res) => {
  const index = users.findIndex(u => u.id === parseInt(req.params.id));
  if (index === -1) {
    return res.status(404).json({ message: 'User not found' });
  }
  users.splice(index, 1);
  res.json({ message: 'User deleted' });
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

GraphQL, on the other hand, is a query language for APIs that was developed by Facebook. It provides a more flexible and efficient alternative to REST by allowing clients to specify exactly what data they need and in what format. GraphQL APIs are characterized by having a single endpoint that can respond to a variety of queries, and by allowing clients to fetch related data in a single request, thereby reducing the number of round-trips to the server.
Example:

const express = require('express');
const bodyParser = require('body-parser');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express();

// Middleware to parse request body as JSON
app.use(bodyParser.json());

// Sample data
const users = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 },
];

// Define the schema
const schema = buildSchema(`
  type User {
    id: ID!
    name: String!
    age: Int!
  }

  type Query {
    users: [User!]!
    user(id: ID!): User
  }

  input UserInput {
    name: String!
    age: Int!
  }

  type Mutation {
    createUser(input: UserInput!): User!
    updateUser(id: ID!, input: UserInput!): User!
    deleteUser(id: ID!): User!
  }
`);

// Define the resolvers
const root = {
  users: () => users,
  user: (args) => users.find(u => u.id === parseInt

Enter fullscreen mode Exit fullscreen mode

While RESTful APIs are more established and widely used, GraphQL offers several advantages over REST, including:

Increased flexibility and efficiency due to the ability to fetch only the required data

Improved developer productivity by providing a strongly-typed schema and detailed documentation

Simplified client-server communication by reducing the number of API endpoints

Better handling of complex data relationships and nested data structures

That being said, each approach has its own strengths and weaknesses, and the choice between them ultimately depends on the specific needs of the project.

Image description

Top comments (0)