Examples of REST, GraphQL, RPC, gRPC
Tags: api, webdev, microservices, graphql
Published: 2024-06-24 07:02:02

This article will focus on practical examples of major API protocols: REST, GraphQL, RPC, gRPC. By examining these examples, you will gain a clearer understanding of how each protocol operates and how to implement them in your own projects.

If you haven't read the first article comparing REST, GraphQL, RPC, and gRPC, check it out here - [Comparative Analysis: REST, GraphQL, RPC, gRPC](https://dev.to/rahulvijayvergiya/rest-graphql-rpc-grpc-3m09)

## REST Example
This example demonstrates how to fetch a user's information using a GET request.

**Endpoint:** GET /users/{id}

**Node.js Example:**
```
const express = require('express');
const app = express();

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Simulate fetching user from database
  const user = {
    id: userId,
    name: "John Doe",
    email: "john.doe@example.com"
  };
  res.json(user);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
```
**Request:**

```
GET /users/123 HTTP/1.1
Host: localhost:3000
```

**Response:**

```
{
  "id": 123,
  "name": "John Doe",
  "email": "john.doe@example.com"
}
```
---
## GraphQL Example
This example shows how to fetch a user's information using a GraphQL query.

**Query:**

```
{
  user(id: 123) {
    id
    name
    email
  }
}
```
**Node.js Example:**
```
const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type User {
    id: ID!
    name: String!
    email: String!
  }

  type Query {
    user(id: ID!): User
  }
`;

const resolvers = {
  Query: {
    user: (_, { id }) => {
      return {
        id,
        name: "John Doe",
        email: "john.doe@example.com"
      };
    }
  }
};

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

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

```
{
  "data": {
    "user": {
      "id": 123,
      "name": "John Doe",
      "email": "john.doe@example.com"
    }
  }
}
```
---

## RPC Example
This example shows how to call a remote procedure to fetch user data.

**Request:**
```
{
  "method": "getUser",
  "params": [123],
  "id": 1,
  "jsonrpc": "2.0"
}
```
**Node.js Example:**

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

app.use(bodyParser.json());

app.post('/rpc', (req, res) => {
  const { method, params, id } = req.body;
  if (method === 'getUser') {
    const userId = params[0];
    const user = {
      id: userId,
      name: "John Doe",
      email: "john.doe@example.com"
    };
    res.json({
      result: user,
      id,
      jsonrpc: "2.0"
    });
  } else {
    res.status(400).json({ error: 'Unknown method' });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
```
**Response:**
```
{
  "result": {
    "id": 123,
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  "id": 1,
  "jsonrpc": "2.0"
}
```
## gRPC Example
This example shows a gRPC service definition and client call to fetch user data.

**Protocol Buffer Definition:**
```
syntax = "proto3";

service UserService {
  rpc GetUser (UserRequest) returns (UserResponse);
}

message UserRequest {
  int32 id = 1;
}

message UserResponse {
  int32 id = 1;
  string name = 2;
  string email = 3;
}
```
**Node.js Example:**

```
const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync('user.proto', {});
const userProto = grpc.loadPackageDefinition(packageDefinition).user;

const server = new grpc.Server();
server.addService(userProto.UserService.service, {
  GetUser: (call, callback) => {
    const user = {
      id: call.request.id,
      name: "John Doe",
      email: "john.doe@example.com"
    };
    callback(null, user);
  }
});
server.bind('localhost:50051', grpc.ServerCredentials.createInsecure());
console.log('gRPC server running on port 50051');
server.start();
```
**Client Code:**
```
const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync('user.proto', {});
const userProto = grpc.loadPackageDefinition(packageDefinition).user;

const client = new userProto.UserService('localhost:50051', grpc.credentials.createInsecure());

client.GetUser({ id: 123 }, (error, response) => {
  if (!error) {
    console.log('User:', response);
  } else {
    console.error(error);
  }
});
```
**Response:**
```
{
  "id": 123,
  "name": "John Doe",
  "email": "john.doe@example.com"
}
```