Accessing Neo4j Data with REST

This guide walks you through the process of creating an application that accesses graph-based data through a hypermedia-based RESTful front end.

What You Will Build

You will build a Spring application that lets you create and retrieve Person objects that are stored in a Neo4j NoSQL database by using Spring Data REST. Spring Data REST takes the features of Spring HATEOAS and Spring Data Neo4j and automatically combines them together.

  • Java 17 or later

  • Gradle 7.5+ or Maven 3.5+

  • You can also import the code straight into your IDE:

  • Spring Tool Suite (STS)

  • IntelliJ IDEA

  • VSCode

  • Like most Spring Getting Started guides , you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

    To start from scratch , move on to [scratch] .

    To skip the basics , do the following:

  • Download and unzip the source repository for this guide, or clone it using Git : git clone https://github.com/spring-guides/gs-accessing-neo4j-data-rest.git

  • cd into gs-accessing-neo4j-data-rest/initial

  • Jump ahead to Permissions to Access Neo4j .

  • When you finish , you can check your results against the code in gs-accessing-neo4j-data-rest/complete .

    Starting Neo4j.
    Started neo4j (pid 96416). By default, it is available at http://localhost:7474/
    There may be a short delay until the server is ready.
    See /usr/local/Cellar/neo4j/3.0.6/libexec/logs/neo4j.log for current status.

    You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

    To manually initialize the project:

  • Navigate to https://start.spring.io . This service pulls in all the dependencies you need for an application and does most of the setup for you.

  • Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  • Click Dependencies and select Rest Repositories and Spring Data Neo4j .

  • Click Generate .

  • Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

  • package com.example.accessingneo4jdatarest;
    import org.springframework.data.neo4j.core.schema.Id;
    import org.springframework.data.neo4j.core.schema.Node;
    import org.springframework.data.neo4j.core.schema.GeneratedValue;
    @Node
    public class Person {
      @Id @GeneratedValue private Long id;
      private String firstName;
      private String lastName;
      public String getFirstName() {
        return firstName;
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      public String getLastName() {
        return lastName;
      public void setLastName(String lastName) {
        this.lastName = lastName;
    import java.util.List;
    import org.springframework.data.repository.PagingAndSortingRepository;
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.data.repository.query.Param;
    import org.springframework.data.rest.core.annotation.RepositoryRestResource;
    @RepositoryRestResource(collectionResourceRel = "people", path = "people")
    public interface PersonRepository extends PagingAndSortingRepository<Person, Long>, CrudRepository<Person, Long> {
      List<Person> findByLastName(@Param("name") String name);
       

    This repository is an interface and lets you perform various operations that involve Person objects. It gets these operations by extending the PagingAndSortingRepositry interface defined in Spring Data Commons.

    At runtime, Spring Data REST automatically creates an implementation of this interface. Then it uses the @RepositoryRestResource annotation to direct Spring MVC to create RESTful endpoints at /people.

    The Spring Initializr creates an application class when you use it to create a project. You can find that in src/main/java/com/example/accessingneo4jdatarest/Application.java. Note that the Spring Initializr concatenates (and properly changes the case of) the package name and adds it to Application to create the application case name. In this case, we get AccessingNeo4jDataRestApplication, as the following listing shows:

    package com.example.accessingneo4jdatarest;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    @EnableTransactionManagement
    @EnableNeo4jRepositories
    @SpringBootApplication
    public class AccessingNeo4jDataRestApplication {
      public static void main(String[] args) {
        SpringApplication.run(AccessingNeo4jDataRestApplication.class, args);
        
  • @Configuration: Tags the class as a source of bean definitions for the application context.

  • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.

  • @ComponentScan: Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.

  • The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.

    The @EnableNeo4jRepositories annotation activates Spring Data Neo4j. Spring Data Neo4j creates a concrete implementation of the PersonRepository and configures it to talk to an embedded Neo4j database by using the Cypher query language.

    Build an executable JAR

    You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

    If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:

    Now that the application is running, you can test it. You can use any REST client you wish. The following examples use the *nix tool called curl.

    First, you want to see the top level service. The following example (with output) shows how to do so:

    $ curl -i -X POST -H "Content-Type:application/json" -d '{  "firstName" : "Frodo",  "lastName" : "Baggins" }' http://localhost:8080/people
    HTTP/1.1 201 Created
    Server: Apache-Coyote/1.1
    Location: http://localhost:8080/people/0
    Content-Length: 0
    Date: Wed, 26 Feb 2014 20:26:55 GMT
  • -i ensures you can see the response message including the headers. The URI of the newly created Person is shown

  • -X POST signals this a POST used to create a new entry

  • -H "Content-Type:application/json" sets the content type so the application knows the payload contains a JSON object

  • -d '{ "firstName" : "Frodo", "lastName" : "Baggins" }' is the data being sent

  • Notice how the previous POST operation includes a Location header. This contains the URI of the newly created resource. Spring Data REST also has two methods (RepositoryRestConfiguration.setReturnBodyOnCreate(…) and setReturnBodyOnCreate(…)) that you can use to configure the framework to immediately return the representation of the resource that was just created.

    The people object contains a list with Frodo. Notice how it includes a self link. Spring Data REST also uses the Evo Inflector library to pluralize the name of the entity for groupings.

    You can query directly for the individual record by running the following command (shown with its output):

    In this guide, there is only one domain object. With a more complex system, where domain objects are related to each other, Spring Data REST renders additional links to help navigate to connected records.

    You can find all the custom queries by running the following command (shown with its output):

    "_links" : { "findByLastName" : { "href" : "http://localhost:8080/people/search/findByLastName{?name}", "templated" : true

    You can see the URL for the query, including the HTTP query parameter: name. Note that this matches the @Param("name") annotation embedded in the interface.

    To use the findByLastName query, run the following command (shown with its output):

    "_links" : { "self" : { "href" : "http://localhost:8080/people/search/findByLastName?name=Baggins"

    Because you defined it to return List<Person> in the code, it returns all of the results. If you had defined it to return only Person, it would pick one of the Person objects to return. Since this can be unpredictable, you probably do not want to do that for queries that can return multiple entries.

    You can also issue PUT, PATCH, and DELETE REST calls to either replace, update, or delete existing records. The following example (shown with its output) shows a PUT call:

    $ curl -X PUT -H "Content-Type:application/json" -d '{ "firstName": "Bilbo", "lastName": "Baggins" }' http://localhost:8080/people/0
    $ curl http://localhost:8080/people/0
      "firstName" : "Bilbo",
      "lastName" : "Baggins",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/0"
          
    $ curl -X PATCH -H "Content-Type:application/json" -d '{ "firstName": "Bilbo Jr." }' http://localhost:8080/people/0
    $ curl http://localhost:8080/people/0
      "firstName" : "Bilbo Jr.",
      "lastName" : "Baggins",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/0"
        
  • Accessing MongoDB Data with REST

  • Accessing data with MySQL

  • Accessing Gemfire Data with REST

  • Consuming a RESTful Web Service

  • Consuming a RESTful Web Service with AngularJS

  • Consuming a RESTful Web Service with jQuery

  • Consuming a RESTful Web Service with rest.js

  • Securing a Web Application

  • Building REST services with Spring

  • Building an Application with Spring Boot

  • Creating API Documentation with Restdocs

  • Enabling Cross Origin Requests for a RESTful Web Service

  • Building a Hypermedia-Driven RESTful Web Service

  • Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.