[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 HelloWorld and use GraphiQL to access it.
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 to the same folder from the terminal. Add package.json and name the package. Since this package is for internal use only, we can declare it as 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 can help Express efficiently process HTTP Post requests. cors is another middleware package that handles cross-source resource sharing.
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 the 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 commands 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 installed successfully 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 pattern
The GraphQL schema defines what kind of objects can be obtained from the service and what fields it has. You can use GraphQL schema definition language to define the schema. Now, add the following code snippets to the server.js
// Adding Type Definitions const typeDefinition = ` type Query { greeting: String }`
Here, the query contains the greeting attribute string value
Step 4: Create a parser
The first step in creating a parser is to add some code to handle requests for the greeting field. This is specified parser The structure of the parser function must match the pattern. Add the following code snippets in the server.js
// Adding resolver const resolverObject = { Query: { greeting: () => 'Hello GraphQL From TutorialsPoint !!' } }
The second step is to use makeExecutableSchema to bind the mode and parser. This function is predefined in the graphql-tools module. Add the following code snippets in 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 snippets to the server.js
const {graphqlExpress, graphiqlExpress} = require('apollo-server-express')
//create routes for graphql and graphiql
app.use('/graphql',graphqlExpress({schema}))
app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))
graphqlExpress function helps to register routes
http://localhost:9000/graphql. ReactJS applications can use this endpoint to query data. Similarly, the graphqliExpress function helps to register the route http://localhost:9000/graphiql. This will be used by 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: Launch 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 below:
Note: Please make sure to use Apollo Server version 1.0.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。