min read

Quickly create REST API for your entities in Spring

You want to quickly expose any of your Spring models as REST APIs without bloating the code just to support basic CRUD opperations on it? Great

spring.io

Hint: According to https://thorben-janssen.com/dont-expose-entities-in-api/ it´s a bad practice to have no separation between your DAO´s and DTO´s, however if you are in full control of your backend and clients you do it without causing problems and safe a lot of time!

First of all we need to add the** "org.springframework.boot:spring-boot-starter-data-rest"** dependency to our build.gradle. This will provide us access to the @RepositoryRestResource implementation.

.
.
.
dependencies {
  implementation "org.springframework.boot:spring-boot-starter:${springVersion}"
  implementation "org.springframework.boot:spring-boot-starter-web:${springVersion}"
  implementation "org.springframework.boot:spring-boot-starter-data-rest:${springVersion}"
  }

Next we define our entity. It´s a simple translation object to store translations of English / German to a related key

@Entity
@Table(name = "translation")
public class Translation {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @CreationTimestamp
    @Column(name = "insertTimestamp")
    private LocalDateTime createdAt;

    @UpdateTimestamp
    @Column(name = "updateTimestamp")
    private LocalDateTime updatedAt;

    @Column(name = "identifier")
    private String key;

    @Column(name = "en")
    private String en;
    
    @Column(name = "de")
    private String de;
    
}

We as well define our TranslationRepository which extends JpaRepository that is giving us some standard CRUD operations out of the box, as well as paging functionality.

We now annotate our TranslationRepository with the @RepositoryRestResource annotation and declare a path our endpoint will be exposed at.

@RepositoryRestResource(path = "/translation")
public interface TranslationRepository extends JpaRepository<Translation, Long> {

}

When you run the application you should now have an REST endpoint eachable under http://localhost:8080/translation (depending on the port you´ve set) that is supporting create, read, update and delete operations, as well as pagination and sorting out of the box.