Spring-Data REST for API’s

In this blog post we went through the process of creating a CRUD REST API with Spring MVC and Spring Data. This is not the only way we can create these API’s. Today we are going to look at another way to create the same API as we created in that blog post.

For this we need a project with the following dependencies:

  • h2 (in memory database)
  • lombok (generate boilerplate code)
  • spring-boot-starter-data-rest
  • spring-boot-starter-data-jpa (create repositories)
  • spring-data-rest-hal-browser (to quickly use our API in the browser)

First we recreate the Product class we created in this blog post.

@Data
@Entity
public class Product{

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    protected Product() {}
}

To interact with the database we need a repository. Last time we did this by extending the CrudRepository interface. Which we then used in the REST controller we created.

This time we extend PagingAndSortingRepository. We could have done that in the last example, but we did not. The new capabilities this gives us are:

  • paging (showing x number of items on a page)
  • sorting (sort the collection by which column and ascending or descending)

This gives use the following code:

@RepositoryRestResource
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {

}

@RepositoryRestResource REST endpoints for all our CRUD methods and enables pagination and sorting on them.

Now let’s run the application and go to localhost:8080 where we will be redirected too. This is a page created by spring-data-rest-hal-browser. On the left side it looks like this.

rest-browsable-api

To use the paging and sorting we write an URL like this: http://localhost:8080/products?page=0&size=2&sort=name,asc

For looking at 1 item or modifying it go to an URL like: http://localhost:8080/products/1

For removing the product we use DELETE. For updating the product we use PUT. For looking at the product we use GET, but there is a green button for that request.

This way of creating a REST API is less code, but when we also need to use the repository for something else then REST calls we can’t use this method of creating REST API’s.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s