How to generate REST services automatically for data repositories using Spring Boot?

There is no need to write REST service controller classes yourself if you just want to expose your databases as REST services.

Spring Boot can automatically convert your database repositories into REST services. In addition to it, it returns the response in HAL format which allows you to navigate to the individual records.

Let’s see how to do this.

STEP 1:

Generate a spring boot project template using Spring Boot Initializr (https://start.spring.io/) :

Add the three dependencies highlighted:

Spring Data REST for generating the REST services

Spring Data JPA for creating the entities and repositories

H2 Database for in memory H2 database to be used for this demo.

I didn’t include any configuration detail for the database for this demo. Not even the database name!

Spring Boot automatically created a database named testdb looking at the H2 dependency in pom.xml and an empty application.properties file!

You Spring Boot!! No wonder people call you opinionated!

STEP 2:

Let’s create an entity class named Customer with two fields name and city.

package com.springdatarest.demo;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Customer {

	@Id
	private Long id;

	private String name;

	private String city;

	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}

	/**
	 * @param city the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

}

Spring boot automatically creates a database named Customer in H2 database.

STEP 3:

Let’s create a CRUD repository to do CRUD operations on the above database.

Just create an interface and implement CRUD repository provided by Spring Data.

In addition , add the annotation @RepositoryRestResource on top of the interface.

This will generate the required rest services:

package com.springdatarest.demo;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface CustomerRepository extends CrudRepository<Customer, Long> {

}

That’s it!

So simple.

Now start the application and navigate to localhost:8080 .

You can see the below response:

{
  "_links" : {
    "customers" : {
      "href" : "http://localhost:8080/customers"
    },
    "profile" : {
      "href" : "http://localhost:8080/profile"
    }
  }
}

customers refer to the database and profile represents metadata about the database.

Spring Boot automatically generates a collection resource named ‘customers’ . It takes the entity class , uncapitalizes the first letter and adds ‘s’ at the end of the entity (pluralizes it).

So in your local you can see the collection resource generated at http://localhost:8080/customers.

Collection resources support two HTTP methods : GET and POST.

So you can use it to get all records in the database and add a new record.

Let’s add a new customer to our DB:

As you see , I have used POST HTTP method in my REST client tool (POSTMAN) . The item got added and the response provides a link to navigate to the newly created record.

I added one more customer (id:2,name:”Vijay”,city:”Chennai”)

Now let’s retrieve all the records using GET method.

It gives me the below response:

{
  "_embedded": {
    "customers": [
      {
        "name": "Sowmiya",
        "city": "Mumbai",
        "_links": {
          "self": {
            "href": "http://localhost:8080/customers/1"
          },
          "customer": {
            "href": "http://localhost:8080/customers/1"
          }
        }
      },
      {
        "name": "Vijay",
        "city": "Chennai",
        "_links": {
          "self": {
            "href": "http://localhost:8080/customers/2"
          },
          "customer": {
            "href": "http://localhost:8080/customers/2"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/customers"
    },
    "profile": {
      "href": "http://localhost:8080/profile/customers"
    }
  }
}

The response returned is in HAL format obeying HATEOS standards.

Now , lets do the other operations , updating a record and deleting a record.

For this you need to navigate to the item level.

Let me update the city against the name ‘Sowmiya’ as ‘Kolkata’ :

As you can see , I am using ‘PUT’ operation and using the URL http://localhost:8080/customer/1 where 1 is the id of the customer.

Now let me delete:

I am using DELETE HTTP method and URL is the same as that of ‘PUT’ method.

The item is deleted and it returns 204 error response.

Now if I query the list of customers it will return empty list for the customers.

We have done all the CRUD operations using REST services without adding a single line of code for creating REST services!

You can further do customizations too.

Please refer below link for more advanced topics:

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#reference

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s