

GraphQL + REST API
source link: https://blog.geekyants.com/graphql-rest-api-f996805d732d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

GraphQL + REST API
Let’s understand how we can combine the best of Graph QL with REST API to achieve the maximum results.
Table of Contents
- What is GraphQL?
- Why Use GraphQL over a Traditional REST API?
- GraphQL With REST
- How To Use REST API in GraphQL?
- How to Implement REST API in Apollo Client?
- Creating an App
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?
- One Endpoint
- Declarative Response
- Fewer Server Requests
- 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:
- Apollo Client
- 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.
npx create-react-app apollo-rest-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.
restClient.jsimport { ApolloClient, InMemoryCache } from '@apollo/client';import { RestLink } from 'apollo-link-rest';
// Set `RestLink` with your endpointconst restLink = new RestLink({ uri: "<http://localhost:4001>" });// Setup your clientexport const restClient = new ApolloClient({link: restLink});
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.
Traditional GraphQL Query
const GET_GRAPHQL_TODOS = gql`query getTodos {getTodos {idtitlecompleted}}`;Rest + Graphql Query
const GET_REST_TODOS = gql`query getTodos {getTodos @rest(path: "/todos") {idtitlecompleted}}`;
Just two changes from the traditional query.
- @rest — it’s added to denote a REST API
- path — to mention the path of the API.
2. Executing the GET ALL query and displaying the data.
import { useMutation, useQuery } from "@apollo/client";import { GET_REST_TODOS } from "../query";import { restClient } from "../restClient";export const Todos = () => {//getconst { data } = useQuery(GET_REST_TODOS, { client: restClient });return data?.getTodos?.map(({ id, title, completed, }: any) =><div key={id}><p className={completed ? "Todo-task completed" : "Todo-task"}>{title}</p></div>);};
3. Adding new todo data using the query.
Traditional Queryconst ADD_TODO_GRAPHQL = gql`mutation CreateTodo($title: String!$description: String!$completed: Boolean!$user: String!) {createTodo(title: $titledescription: $descriptioncompleted: $completeduser: $user) {idtitlecompleteddescriptionuser {idnameage}}}`;Rest + GraphQL Queryconst ADD_TODO_REST = gql`mutation CreateTodo {createTodo(input: $input)@rest(path: "/todos", method: "POST", bodyKey: "input") {idtitlecompleteddescriptionuser {idnameage}}}`;
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.
import { useMutation } from "@apollo/client";import { useState } from "react";import { ADD_TODO_REST } from "../query";import { restClient } from "../restClient";export const Todos = () => {const [newTodoTitle, setNewTodoTitle] = useState("");// addconst [addTodo] = useMutation(ADD_TODO_REST, {client: restClient,});return (<div><form
onSubmit={(e) => {e.preventDefault();addTodo({variables: {input: {completed: false,title: newTodoTitle},},});setNewTodoTitle("");}}><input
value={newTodoTitle}onChange={(e) =>setNewTodoTitle(e.target.value )}/><button type="submit">Add Todo</button></form></div>));};
5. Delete a Todo by id.
Traditional Queryconst DELETE_GRAPHQL = gql`mutation deleteTodo($id: String!) {deleteTodo(id: $id) {idtitlecompleteddescription}}`;Rest + GraphQL Queryconst DELETE_REST = gql`mutation DeleteTodo($id: String!) {deleteTodo(id: $id)@rest(type: "Todo", path: "/todos/{args.id}", method: "DELETE") {NoResponse}}`;
6. Executing the Delete todo in the code.
import { useMutation } from "@apollo/client";import { useState } from "react";import { DELETE_TODO_REST } from "../query";import { restClient } from "../restClient";export const Todos = () => {//getconst { data } = useQuery(GET_REST_TODOS, { client: restClient });// deleteconst [deleteTodo] = useMutation(DELETE_TODO_REST, {client: restClient,},});const deleteTodoById = async (id: string) => {deleteTodo({variables: {id,},});};return data?.getTodos?.map(({ id, title, completed, }: any) =><div key={id}><p className={completed ? "Todo-task completed" : "Todo-task"}>{title}</p><button onClick={() => deleteTodoById(id)}>Delete</button></div>)};
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.
This article was written by Yogeshwaran Ramesh, Senior Software Engineer at GeekyAnts.
</div
Recommend
-
32
Cover image by Alexandra on Flickr Arguing about technology choices is a huge thing,
-
18
Mikä on GraphQL ja miten se eroaa REST-rajapinnoista (API)? Teknologiamaailmassa tunnetusti riittää jargonia. Toinen toistaan parempi teknologia tuntuu seuraavan toisiaan. Viime vuos...
-
7
REST API to OpenApi to GraphQLThe journey from undocumented untyped API to typed GraphQL using GraphQL-MeshI love GraphQL. I really believe it is the next generation of API implementation. It i...
-
15
我们知道,两个单独的应用程序需要中介程序才能相互通信。因此,开发人员通常会搭建桥梁(应用程序编程接口),以允许一个系统访问另一个系统的信息或功能。为了快速、大规模地集成应用程序,API是使用协议或规范实现的,这些协议或规范定义了通...
-
7
Samson Omojola Follow I'm an experienced software engineer. I love creating applications with responsive, beautiful, intuitive, state-of-the-art designs. I'm sk...
-
6
Spring REST GET API vs Spring GraphQL Query APIIn this tutorial, I would like to show you how to create GraphQL Query API using Spring Boot. Most software developers use REST API, so for a better understanding, I wil...
-
14
Introduction This article introduces a model-driven REST or GraphQL API for CRUD (Create, Read, Update, Delete). With it, you can write simple models (specifying a database table and the set of columns to be exposed) and the REST endpoin...
-
6
REST vs GraphQL vs gRPC三者API技术比较 3种最流行的A...
-
9
Learning Objectives How to add GraphQL wrapper How to use the NSwag tool to generate code Prerequisites Require “HotChocolate.AspNetCore” from the NuGet package. Require .Net 5 Framewor...
-
9
DEV Community ???? You have probably heard about GraphQL, but you might not be entirely sure how and whether it differs from REST. You're in luck, then! Today, we'l...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK