How to write GraphQL Code?

How to write GraphQL Code?

Before we start using GraphQL, we should know some important basic terms that are very useful for understanding the concept of GraphQL.

In the GraphQL Installation, we have used various commands, and many of the commands we are going to use further. The first term that we need to understand is 'npm.' Basically, 'npm' is one of the different package managers for the programming language JavaScript.  As mentioned, npm is a package manager, and it is the default package manager for node.js. It is the essential requirement for running GraphQL on your device.

To write GrpahQL code, we need to follow the below steps:

  • Firstly, open your Command prompt and enter the following command.
‘npm -v’

When you press the enter key, this command will tell you the version of npm installed in your system. The knowledge of versions of npm is also crucial because many commands may differ in different kinds of versions.

How to write GraphQL Code?

Once you know the version of npm installed in your system, you can enter the commands which will work in your npm version.

  • Now, write npm in your command prompt and press enter, and you will see some necessary details about the npm as in the following result window:
How to write GraphQL Code?

This window also tells you about some basic commands and how to enter and run them correctly in your system's command prompt. We all have learned what npm is and how commands will work in the command prompt.

  • For more info about how the npm works and how npm runs in your system, enter the following command:
'npm init -y.'

when you press the enter key, you will see the following result window in the system's command prompt:

How to write GraphQL Code?

As you all will look at this result window, telling us about all the packages installed in our system. All the packages that are mentioned here, we have already installed in our previous installation section.

Note: If you haven't done with the installation part yet, please go to the previous section, and you will learn how to install all these packages.

So, in the result window, we also see that the result is also telling about versions of all the packages installed in our system in the previous installation section.

When you run the command, as mentioned above in system's command prompt, npm will create a 'package.json’  file in your system. All the dependencies required for GraphQL to run, which are installed in your system, and all the commands will be there in the file, as mentioned above, that npm has created.

So, as we have learned how what is npm and how it works? We are ready to write query in the GraphQL using the node.js installed in the system.

To understand it, we will create a simple GraphQL "Hello-world" example. It will use the Node.js, Apollo-server, Express app (which we have installed previously) and GraphQL. We will use all the packages mentioned above to build a GraphQL API to communicate between client-side and server-side. Let’s discuss each of them:

Node.js: -Basically if we talk about only the node.js, it is open-source, which can be used or build in many kinds of platform, a server-side runtime environment. It is used for executing the JavaScript code outside of any web browser.

Express: - The express we have installed is a prevalent web application framework used with node.js. As we have mentioned, it is a web application framework, so it is used to build different kinds of websites and different kinds of web applications alongside the node.js.

Apollo Server: - As the name suggests, the apollo server is a server platform. It is a spec-compliable server for GraphQL, and it is also open-source. It is so easy to use with the many GraphQL-clients such as apollo-client. This server is the widest server used for the GraphQL-API, which can fetch data from any source worldwide.

GraphiQL: - As it is mentioned in the Name of GraphiQL ‘I,' so GraphiQL is an IDE (Integrated Development Environment) for the GraphQL. GraphiQL is a potent tool to develop many kinds of websites, especially the websites which take static data and convert that data into a dynamic site with the help of ReactJS (Also called Gatsby Websites)

Now, let's build our first example of GraphQL query with installed packages that are installed in our previous section of the installation part of this GraphQL tutorials. We have learned to install GraphQL in our system with two methods. We will now write one example query of GraphQL by using each package installed for GraphQL.

  1. Writing and Executing a GraphQL query directly using a command prompt inline tool.
  2. Writing and executing a GraphQL query by setting up an express app server.

1. Writing and executing a GraphQL query directly using a command prompt inline tool: -

As we have installed GraphQL set up in our system directly using the npm command prompt, we will also write our query and directly execute it using the command prompt inline tool.

For executing a query, you will need to write a basic code in the JavaScript programming language. For writing the code, you need a text editor. There are many text editors available, and you can use any of them. Some examples of text editors are Notepad, Notepad++, Visual Studio Code etc. etc. You can use any one of the text editors according to your system, and which you like the most.

