A minimal Spring Data REST example

Last modified: July 1, 2021

What do you need to complete this tutorial?

  • Maven/Gradle
  • Java 17

Go to the Spring Initializr website to create a new Spring project

Spring Initializer

Create a new Book class

@Entity
public class Book {

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

    private String title;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Create a Book repository

@RepositoryRestResource(collectionResourceRel = "books", path = "books")
public interface BookRepository extends PagingAndSortingRepository<Book, Long> {
    List<Book> findByTitle(@Param("title") String title);
}

Start the application and add a new book via curl

curl -i --request POST --header "Content-Type:application/json" --data '{"title" : "Moby Dick"}' http://localhost:8080/books

Open the app in a browser to see your created book: http://localhost:8080/books

Further reading

Learn more about SDR: