Oct 7, 2022

GraphQL + REST API

Let's understand how we can combine the best of Graph QL with REST API to achieve the maximum results.
Yogeshwaran Ramesh
Yogeshwaran RameshSenior Software Engineer - II
lines

Pre-requisite

  • GraphQL
  • React

Before Diving into the topic, let's understand what is GraphQL first.

What is GraphQL?

GraphQL is a query language for your API and a server-side runtime for executing queries using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data.

Why Use GraphQL over a Traditional REST API?

  1. One Endpoint
  2. Declarative Response
  3. Fewer Server Requests
  4. Auto Documentation of Queries

The mantra of GraphQL is - “Ask for what you want − and get it”.

GraphQL With REST

Calling REST APIs from a GraphQL client opens the benefits of GraphQL for many developers.

Now, let's see how we can use the existing REST APIs as GraphQL Query.

How To Use REST API in GraphQL?

There are many libraries to support the efficient way of querying data using GraphQL.

Like:

  1. Apollo Client

Introduction to Apollo Client

  1. URQL

URQL Documentation

  1. Relay

Relay

But for using REST API with GraphQL, Apollo client is the only package to support REST as of now.

How to Implement REST API in Apollo Client?

Let's get our hands dirty.

First, let's create a new React app.

We’ll create a new REST Client file.

For integrating the REST API, apollo-client provides a package apollo-link-rest to create a REST client.

REST Link

Simple, right?!

Creating an App

Let’s create a simple to-do app to see how to do CRUD operations using REST API in GraphQL.

1. Writing the query to get all the to-do data from the backend.

We need to write a GraphQL query to get all the data.

Just two changes from the traditional query.

  1. @rest - it's added to denote a REST API

  2. path - to mention the path of the API.

2. Executing the GET ALL query and displaying the data.

3. Adding new todo data using the query.

4. Executing the Add Todo in the code.

To pass the values to the body of the API call, we can pass them inside the `addTodo` function as variables parameter. Inside variables, we can pass the data as part of the `input (bodyKey input in the query)` object.

5. Delete a Todo by id.

6. Executing the Delete todo in the code.

As simple as that 😎.

Instead of Converting the existing REST APIs into a GraphQL API, you can now directly integrate REST APIs with GraphQL queries.

Hire our Development experts.