Building a Neo4j-Powered API with Node.js and Express

Graph databases are becoming increasingly popular for applications that deal with highly interconnected data. Neo4j, a leading graph database management system, offers powerful capabilities to manage and query graph data efficiently. In this tutorial, we'll walk through the steps to set up a Node.js server with Express and Neo4j, enabling you to fetch graph data from a Neo4j database.

Prerequisites

Before we begin, ensure you have the following installed:

  • Node.js and npm (Node Package Manager)
  • Neo4j Database
  • Basic knowledge of JavaScript and Node.js

Step 1: Setting Up the Project

First, let's set up a new Node.js project and install necessary dependencies:

mkdir neo4j-express-api
cd neo4j-express-api
npm init -y
npm install express neo4j-driver cors

Step 2: Connecting to Neo4j

Create a server.js file and set up Express along with the Neo4j driver to connect to your Neo4j database:

// server.js

const express = require('express');
const neo4j = require('neo4j-driver');
const cors = require('cors');

const app = express();
const port = 3000;

// Middleware
app.use(cors());
app.use(express.json());

// Neo4j Driver
const driver = neo4j.driver(
  'bolt://localhost:7687',
  neo4j.auth.basic('neo4j', 'Password123') // Replace with your Neo4j credentials
);
const session = driver.session();

// Endpoint to get graph data
app.get('/graph', async (req, res) => {
  try {
    const result = await session.run(
      'MATCH (n)-[r]->(m) RETURN n, r, m'
    );

    const records = result.records.map(record => ({
      n: record.get('n').properties,
      m: record.get('m').properties,
      r: record.get('r').type,
    }));

    res.json(records);
  } catch (error) {
    console.error('Error fetching data from Neo4j:', error);
    res.status(500).send('Internal Server Error');
  }
});

// Start server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

// Gracefully close the Neo4j session and driver on exit
process.on('exit', () => {
  session.close();
  driver.close();
});

Step 3: Understanding the Code

  • Express Setup: Initializes an Express application and sets up middleware like cors for handling Cross-Origin Resource Sharing (CORS) and express.json() for parsing JSON requests.

  • Neo4j Driver: Configures a connection to your Neo4j database using the neo4j-driver package. Replace 'bolt://localhost:7687' with your Neo4j server URI and 'neo4j' with your Neo4j username, and 'Password123' with your password.

  • API Endpoint (/graph): Defines a GET endpoint that executes a Cypher query to retrieve graph data from Neo4j. It maps the retrieved data into a JSON response format and handles errors gracefully.

Step 4: Running the Server

Run the server using Node.js:

node server.js

Ensure your Neo4j database is running and accessible.

Step 5: Testing the Endpoint

Open your browser or use tools like Postman to send a GET request to http://localhost:3000/graph. You should receive JSON data representing the nodes, relationships, and properties retrieved from your Neo4j database.

Conclusion

In this tutorial, we've demonstrated how to build a basic Node.js server using Express and connect it to a Neo4j graph database. This setup provides a foundational structure for creating APIs that interact with graph data, facilitating powerful queries and applications.

Expand upon this foundation by adding more endpoints, implementing additional functionality, and exploring Neo4j's capabilities further. Stay tuned for more tutorials and insights on leveraging Neo4j for scalable and efficient data management in your applications.

For more information and detailed documentation, visit Neo4j Documentation.

Happy coding with graphs!


Author: Dale Lewis Role: Co-Founder CEO

Profile Picture