GraphQL Installation
Let’s start with GraphQL.js installation. You must have the following things before going to start.
- We need a computer system with running Windows, Linux, or macOS operating system. Here, we are using Windows.
- We need the latest version of a web browser. Here, we recommend Google Chrome.
- Install the latest version of Node.js. See how to install node.js: https://tutoraspire.com/install-nodejs or go to node.js official website https://nodejs.org/en/ and download and install the latest version of node.js
There are two ways to execute GraphQL queries:
- Execute GraphQL query with a command-line tool
- Run an Express GraphQL Server to execute query
Execute GraphQL query with a command-line tool
Here, we are not using any language features that require transpilation, but we will use some ES6 features like Promises, classes, and fat arrow functions, etc.
- Open node.js command prompt.
- Run the following command to create a new project and install GraphQL.js.
How to write the code?
There are three important components for GraphQL application. i.e. schema, query, and resolver. When we write a query for the GraphQL server, then to handle GraphQL queries, we need a schema. The schema is used to define the Query type. We also require an API root with a function called a “resolver” for each API endpoint.
Let’s make an API to simple return “Hello World”. Create a server.js file in the current folder where node.js is installed and write the following code:
Now, run this using the following command:
Here, you can see the GraphQL response printed as
This is a simple GraphQL query that you executed on command prompt without using a server.
Run an Express GraphQL Server to execute query
The easiest way to run a GraphQL API server is to use Express. Express is a popular web application framework for Node.js.
If you have not installed Express yet, first install Express by using the following command
See this link for more information: https://tutoraspire.com/install-expressjs
You have to install two additional dependencies by using the following command:
How to write the code?
Modify the “server.js” file with the following code to make an API server rather than a script that runs a single query. Here, we use the ‘express’ module to run a webserver, and instead of executing a query directly with the graphql function, we can use the express-graphql library to mount a GraphQL API server on the “/graphql” HTTP endpoint
Now, run the GraphQL server by using the following command:
The GraphQL API server is running now. Open http://localhost:4000/graphql on a web browser.
Here, you can see that how to run a GraphQL server and how to use the GraphiQL interface to issue queries. Next TopicGraphQL Architecture