Skip to main content

One post tagged with "Spring Data REST"

View All Tags

Effortless REST API Development with Spring Data REST and PostgreSQL

· 5 min read
Huseyin BABAL
Software Developer

Introduction

In today’s fast-paced software development world, building efficient and flexible REST APIs is essential. Spring Data REST simplifies this process significantly by allowing developers to quickly expose repository-based data models as RESTful services with minimal configuration. In this article, we’ll explore how easy it is to create a REST API using Spring Data REST and PostgreSQL, allowing you to focus on your business logic instead of boilerplate code.

Why Spring Data REST?

Spring Data REST is built on top of Spring Data repositories and automatically exposes them as RESTful endpoints. Instead of manually writing controller logic to handle CRUD operations, Spring Data REST provides out-of-the-box support for:

  • Automatic generation of REST endpoints.
  • Hypermedia as the Engine of Application State (HATEOAS) support.
  • Pagination, sorting, and filtering.
  • Integration with Spring Data repositories for database interaction.

By leveraging Spring Data REST, you can rapidly create a fully functional REST API with minimal code, and focus on business rules, rather than implementing boilerplate REST operations.

Persistence Layer

In this article, we will be using PostgreSQL as our database. You can maintain your database in any database management system. For a convenient deployment option, consider cloud-based solutions like Rapidapp, which offers managed PostgreSQL databases, simplifying setup and maintenance.

tip

Create a free database in Rapidapp in seconds here

Step-by-Step Guide to Creating Project

Project Initialization and Dependencies

We will be using Spring Boot and PostgreSQL to build a todo application. You can initialize a spring boot project by using Spring Boot CLI. Once installed, you can use following command to initialize a project with required dependencies.

spring init \
--dependencies=web,data-jpa,data-rest,postgresql \
--type=maven-project \
--javaVersion=21 \
spring-data-rest-example

Line 2: web for implementing REST endpoints, data-jpa for database persistence, data-rest for automatically expose your data as fully qualified REST endpoints, and postgresql for PostgreSQL driver.

Line 3: --type=maven-project for creating a Maven project.

Line 4: --javaVersion=21 we will use Java 21 to compile and run project.

Now that we initialized the project, go to the folder spring-data-rest-example and open it with your favourite IDE.

Implementing Entity and Repository

We have only one entity here, Product, which will be used to store our products. Let's create a new entity called Product as follows.

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
class Product {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private BigDecimal price;
}

In order to manage Product entity in database, we will use following repository interface.


interface ProductRepository extends CrudRepository<Product, Integer>{}

Application Configuration

This section contains application level configurations such as the application name, datasource, and jpa as shown below:

application.yaml
spring:
application:
name: spring-data-rest-example
datasource:
url: <connection-string-from-rapidapp|or your own managed postgres url>
username: <username>
password: <password>
jpa:
database-platform: org.hibernate.dialect.PostgreSQLDialect
hibernate:
ddl-auto: update

Line 5: Connection URL for the PostgreSQL database. You can obtain this from Rapidapp or your own managed PostgreSQL service. It should have a format like jdbc:postgresql://<host>:<port>/<database>?sslmode=require.

That's it! You have successfully created a Spring Data REST API with PostgreSQL as the database. One second, we don't have controllers,services, etc... Yes, Spring Data REST will take care of all these for you. It simply analyzes your entity with the help of @RepositoryRestResource annotation you put in repository interface above and exposes it as REST endpoints.

You can now run the application as follows;

mvn spring-boot:run

If everything goes well, you can verify app by visiting http://localhost:8080/products in your browser.

{
"_embedded" : {
"products" : [ ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/products"
},
"profile" : {
"href" : "http://localhost:8080/profile/products"
}
}
}

Rest Endpoints

Once the repository is created, Spring Data REST will automatically expose CRUD endpoints for the Product entity. These include:

  • GET /products: List all products.
  • GET /products/{id}: Retrieve a specific product.
  • POST /products: Create a new product.
  • PUT /products/{id}: Update an existing product.
  • DELETE /products/{id}: Delete a product.

There’s no need to write additional controller classes; the endpoints are provided automatically based on your repository definition.

Customizing the REST Behavior

Although Spring Data REST provides default behavior, you can customize the endpoints to suit your needs. For instance, you can modify the base path, limit the exposed operations, or add custom validation.

  • Customizing base paths: You can change the default endpoint path by adding the @RepositoryRestResource annotation to the repository:
@RepositoryRestResource(path = "product")
public interface ProductRepository extends JpaRepository<Product, Long> {
}

Now, the base URL for product-related endpoints will be /product instead of /products.

  • Exposing specific fields: You can expose or hide fields by using Spring Data REST’s projection feature:
@Projection(name = "customProduct", types = { Product.class })
interface CustomProduct {
String getTitle();
}

This will limit the fields exposed in the API response for products and show only title field.

Demo

Create Product

curl -XPOST -H "Content-Type: application/json" \
http://localhost:8080/products -d \
'{"title": "Laptop", "price": 1000}'

List Products

curl -XGET http://localhost:8080/products

Update Product

curl -XPUT -H "Content-Type: application/json" \
http://localhost:8080/products/1 -d \
'{"title": "Laptop", "price": 1200}'

Delete Product

curl -XDELETE http://localhost:8080/products/1

Get Product

curl -XGET http://localhost:8080/products/1

Conclusion

Spring Data REST, combined with PostgreSQL, provides a fast and simple way to create fully functional REST APIs without the need for writing repetitive boilerplate code. With automatic CRUD operations, pagination, and HATEOAS support, you can focus on the unique aspects of your application and leave the rest to Spring Data REST. By adopting this approach, you can significantly reduce development time and quickly deliver high-quality APIs.

tip

You can find the complete source code for this project on GitHub.