How to use GraphQL with Javascript – GraphQL.js tutorial
Khalil Stemmler
GraphQL is first and foremost: a query language. It’s a more flexible and robust way to ask for data. You can use JavaScript to execute GraphQL anywhere. In this short post, we’ll take a look at the underlying JavaScript GraphQL implementation used by many popular GraphQL libraries and frameworks: graphql-js
.
Prerequisites
- You understand what GraphQL is
- You’re familiar with the command line
- You have Node.js (8+) installed
What is GraphQL.js
GraphQL.js is the reference implementation of GraphQL for JavaScript. By reference implementation, we mean that it adheres to the rules declared in the official GraphQL specification.
Other languages have also implemented the GraphQL specification, like Java, .NET, and Go.
Getting started with GraphQL.js
Let’s install GraphQL.js and execute a query with it.
Create a new project
We’ll start by creating a new folder for our project. Run the following command to create a directory and then cd
into it.
mkdir graphql-js
cd graphql-js
Use npm
(or Yarn) to initialize a new Node.js project.
npm init --yes
Installation
To install graphql-js
, run the following command:
npm install --save graphql
This should create a package.json
file and a node_modules
folder. Next, we’ll create the file that we’re going to work within.
Create an index.js file
We’ll write our code in a single file. Create a new index.js
file in the current directory.
touch index.js
Writing a query in GraphQL.js
The following code constructs a schema with the root Query
type containing a hello
field. Then, we create a resolver to resolve the value for the hello
field and run a query by passing in the schema, the query itself, and graph resolvers.
const { graphql, buildSchema } = require('graphql');
// Builds a schema using the GraphQL schema language
const schema = buildSchema(`
type Query {
hello: String
}
`);
// The root of our graph gives us access to resolvers for each type and field
const resolversRoot = {
hello: () => {
return 'Hello world!';
},
};
// Run a simple graphql query '{ hello }' and then print the response
graphql(schema, '{ hello }', resolversRoot).then((response) => {
console.log(JSON.stringify(response.data));
});
Running the query
To run this code, in your console — type the following command:
node index.js
If all goes well, you should see this:
{ "hello": "Hello world!" }
This is how we can use plain JavaScript to write GraphQL queries with GraphQL.js.
Next steps
Serve GraphQL over HTTP with a Server Library
GraphQL.js is the definitive JavaScript GraphQL implementation, but most of us are using GraphQL to build backend APIs. For that to work, we need to serve GraphQL over HTTP.
We covered how GraphQL.js works (under the hood of other GraphQL JavaScript libraries like Apollo Server), but I recommend reading “Using Express with GraphQL – How to create a GraphQL server with Node.js/Express” to learn how to connect GraphQL to a web server.