Table of Contents
Open Table of Contents
Intro
In this article, we will build a RESTful API using Spring boot version 2.7.5 and Java 11.
So, why Java - Spring boot?
Java is an object-oriented programming language that is used for enterprise grade Software and platforms worldwide. It is actively developed and maintained by Oracle but it is open source, meaning, developers worldwide can contribute to its development.
Spring boot on the other hand is a Java and Spring based framework that makes the development of microservices and other software easy to develop and maintain. The easy bit comes from the unncessesary need to create boiler plate code that comes with initializing a Spring-only app. Note that Spring boot is a simplification of Spring.
Project Initialization
Head over to spring initializr, initialize your project by picking Maven, Java (11), non snapshot or M Spring Boot version then give a name for your project. The name of our application will be playground
. In addition, add the following dependencies.
- Spring boot starter data JPA
- Spring boot starter web
- Lombok
- Spring boot starter test
- Derby
Finish by clicking Generate to download a zip file of your initialized project. Unzip your project then open it with your favorite editor.
What are those Dependencies?
-
Spring boot starter data JPA - JPA means Java Persistence API, that is used to persist, control and manipulate Java entities/objects into relational databases.
-
Spring boot starter web - It is used to create a MVC (Model View Controller) type for web based spring applications.
-
Lombok - It is a Java library that aids in creating and processing annotations used within Java applications. For instance, if a class is annotated with @Getter and @Setter, then when Java compiles the class, Lombok will aid in the automatic pluging in of Getter and Setter methods. In other words, Lombok reduces the need for boiler plate code.
-
Derby - This is an embedded database, so we do not need to have an external relational database configured to store our data.
Folder Structure
We will be working with the following folder structure for our project.
playground
src
main
java
com.playground
PlaygroundController.java
PlaygroundService.java
PlaygroundRepository.java
PlaygroundTable.java
PlaygroundApplication.java
resources
dev-properties.yaml
test
java
resources
pom.xml
Package Contents
-
Controller - The controller class maps out the API endpoints as well as HTTP methods that will be called by the API. Such methods include; GET, POST, DELETE, PUT. It will be annotatated with
@RestController
for spring boot to understand the class’s work. -
Service - The service class implements the methods that will be called by the controller class. While the business logic of methods called by the controller can be incuded within the controller class, adding them in the service class helps decouple the app and separate concerns. In order to follow OOP principles, Service could be an interface with methods that will be implemented within another
ServiceImpl
class. -
Repository - The repository class extends Jpa class so that its methods can be plugged into the app when data persistence is required.
-
Entity/Table - This class maps out the database table so that whenever JPA methods are called, the Java object with its associated fields and data will be persited in the database.
Show me the code!!
PlaygroundController.java
@RestController
public class PlaygroundController {
// dependency injection
private final PlagroundService plagroundService;
public PlaygroundController(PlagroundService plagroundService){
this.plagroundService = plagroundService;
}
// Get one
@GetMapping("/playground/{id}")
public ResponseEntity<PlaygroundEntity> getOne(@PathVariable long id) throws Exception {
log.info("Queried by id {} ", playgroundService.getOne((int) id));
return new ResponseEntity<>(playgroundService.getOne((int) id), HttpStatus.OK);
}
// Post
@PostMapping("/playground")
public ResponseEntity<String> postOne(@RequestBody PlaygroundEntity playgroundEntity) {
playgroundService.postOne(playgroundEntity);
log.info("Posted the payload {}", playgroundEntity);
return new ResponseEntity<>("Posted Successfully", HttpStatus.ACCEPTED);
}
}
PlaygroundService.java
@Service
public class PlagroundService {
// dependency injection
private final PlaygroundRepository playgroundRepository;
public PlaygroundService(PlaygroundRepository playgroundRepository){
this.playgroundRepository = playgroundRepository;
}
// Get one
public PlaygroundEntity getOne(int id) throws Exception{
Optional<PlaygroundEntity> playgroundEntity = playgroundRepository.findById(id);
if (playgroundEntity.isEmpty()){
throw new Exception("Entity not found with id " + id);
}
return playgroundEntity.get();
}
// Post
public void postOne(PlaygroundEntity playgroundEntity){
playgroundRepository.save(playgroundEntity);
}
}
PlaygroundRepository.java
public interface PlaygroundRepository extends JpaRepository<PlaygroundEntity, Integer> {
@Query("SELECT i FROM PlaygroundEntity i WHERE i.id = :id")
Optional<PlaygroundEntity> findById(@Param("id") int id);
}
PlaygroundTable.java
@Entity
@Table
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class PlaygroundTable {
@Id
@Column
private int Id;
@Column
private String name;
@Column
private String description;
}
Let’s Roll
Run the application with maven. ie mvn clean install
then mvn spring-boot:run
.
Test the API with Postman using the url, http://localhost:8080/playground
Sample Payload
{
"id": 1,
"name": "John Doe",
"description": "This is a RESTful API"
}