Getting started

This tutorial walks you through creating a new project with the Neo4j GraphQL Library.

If you are not familiar with Neo4j and GraphQL, you can alternatively take the course Introduction to Neo4j & GraphQL in GraphAcademy to learn the fundamentals, how to use the Neo4j GraphQL Toolbox and the Neo4j GraphQL Library to create GraphQL APIs backed by a Neo4j graph database.

This tutorial shows you how to:

  • Install the Neo4j GraphQL Library and its dependencies.

  • Set type definitions that represent the structure of your graph database.

  • Start an instance of the library to generate a GraphQL schema.

  • Run an instance of a server to execute queries and mutations against your schema.

The tutorial assumes familiarity with command line and JavaScript, and also that you have a recent version of Node.js installed. The examples use the default npm package manager, but you can use another one of choice.

Create a new project

  1. Create a new directory and cd into it:

    mkdir neo4j-graphql-example
    cd neo4j-graphql-example
  2. Create a new Node.js project (with ESM modules enabled by using the es6 option):

    npm init es6 --yes
  3. Create an empty index.js file which will contain all of the code for this tutorial:

    touch index.js

Install dependencies

  1. Install the Neo4j GraphQL Library and its dependencies:

    1. @neo4j/graphql: the official Neo4j GraphQL Library package. It takes your GraphQL type definitions and generates a schema backed by a Neo4j database.

    2. graphql: the package used to generate a schema and execute queries and mutations.

    3. neo4j-driver: the official Neo4j Driver package for JavaScript, of which an instance must be passed into the Neo4j GraphQL Library.

  2. Install a GraphQL server package to host your schema and allow the execution of queries and mutations against it.

    1. The @apollo/server is the default package for Apollo Server:

      npm install @neo4j/graphql graphql neo4j-driver @apollo/server
  3. Set up a Neo4j database. Make sure it fulfills the requirements, including the necessary plugins.

Set GraphQL type definitions

The Neo4j GraphQL Library is primarily driven by type definitions which map to the nodes and relationships in your Neo4j database. To get started, use a simple example with two node types, one with label "Actor" and the other "Movie":

  1. Open the previously created index.js in your editor of choice and write your type definitions. Add all of the necessary package imports:

    import { ApolloServer } from '@apollo/server';
    import { startStandaloneServer } from '@apollo/server/standalone';
    import { Neo4jGraphQL } from "@neo4j/graphql";
    import neo4j from "neo4j-driver";
    
    const typeDefs = `#graphql
        type Movie {
            title: String
            actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN)
        }
    
        type Actor {
            name: String
            movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
        }
    `;

    Note that these type definitions only define the node labels "Actor" and "Movie", and a relationship "ACTED_IN" between the two. When the schema is generated, you can then execute queries for actors and movies to read data from the database.

  2. Alternatively, you can also automatically generate type definitions from an existing database by introspecting the schema.

Create an instance of Neo4jGraphQL

To create an instance of the Neo4j GraphQL Library, you need a Neo4j driver to connect to your database.

Using AuraDB

  1. For an AuraDB database, create an instance.

  2. Make sure to save the generated password and the connection URI provided after the instance is ready and looking similar to this:

    neo4j aura dashboard

Using a Neo4j database

For a database located at the default "neo4j://localhost:7687" (see more about port configuration), with the username "username" and the password "password", add the following to the bottom of your index.js file:

const driver = neo4j.driver(
    "neo4j://localhost:7687",
    neo4j.auth.basic("username", "password")
);

const neoSchema = new Neo4jGraphQL({ typeDefs, driver });

Create an instance of ApolloServer

To create an Apollo Server instance using the generated schema, in which you can execute queries against it, add the following to the bottom of index.js:

const server = new ApolloServer({
    schema: await neoSchema.getSchema(),
});

const { url } = await startStandaloneServer(server, {
    listen: { port: 4000 },
});

console.log(`🚀 Server ready at ${url}`);

Start the server

Make sure that your index.js file looks like this:

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { Neo4jGraphQL } from "@neo4j/graphql";
import neo4j from "neo4j-driver";

const typeDefs = `#graphql
    type Movie {
        title: String
        actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN)
    }

    type Actor {
        name: String
        movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
    }
`;

const driver = neo4j.driver(
    "neo4j://localhost:7687",
    neo4j.auth.basic("username", "password")
);

const neoSchema = new Neo4jGraphQL({ typeDefs, driver });

const server = new ApolloServer({
    schema: await neoSchema.getSchema(),
});

const { url } = await startStandaloneServer(server, {
    context: async ({ req }) => ({ req }),
    listen: { port: 4000 },
});

console.log(`🚀 Server ready at ${url}`);

You are ready to start up your GraphQL server. Back in the command line, run:

node index.js

If successful, you should see the following output:

🚀 Server ready at http://localhost:4000/

The address http://localhost:4000/ is the URL where the Apollo Server starts.

Create nodes in the database

  1. Visit http://localhost:4000/ in your web browser. You should get redirected to the Apollo Sandbox:

    apollo server landing page
  2. At the moment your database is empty. To start adding data, copy and paste the following mutation to the Operation panel to create a movie and an actor in that movie:

    mutation {
      createMovies(
        input: [
          {
            title: "Forrest Gump"
            actors: { create: [{ node: { name: "Tom Hanks" } }] }
          }
        ]
      ) {
        movies {
          title
          actors {
            name
          }
        }
      }
    }
  3. Click the "Run" button on the top right. You should get the following confirmation that the data has been created in the database in the Response panel:

    {
      "data": {
        "createMovies": {
          "movies": [
            {
              "title": "Forrest Gump",
              "actors": [
                {
                  "name": "Tom Hanks"
                }
              ]
            }
          ]
        }
      }
    }
  4. Query the data which you just added. Copy and paste the following query to the Operations panel:

    query {
      movies {
        title
        actors {
          name
        }
      }
    }

    Since you only created one "Movie" node and one "Actor", the Response panel shows the following:

    {
      "data": {
        "movies": [
          {
            "title": "Forrest Gump",
            "actors": [
              {
                "name": "Tom Hanks"
              }
            ]
          }
        ]
      }
    }

Conclusion

This concludes the tutorial. By now, you should have a GraphQL API connected to a Neo4j database, to which you added two nodes.

To learn more, keep reading the documentation about Queries and aggregations or alternatively learn how to use the Neo4j GraphQL Toolbox. For more advanced database settings, refer to the Driver configuration page.