Fetching Data with GraphiQL

GraphiQL is an interactive platform that allows user to query the GraphQL API from the browser itself, without the need to download, or go to another platform. GraphiQL also provides other features like auto-completion, syntax highlighting, etc.

Let’s look at how we can fetch the GraphQL data using GraphiQL.

Step 1: We will create a basic NodeJS server to setup up our GraphQL API

In the below code, we will create a basic GraphQL API, with only one query, “hello”, and we will create a resolver that returns “Hello, GFG!”, when the query is called. We will use express to setup and create our server, and we will use the “graphqlHTTP” express middleware to create a graphQL endpoint for our server.

Filename: server.js

Javascript




const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
  
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);
  
const root = {
  hello: () => {
    return 'Hello, GFG!';
  },
};
  
const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
  
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}/graphql`);
});


Step 2: Start the server

To start the server run the below command in the terminal.

node server.js

Output:

Server running on http://localhost:4000/graphql

Step 4: Test the query in GraphiQL interface.

To test the query, execute the below query in the GraphiQL interface.

query {
hello
}

Output:

The output of the above query will look like below

Data Fetching with GraphQL

GraphQL is an open-source technology that allows us to query only the data that we require, unlike the traditional REST architecture which returns us the entire resources and data with specific endpoints configured for the same. Using GraphQL, we specify using the query the data that we want, and it returns the specified data in the specified format. It helps reduce the amount of data transfer over the network and saves network bandwidth.

This article will teach us how to fetch data using GraphQL, with React as our front-end UI library.

Similar Reads

Fetching GraphQL Data with React as a UI Library

Step 1: Create an open-source application...

Fetching GraphQL Data Using Fetch API

...

Fetching Data with GraphiQL

...

Conclusion

...

Contact Us