Skip to content

Accessing Neo4j Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.

Notifications You must be signed in to change notification settings

talhaocakci/gs-accessing-neo4j-data-rest

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tags projects
spring-data
neo4j
rest
hateoas
spring-data-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’ll build

You’ll build a Spring application that let’s you create and retrieve Person objects stored in a Neo4j NoSQL database using Spring Data REST. Spring Data REST takes the features of Spring HATEOAS and Spring Data Neo4j and combines them together automatically.

Note
Spring Data REST also supports Spring Data JPA, Spring Data Gemfire and Spring Data MongoDB as backend data stores, but those are not part of this guide.

Create a domain object

Create a new domain object to present a person.

src/main/java/hello/Person.java

link:complete/src/main/java/hello/Person.java[role=include]

The Person has a first name and a last name. There is also an id object that is configured to be automatically generated so you don’t have to deal with that.

Create a Person repository

Next you need to create a simple repository.

src/main/java/hello/PersonRepository.java

link:complete/src/main/java/hello/PersonRepository.java[role=include]

This repository is an interface and will allow you to perform various operations involving Person objects. It gets these operations by extending the PagingAndSortingRepositry interface defined in Spring Data Commons.

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

Note
@RepositoryRestResource is not required for a repository to be exported. It is only used to change the export details, such as using /people instead of the default value of /persons.

Make the application executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.

src/main/java/hello/Application.java

link:complete/src/main/java/hello/Application.java[role=include]

The main() method defers to the SpringApplication helper class, providing Application.class as an argument to its run() method. This tells Spring to read the annotation metadata from Application and to manage it as a component in the Spring application context.

The @EnableNeo4jRepositories annotation activates Spring Data Neo4j. Spring Data Neo4j will create a concrete implementation of the PersonRepository and configure it to talk to an embedded Neo4j database using the Cypher query language. Currently you have to provide the mandatory base-package of your entities via a setBasePackage("hello") method call in the configuration constructor.

Spring Data REST is a Spring MVC application. The @Import(RepositoryRestMvcConfiguration.class) annotation imports a collection of Spring MVC controllers, JSON converters, and other beans needed to provide a RESTful front end. These components link up to the Spring Data Neo4j backend.

The @EnableAutoConfiguration annotation switches on reasonable default behaviors based on the content of your classpath. For example, because the application depends on the embeddable version of Tomcat (tomcat-embed-core.jar), a Tomcat server is set up and configured with reasonable defaults on your behalf. And because the application also depends on Spring MVC (spring-webmvc.jar), a Spring MVC DispatcherServlet is configured and registered for you — no web.xml necessary! Auto-configuration is a powerful, flexible mechanism. See the API documentation for further details.

Logging output is displayed. The service should be up and running within a few seconds.

Test the application

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 curl.

First you want to see the top level service.

$ curl http://localhost:8080
{
  "_links" : {
    "people" : {
      "href" : "http://localhost:8080/people{?page,size,sort}",
      "templated" : true
    }
  }
}

Here you get a first glimpse of what this server has to offer. There is a people link located at http://localhost:8080/people. It has some options such as ?page, ?size, and ?sort.

Note
Spring Data REST uses the HAL format for JSON output. It is flexible and offers a convenient way to supply links adjacent to the data that is served.
$ curl http://localhost:8080/people
{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people{?page,size,sort}",
      "templated" : true
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
}

There are currently no elements and hence no pages. Time to create a new Person!

$ 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

Note
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 on RepositoryRestConfiguration.setReturnBodyOnCreate(…) and setReturnBodyOnCreate(…) which you can use to configure the framework to immediately return the representation of the resource just created.

From this you can query against for all people:

$ curl http://localhost:8080/people
{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people{?page,size,sort}",
      "templated" : true
    }
  },
  "_embedded" : {
    "people" : [ {
      "firstName" : "Frodo",
      "lastName" : "Baggins",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/0"
        }
      }
    } ]
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

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

You can query directly for the individual record:

$ curl http://localhost:8080/people/0
{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people/0"
    }
  }
}
Note
This might appear to be purely web based, but behind the scenes, there is an embedded Neo4j graph database. In production, you would probably connect to a stand alone Neo4j server.

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 will render additional links to help navigate to connected records.

You can also issue PUT, PATCH, and DELETE REST calls to either replace, update, or delete existing records.

$ 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"
    }
  }
}
Note
PUT replaces an entire record. Fields not supplied will be replaced with null. PATCH can be used to update a subset of items.

You can delete records:

$ curl -X DELETE http://localhost:8080/people/0
$ curl http://localhost:8080/people
{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people{?page,size,sort}",
      "templated" : true
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
}

Summary

Congratulations! You’ve just developed an application with a hypermedia-based RESTful front end and a Neo4j-based back end.

About

Accessing Neo4j Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 83.8%
  • Shell 16.2%