Introduction
Yes, GraphQL can call REST APIs. In fact, this is a common way to use GraphQL in real projects. It lets you use your existing REST services while giving frontend apps the flexibility of GraphQL.
In this article, you’ll learn how to call REST from GraphQL using a very simple and practical method.
Why Use GraphQL with REST?
Many apps already have REST APIs. Instead of replacing them completely, you can wrap those APIs with GraphQL. This lets frontend developers ask only for the data they need, without changing your backend.
You get the best of both worlds:
- Use existing REST endpoints
- Expose a cleaner GraphQL API to clients
Let’s Build It Step-by-Step
We’ll create a GraphQL server using Node.js, and we’ll call a public REST API:
https://jsonplaceholder.typicode.com/users/:id
This is a fake REST API that returns fake user data. It’s perfect for testing.
Step 1: Set Up Project
Make a new folder and install the packages:
mkdir graphql-rest-example
cd graphql-rest-example
npm init -y
npm install express express-graphql graphql axios
Step 2: Create the GraphQL Server
Create a file called index.js
:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const axios = require('axios');
// Step 1: Define GraphQL schema
const schema = buildSchema(`
type User {
id: ID
name: String
username: String
email: String
}
type Query {
user(id: ID!): User
}
`);
// Step 2: Define resolver that calls REST API
const root = {
user: async ({ id }) => {
const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);
const user = await response.data;
return {
id: user.id,
name: user.name,
username: user.username,
email: user.email
};
}
};
// Step 3: Create Express server
const app = express();
app.use(
'/graphql',
graphqlHTTP({
schema,
rootValue: root,
graphiql: true // Enable UI
})
);
app.listen(4000, () => {
console.log('GraphQL server running at http://localhost:4000/graphql');
});
Step 3: Run the Server
Start the server:
node index.js
Then open your browser and go to:
http://localhost:4000/graphql
You’ll see a GraphQL UI where you can run this query:
{
user(id: 1) {
id
name
email
}
}
It will return this result:
{
"data": {
"user": {
"id": "1",
"name": "Leanne Graham",
"email": "Sincere@april.biz"
}
}
}
This proves that you can call a REST API from GraphQL using a resolver.
Conclusion
If you were wondering can GraphQL call REST API? Now you know the answer is yes, and it's quite simple. By calling REST endpoints from your resolvers, you can keep your backend logic and still enjoy the benefits of GraphQL on the frontend.
This method is clean, fast to implement, and great for gradually modernizing your stack.
Finally, if you found this article useful, you can check more here: