As its name suggests, GraphQL is a query language for APIs. It can be used to define data with fields and types, and then provide functions associated with each of them. Compared to REST (Representational State Transfer), which fetches one resource at a time identified by a URL, each GraphQL request can return multiple resources identified by fields and types.
Environment
- macOS Catalina, Version 10.15.7.
- Node.js, v14.17.5.
Hello, World!
The official GraphQL tutorial gives a quick example of running GraphQL in a Node.js environment.
-
Create a directory for the project such as
mkdir hello
. -
Create a
package.json
file in thehello
directory.A
package.json
file makes it easy to manage and install a package. For example, it tells the dependencies and versions of a package used by a project.Simply running
npm init -y
would quickly create a file as below.Wrote to /home/test/hello/package.json: { "name": "hello", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
-
Install GraphQL.js in the
hello
directory vianpm install graphql --save
. -
Writing the code and save it as
hello.js
.var { graphql, 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!'; }, }; // Run the GraphQL query '{ hello }' and print out the response graphql(schema, '{ hello }', root).then((response) => { console.log(response); });
-
Run the code with
node hello.js
and it will show the response:{ data: [Object: null prototype] { hello: 'Hello, World!' } }