Spring Boot Data Rest

Posted By : Amit Mishra | 28-Dec-2020

Rest services have been very popular nowadays because it provides an effective way to deal with data and data security. The monolithic web-based applications are now migrating to modern architecture which consists of client and server model which allow you to work on the server-side or client-side effectively.

In order to create a rest API, you need to define a controller, domain, businessLayer, and your service layer so to reduce these efforts Spring has an implementation of SpringDataJPA which is now known by the name of Spring Data Rest which can help you to reduce your most of the code and you can create a rest API within a few seconds. Spring Data Rest allows clients to automatically find functionality revealed by the repositories by taking advantage of hypermedia. It then lets them integrate these resources into hypermedia-based functionality.

 

Features :

1. Using HAL as a media type, it exposes a discoverable REST API for your domain model.
2. Exposes collection, item and association resources representing your model.
3. Supports pagination via navigational links.
4. Allows to dynamically filter collection resources.
5. Exposes dedicated search resources for query methods defined in your repositories.
6. Allows to hook into the handling of REST requests by handling Spring ApplicationEvents.

 

Also Read: Spring Boot Application With Zull API Gateway

 

There are a lot many other feautures to get a complete reference of Spring Data rest please browse through the guide available : here

1. Getting Started.

To get started using Spring Data Rest the best way is to use Spring boot to leverage the feature of auto configuration. The following example will show you how you can get started with your favorite build tools: Maven and Gradle.

Maven


  ...
  <dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-rest</artifactid>
  </dependency>
  ...

Gradle

dependencies {
  ...
  compile("org.springframework.boot:spring-boot-starter-data-rest")
  ...
}

 Great, now when you've these dependencies in your POM, then let's get started by creating a domain. In this example we're taking a simple domain name User.

2. Writing the code. 

Let's create a simple domain with name User.

 

@Entity
@Data
@NoArgsConstructor
public class User {
	@Id @GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	private String firstName;
	private String lastName;

}

Note :- I've used Lombok in this project to leverage the feature of implicit setters getters and other basic domain requirements. You can read more about project Lombok here: https://projectlombok.org/

    2.1 Creating a repository.

 

UserRepository.java

@RepositoryRestResource(collectionResourceRel = "/users", path = "users")
public interface UserRepository extends PagingAndSortingRepository{
	
}

Explanation: Ignoring the annotation everything seems familiar if you've worked on Spring Data JPA and it's going to be very easy if you were working with Spring Data JPA because with Spring Data Rest there is no need to create explicit servlet controllers. 

 

Also Read: Firebase CRUD operation using spring boot

 

We used to annotation this repository with spring's standard @Repository annotation to keep naming conventions in mind. Now we've annotated this repository with @RepositoryRestResource with makes this special. Just to get started with you just need to a parameter path which will be the path from where it will start creating links. In this example, I've typed path="users" meaning every operation related this repository will started from server.context.path + "/users".

The second parameter we have seen is collectionResourceRel which is nothing but the rel value to use when generating links to the collection resource.

3. Testing the Application.

Now, with this much configuration, you're ready to consume your rest services. Let's send the rest to the context path and see what we get.
 

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

The response that you've received is showing the available rest resources that you can browse through and spring has already generated this much feature for you for pagination size and sorting. 

Let's try hitting the link available in href tag

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

The embedded key shows the available data in the database and the links will show the further available links. 

The next example will show you how to create user.

$ curl -i -H "Content-Type:application/json" -d '{"firstName": "Frodo", "lastName": "Baggins", "email": "[email protected]"}' http://localhost:8080/user

Query again for all the available data in the database

$curl http://localhost:8080/users/
{
    "_embedded": {
        "/users": [
            {
                "firstName": "John",
                "lastName": "Doe",
                "email": "[email protected]",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/users/1"
                    },
                    "user": {
                        "href": "http://localhost:8080/users/1"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/users/"
        },
        "profile": {
            "href": "http://localhost:8080/profile/users"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 4,
        "totalPages": 1,
        "number": 0
    }
}

 

It was spring data rest resource a very basic introduction and it has a lot more features by which you can even make more complex operations without writing a lot of code and I hope this article has helped you in anyway.

 

We are a 360-degree software development company that provides cross-platform SaaS app development services to address varied software project requirements. We have an experienced team of Java, PHP, and Python developers who use advanced frameworks, tools, and SDKs to build scalable web and mobile applications with custom features. For more detail, reach us out at [email protected].

About Author

Author Image
Amit Mishra

Amit is a spring web developer. He has good knowledge of Spring Cloud, Spring Boot, Spring MVC, Hibernate, and some template engines like jsp and thymleaf.

Request for Proposal

Name is required

Comment is required

Sending message..