This post walks you through the process of creating a RESTful API Example with Spring Data REST and MySQL.

What you'll need

  • JDK 1.7+
  • Maven 3+
  • MySQL Server 5.6+

Stack

  • Spring Boot
  • Spring Data REST
  • Spring Data JPA
  • MySQL

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── restfulapi
│       │               ├── Application.java
│       │               ├── model
│       │               │   └── Book.java
│       │               └── repository
│       │                   └── BookRepository.java
│       └── resources
│           └── application.properties
└── pom.xml

Project dependencies


Create database

Create a new empty MySQL database named restful_api. Tables will be auto created by Hibernate when the application started

Create domain object


Spring Data Repository

Spring Data JPA and Spring Data Rest will auto create some helper methods and RESTful APIs. For this example, we only need to extend JpaRepository


Application Properties


Run the application


Type mvn clean spring-boot:run on terminal at the project root directory to run

Test the application

Create some new books

curl -i -X POST -H "Content-Type:application/json" -d "{\"title\" : \"Hello Koding\", \"description\": \"Simple coding examples and tutorials\"}" http://localhost:8080/books  
curl -i -X POST -H "Content-Type:application/json" -d "{\"title\" : \"Hello Koding 2\", \"description\": \"Simple coding examples and tutorials 2\"}" http://localhost:8080/books  

Find all books

curl http://localhost:8080/books  

Find book with id=2

curl curl http://localhost:8080/books/2  

Update book id 2

curl -i -X PATCH -H "Content-Type:application/json" -d "{\"title\" : \"Hello Koding 2 updated\"}" http://localhost:8080/books/2  

Replace book id 2

curl -i -X PUT -H "Content-Type:application/json" -d "{\"title\" : \"Hello Koding 2 replaced\"}" http://localhost:8080/books/2  

Delete book id 2

curl -i -X DELETE http://localhost:8080/books/2  

Source code

[email protected]:hellokoding/restfulapi-springboot-springdatarest-mysql.git

https://github.com/hellokoding/restfulapi-springboot-springdatarest-mysql