Now, moving forward, open text editor and write the following code in the text editor:

var { graphql, buildSchema } = require('graphql'); 
// A schema is constructed using GraphQL schema language 
var schema = buildSchema(` 
  type Query { 
    hello: String 
} 
`);
// Following root provides a resolver function for every each API's endpoint. 
var root = { 
  hello: () => { 
    return 'Hello GraphQL World! This is the first example of GraphQL query'; 
  }, 
}; 
// Run this written GraphQL query '{ hello }' and print out the response of the query. 
graphql(schema, '{ hello }', root).then((response) => { 
  console.log(response); 
});

After writing this code, save the file name with server.js in the folder where your node.js file is installed. In the case, if you don't know the directory of where node.js is installed in your system, the default location for the file is C:\ Users\ Name (Name of the user). If you are confused with where to save the server.js file in your device, save it in the same directory, which is mentioned above for the default location of node.js file, i.e., C:\ Users\ name.

Once you save the server.js file in your system with the above-written code, you have to open the command prompt and write the following command in command prompt to open the file express.js with the node which will execute your query:

'node express.js.'

Now, press the enter key. After pressing the enter key, you will see the following result window in the command prompt of your system:

How to write GraphQL Code?

We can see that in this result window, GraphQL executed and printed out the query:

hello: "Hello, GraphQL World! It is the first example of a GraphQL query."

It is a simple GraphQL query executed and printed in your system's command prompt without any help from the server. Now, we will execute our GraphQL query with the help of server and APIs using the express app in our next method of executing the GraphQL query.

2. Writing and executing a GraphQL query by setting up express app server:-

The simplest and easiest way for executing GraphQL APIs on the server is through the use of an express app. Now, we will use an API server file rather than a script file, which only able to run a single query request. We will use the Express module web server for the server method, which will work as a server for all GraphQL queries. We will also use the graphql-express library to build a GraphQL API server on the HTTP endpoint.

Open the “express.js” file which you have created in the text editor and modify that file with the following code: -

  var express = require('express'); 
var graphqlHTTP = require('express-graphql').graphqlHTTP; 
var { buildSchema } = require('graphql'); 
// Construct a schema, using GraphQL schema language 
var schema = buildSchema(` 
  type Query { 
    hello: String 
} 
`); 
// The root provides a resolver function for each API endpoint 
var root = { 
  hello: () => { 
    return 'Hello world!'; 
  }, 
}; 
var app = express(); 
app.use('/graphql', graphqlHTTP({ 
  schema: schema, 
  rootValue: root, 
  graphiql: true, 
})); 
app.listen(4000); 
console.log('Running a GraphQL API server at http://localhost:4000/graphql');

Save the same server.js file with the above-written code and with the same name.

The critical thing in this to remember is that in the previous versions of npm, you can run the server file with old coding files, but that is what you can't do in newer versions of npm. See the second line of the above code for the older versions, where you don't need to write highlighted ".graphqlHTTP” to run the file. In the older versions, you could only write ‘var graphqlHTTP = require('express-graphql');’ file would have run successfully without throwing any error, but in the newer versions, if you don't add ". graphqlHTTP", the npm will throw an error and will not run the file. So, please do remember these points and code according to the npm versions of your device.

Now, open the command prompt of your system and write the following command to run the GraphQL server with the use of the express app:

‘node  server.js’

After pressing the enter, you will see the following result window in your command prompt:

How to write GraphQL Code?

Now, the GraphQL API server is running in your system. It means now when you will launch the query in the GraphQL, it will fetch the requisite data from the server file, which you created above.

Now, copy the URL: http://localhost:4000/graphql,  and paste, and run in the web browser of your device. You will see a GraphiQL window will show up. On the left side, some queries are written, and on the right side, the results that GraphQL has fetched from the server.

Clear all the queries from the left and write:

{
Hello
}

This query will fetch the data from your server file. And it will show the result of the requested query on the right side of the window of the web browser.

How to write GraphQL Code?

So, that's how you can execute your queries while building a GraphQL server with express help.

In this section, we have learned how to write code/queries in GraphQL and how to execute them in our system.