Code samples used in this blog series have been updated to latest version of .NET Core (5.0.4) and GraphQL-Dotnet (4.2.0). Follow this link to get the updated samples.
GraphiQL (pronounced graphical) is an in-browser IDE for exploring GraphQL. I think it's a must-have tool for any server running behind GraphQL. With GraphiQL in place, you can easily give yourself or your team an in-depth insight into your API.
There are setups you have to do first. We need some packages installed. Create a package.json file and paste the following snippet,
You might say, "Why do we need React!". GraphiQL is really just a React component. In order to use this component, we need a basic app skeleton similar to any React app, you will find online.
At this point, you can either use yarn or npm to install the packages.
Next, create a folder ApiExplorer and add the following two files with the code snippets,
GraphiQL is a client-side library which provides a React component i.e. <GraphiQL/>. It renders the whole graphical user interface of the IDE. The component has a fetcher attribute which can be attached to a function. The attached function returns an HTTP promise object which just mimics the POST requests that we have been making with Insomnia/Postman. All of these are done in the index.jsx.
The final bits is to bundle up and ship them to a publicly available static files folder. The task of bundling up is done by webpack. Add a webpack.config.js file and paste the following piece of code,
The configuration is pretty much self-explanatory. It takes all the files under the ApiExplorer folder, the dependencies from the node_modules and compiles them into a single bundle.js file. It also generates an index.html file. Both of the compiled files are sent to the wwwroot to make them publicly available.
All done! Now run the webpack command in the terminal on the root of your project.
On the server-side, in Startup.cs files, add the middleware to serve static files, specifically the default index.html file,
The Configure method should look like the following,
Now, run the application and you will be presented with the following interface,
If you get an error like the following,
System.InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.
ASP.NET 3.0+ throws this error when some synchronous call is made. It means that GraphQL Dotnet library still depends on Newtonsoft.Json. And that library does some synchronous code execution. But for the time being, we can also overcome this situation. We only have to add these lines of code in ConfigureServices method.
On the right-hand side is the documentation explorer pane, you can browse through different queries and have a deep understanding of what fields are available and what they are supposed to do
Some of the nice features this IDE has to offer are as follows,
Intelligent type ahead of fields, arguments, types, and more.