Skip to content

Build a REST API with Spring boot

Posted on:October 17, 2023 at 09:30 AM

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.

  1. Spring boot starter data JPA
  2. Spring boot starter web
  3. Lombok
  4. Spring boot starter test
  5. 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?

  1. Spring boot starter data JPA - JPA means Java Persistence API, that is used to persist, control and manipulate Java entities/objects into relational databases.

  2. Spring boot starter web - It is used to create a MVC (Model View Controller) type for web based spring applications.

  3. 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.

  4. 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

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"
    }

Project Code