GraphiQL is an interactive development environment. It’s a tool built into many GraphiQL graphical services that allow you to interact with your app data and GraphQL APIs. We will create a basic browser GraphiQL tool using React.js.
It is important to have these prerequisites in order to follow along with this tutorial:
Node.js runtime is installed on your local machine. We need Node.js to create React applications.
We will build a GraphiQL tool with React.js and demonstrate how to use it with a GraphQL API. Therefore, you need to create a GraphQL API that GraphiQL will use. A GraphQL API can be implemented using different technologies. You need to have one running.
Whenever you create a GraphQL API, GraphQL provides an extendable playground to execute and a GraphQL schema for the created API. However, take a scenario where you have a CMS such as WordPress. You need to generate API data to separate the presentation layer.
In this case, an API plays a big role in helping users fetch data from the CMS. Therefore, you need to create a GraphQL interface that will allow these users to generate GraphQL-based queries using GraphiQL.
This helps bridge modern frontend stacks with content management with systems such as CMS. GraphQL queries allow you to have access to multiple root resources with a single request. Below is a basic example of a GraphiQL tool.
We will use the above GraphQL API to integrate with a React GraphiQL tool. Let’s dive in and create GraphiQL using React.js. First, create a basic React.js application using the following command as such:npx create-react-app client
The abovementioned command will generate a new React application with a new directory client
. Change the directory to created client
folder:cd client
Start the development server:npm start
You can now view the created React app in the browser http://localhost:3000
To create a GraphiQL tool, we need the following packages:
GraphQL - Used to build GraphQL type schema and serve GraphQL queries.
GraphiQL - It allows you to create an in-browser GraphQL IDE to design interactive GraphQL components for frontend frameworks.
To get these libraries, use the following command. If yarn is your dependency manager, you may also utilize it.npm install graphql graphiql
For yarn, use:npm install graphql graphiql
Let’s create a UI for interactive GraphQL queries. Head to your React app src/app.js
file and implement the GraphiQL tool as described in the following steps:
Import the dependencies and the peer dependencies as follows:
1 2 3 4 5 6 7 8 9 10
import React from 'react'; // import GraphiQL to have access to GraphiQL tools import GraphiQL from 'graphiql'; //Import graphql features that you want to use in your GraphiQL import { getIntrospectionQuery, buildClientSchema } from 'graphql'; // Add the css for styling enhancements import 'graphiql/graphiql.min.css';
Send requests to the server using fetch. In this case, make sure you add the GraphQL URL that executes the GraphQL route of your server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const fetcher = async (graphQLParams) => {
const data = await fetch(
// This is an endpoint that points to your running GraphQL server
'http://localhost:4000/graphql', {
//headers Post method
method: 'POST',
// Add the headers needed to access the above server
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
// specify the origin credentials for both applications to be able to communicate
body: JSON.stringify(graphQLParams),
// The origin data sharing policy
credentials: 'same-origin',
},
);
// return the origin of the data being shared
return data.json()
.catch(() => data.text());
}
Create a class React component.
1
class App extends React.Component {}
Inside this component, create a GraphiQL component as follows:
Define the state. Here, create the state for the GraphQL schema and query as follows:
1
2
3
4
5
6
7
8
9
10
11
_graphiql;
state = {
schema: null,
query: '# Hola!'
};
_handleEditQuery = (query) => this.setState({
query
});
componentDidMount() {
this.updateSchema();
}
Execute the GraphQL from the server and sever the result of the server JSON response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
executeQuery = async (graphQLParams) => { // Handle the response from the graphql server const response = await fetch('http://localhost:4000/graphql', { //headers Post method method: 'POST', // Add the headers needed to access the above server headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, // specify the origin credentials for both applications to be able to communicate credentials: 'same-origin', // json body body: JSON.stringify(graphQLParams), }); // save the response from the server const result = await response.json(); // return the saved results of the above response return result; }
Using an async method, fetch the schema from the response result executed by the executeQuery function. In this case, create an async method and fetch the schema inside a try and catch block as follows:
Create the updateSchema()
function.
1 2 3
async updateSchema() { try {} }
Inside this function, try to block fetch the schema using introspection query.
1 2 3 4 5
const { data } = await this.executeQuery({ query: getIntrospectionQuery() });
Use the data we got back from GraphQL to build a client schema.
1
const schema = buildClientSchema(data);
Update our component with the new schema.
1 2 3
this.setState({ schema });
Log any errors.
1
2
3
this.setState({
error: null
});
Finally, close the catch block inside updateSchema() to catch errors as follows:
1 2 3 4 5 6 7
catch (error) { console.error('Error occurred when updating the schema:'); console.error(error); this.setState({ error }); }
Render the GraphQL data on the browser. This references the _graphiql
and fetches the execute the GraphQL requests from the server.
Additionally, you can add the Prettify, History, and Explorer toolbar to GraphiQL. Here they are represented as dummies. Go ahead and implement them if your GraphiQL needs such functionalities.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
render() { return ( <div className="graphiql-container"> <GraphiQL ref={ref => (this._graphiql = ref)} fetcher={fetcher} > <GraphiQL.Toolbar> <GraphiQL.Button title="Prettify Query (Shift-Ctrl-P)" label="Prettify" /> <GraphiQL.Button label="History" title="Show History" /> <GraphiQL.Button label="Explorer" title="Construct a query with the GraphiQL explorer" /> </GraphiQL.Toolbar> </GraphiQL> </div> ); }
Finally, export the App component.
1
export default App;
Let’s test if this tool is working as expected. At this point:
Ensure your GraphQL server is running.
Ensure the React app is running and open the app in the browser using the URL http://localhost:3000
. You will be served with the GraphiQL tool we have just created.
Let’s test if the React GraphiQL tool can interact with the API data. We will execute a query to fetch posts from the database as follows:
1 2 3 4 5 6
query Query { posts { title description } }
Add this query to the GraphiQL tool.
Then hit the play button.
And there you have it. The frontend tool you created can directly interact with your server, deploy it, and allow users to interact with the content managed by your API.
GraphQL uses a mechanism that queries data and then displays that data with the GraphQL schema. This uses GraphiQL. You might want to query data from your application. A good example is how WordPress uses wpGraphQL to fetch WordPress-driven data.
This guide helped you create a GraphiQL tool to perform such GraphQL tasks. This provides extendable GraphQL features within your application.