GraphQL quick start [5] GraphQL example

[note] this article is translated from:
GraphQL - Quick Guide (tutorialspoint.com)

     In this chapter, we will create a simple API that returns a greeting message Hello world and access it using GraphiQL.

Example

     This example is based on NodeJS, Express, and Apollo servers. We will learn to combine all concepts through the following 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 only used internally, we can declare it private.

{
    "name": "hello-world-server",
    "private": true
}

     Install the dependencies of the Express server as follows:
C:\Users\Admin\hello-world-server>npm install express body-parser cors
     Body parser is a middleware package that helps Express process HTTP Post requests effectively. cors is another middleware package that handles cross source resource sharing.
     Create the server.js file in the 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}`))

     To verify that the Express server is up and running, execute the following code in a terminal window:
C:\Users\Admin\hello-world-server>node server.js
     The 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 9000
     If you open a browser and enter http://localhost:9000 , you will see the following screen:

     To stop the server, press Ctrl + 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 version. 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 verify that these dependencies are successfully installed by checking the package.json file we created earlier.
{
    "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"
    }
}

Step 3: define the schema

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

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

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

Step 4: create 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 !!'
    }
}

     The second step is to bind the schema and parser using makeExecutableSchema. 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})

Step 5: define the route to get data from 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'}))

     The graphqlExpress function helps to register routes
http://localhost:9000/graphql . ReactJS applications can use this endpoint to query data. Similarly, the graphqliExpress function helps register routes http://localhost:9000/graphiql . 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'}))

Step 6: start the application

     Use Node.js to execute server.js, as shown below:
C:\Users\Admin\hello-world-server>node server.js

Step 7: test the GraphQL API

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

{
  greeting
}

     The response from the server is as follows:

{
    "data": {
        "greeting": "Hello GraphQL From TutorialsPoint !!"
    }
}

     As shown in the figure below:

**Note: * * Please make sure to use Apollo server version 1.0.

Tags: node.js graphql

Posted on Wed, 29 Sep 2021 15:02:40 -0400 by jamesm87