[Note]GraphQL – Quick Guide (tutorialspoint.com) In this chapter, we’ll create a simple API that returns a greeting message, HelloWorld, and accesses it using GraphiQL.

The sample

This example is based on NodeJS, Express, and Apollo servers. We will learn to combine all the concepts by following these steps:

Step 1: Set up Express

ExpressJS is a Web application framework that helps build Websites and Web applications. In this example, we will build a GraphQL API on top of the Express framework. The next step is to create the folder Hello-world-server and navigate from the terminal to the same folder. Add package.json and name the package. Since this package is for internal use only, we can declare it private.

{
    "name": "hello-world-server"."private": true
}
Copy the code

Install the Express server dependencies as follows: C:\Users\Admin\hello-world-server> NPM install Express Body-parser Cors body-parser is a middleware package. Can help Express process HTTP Post requests efficiently. Cors is another middleware package that handles sharing across source resources. Create a server.js file in your project folder and type the following in it:

const bodyParser = require('body-parser')
const cors = require('cors')
const express = require('express')
const port = process.env.PORT|| 9000
const app = express()
//register middleware
app.use(bodyParser.json() , cors())
app.listen(port, () = > console.log(`server is up and running at ${port}`))
Copy the code

To verify that the Express server is up and running, execute the following code in the terminal window:C:\Users\Admin\hello-world-server>node server.jsThe following output is displayed in the server console. This indicates that the Express server is running on port 9000.server is up and running at 9000If you open a browser and typehttp://localhost:9000, you will see the following screen:To stop the server, pressCtrl + C.

Step 2: Install GraphQL and Apollo Server

Now that Express is configured, the next step is to download the following GraphQL dependencies:

  • graphql
  • graphql-tools
  • apollo-server-express@1

We will use Apollo server V1.0 because it is a stable release. Type the following command to install these dependencies: C:\Users\Admin\hello-world-server> NPM install graphQL graphqL-tools apollo-server-express@1 we can do this by checking the one we created earlier The package.json file is used to verify that these dependencies were successfully installed.

{
    "name": "hello-world-server"."private": true."dependencies": {
        "apollo-server-express": "^ 1.4.0." "."body-parser": "^ 1.18.3"."cors": "^ 2.8.4"."express": "^ 4.16.3"."graphql": "^ 0.13.2"."graphql-tools": "^ 3.1.1." "}}Copy the code

Step 3: Define the schema

The GraphQL schema defines what objects can be retrieved from the service and what fields it has. Schemas can be defined using the GraphQL schema definition language. Now add the following code snippet to the server.js file:

// Adding Type Definitions
const typeDefinition = `
   type Query  {
      greeting: String
   }`
Copy the code

Here, the query contains the greeting property that returns a string value.

Step 4: Create the parser

The first step in creating a parser is to add some code to handle requests for greeting fields. This is specified in the parser. The structure of the parser function must match the pattern. Add the following code snippet to the server.js file.

// Adding resolver
const resolverObject = {
    Query: {
        greeting: () = > 'Hello GraphQL  From TutorialsPoint !!'}}Copy the code

The second step is to use the makeExecutableSchema binding pattern and parser. This function is predefined in the GraphQL-Tools module. Add the following code snippet to the server.js file.

const {makeExecutableSchema} = require('graphql-tools')
const schema = makeExecutableSchema({typeDefs:typeDefinition, resolvers:resolverObject})
Copy the code

Step 5: Define the route to get the data from the ReactJS/GraphiQL application

Add the following code snippet to the server.js file:

const {graphqlExpress, graphiqlExpress} = require('apollo-server-express')

//create routes for graphql and graphiql
app.use('/graphql',graphqlExpress({schema}))
app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))
Copy the code

GraphqlExpress help registered http://localhost:9000/graphql routing function. ReactJS applications can use this endpoint to query data. Similarly, graphqliExpress function helps to registered http://localhost:9000/graphiql routing. This will be used by the GraphiQL browser client to test the API. The complete server.js code is as follows:

Const bodyParser = require('body-parser')
const cors = require('cors')
const express = require('express')
const port = process.env.PORT || 9000
const app = express()

//register middleware
app.use(bodyParser.json(), cors())
app.listen(port, () = > console.log(`server is up and running at ${port}`))

// Adding Type Definitions
const typeDefinition = ` type Query { greeting: String }`

// Adding resolver
const resolverObject = {
    Query: {
        greeting: () = > 'Hello GraphQL From TutorialsPoint !! '}}const {makeExecutableSchema} = require('graphql-tools')
const schema = makeExecutableSchema({typeDefs:typeDefinition, resolvers:resolverObject})

const {graphqlExpress, graphiqlExpress} = require('apollo-server-express')

//create routes for graphql and graphiql
app.use('/graphql',graphqlExpress({schema}))
app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))
Copy the code

Step 6: Start the application

Execute server.js with node.js as follows: C:\Users\Admin\hello-world-server> Node server.js

Step 7: Test the GraphQL API

Open a browser and type http://localhost:9000/graphiql. In the query TAB of GraphiQL, enter the following:

{
  greeting
}
Copy the code

The response from the server is as follows:

{ "data": { "greeting": "Hello GraphQL From TutorialsPoint !!" }}Copy the code

As shown below:** Note: ** Be sure to use Apollo Server version 1.0.