Published on

Building REST API using Spring boot

Authors
  • avatar
    Name
    Nguyễn Tạ Minh Trung
    Twitter

Introduction

Developers are no longer unfamiliar with the Restful API. Using the HTTP protocol, we may effortlessly communicate with other applications by using Restful API.... So, let's start a new Rest API with Spring boot.

Wait.... Before starting, we have to setup environments as a Java backend developers 👨🏻‍💻:

  1. Java - SDK Manager is recommended
  2. Maven or Gradle
  3. Code IDE - IntelliJ is recommended

Okay! The few things above are enough to get start... Let's go 🚀

Getting started

  • In this article, I am going to using Maven for dependencies management, postgresql as database.
  • Going to Spring Initializr and generating a new Spring project with following the dependencies:
    • Spring Web
    • Lombok
    • postgresql
    • Spring JPA
Spring Initializr
  • Opening the downloaded project with your IDE
Alternative, if you are using IntelliJ Ultimate IDE, it's easy to create a Spring boot project on your machine IntelliJ IDE generating Next, intellij-spring-boot-generate Then, create

Database setup

  • Postgresql can be downloaded via internet and install directly on your machine
  • Alternatively, Docker is also a good option for every developers. A docker-compose.yml file is needed and we can easily start and use postgresql on your local by command docker-compose up
version: '3.5'
name: 'spring-boot-rest-api-docker'
services:
  db:
    image: postgres:12.13
    container_name: postgresql
    restart: on-failure
    ports:
      - 5432:5432
    environment:
      - POSTGRES_PASSWORD=password
      - POSTGRES_USER=postgresql
      - POSTGRES_DB=spring-rest-api-db

Okay, then, time to coding ... 👨‍💻

Architecture

  1. Controller: a controller is a class responsible for handling incoming HTTP requests and returning an appropriate HTTP response
  2. Service: a service is a type of class or component that encapsulates business logic or application functionality that can be reused across different parts of an application.
  3. Repository: a repository is a mechanism or component responsible for handling the storage, retrieval, and management of domain objects or entities.
  4. Domain: a domain is a representation of domain business objects or entities

Creating a domain object

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "persons")
public class Person {

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

    private String name;

    private Integer age;
}
  • @Getter: generating the corresponding getter method for the fields
  • @Setter: generating the corresponding setter method for the fields
  • @NoArgsConstructor: generating a no-argument constructor for that class
  • @AllArgsConstructor: generating a all arguments constructor for that class
  • @Entity: an annotation used in Java Persistence API (JPA) to mark a class as an entity, indicating that instances of this class will be stored in a relational database
  • @Table: an annotation used in Java Persistence API (JPA) to specify the details of the table to which an entity class will be mapped in the relational database

Creating a controller

  • PersonController class is identified by the @RestController annotation
  • PersonController class handles a GET request by @GetMapping annotation
@RestController
@RequestMapping(PersonController.CONTROLLER_MAPPING)
@RequiredArgsConstructor
public class PersonController {

    static final String CONTROLLER_MAPPING = "/person";

    private final PersonService personService;

    @GetMapping("/list")
    public List<Person> getListPerson() {
        return personService.getAllPersons();
    }

    @GetMapping("/{id}")
    public Person getById(@PathVariable Long id) {
        return personService.getPersonById(id);
    }
}

Creating a service

  • PersonService is an interface which defines all business methods relevant of Person entity
public interface PersonService {
    List<Person> getAllPersons();
    Person getPersonById(Long id);
}
  • PersonServiceImpl is an implementation, where implements the business logic for all methods. It is identified by @Service annotation
@Service
@RequiredArgsConstructor
public class PersonServiceImpl implements PersonService {
    private final PersonRepository personRepository;

    @Override
    public List<Person> getAllPersons() {
        return personRepository.findAll();
    }

    @Override
    public Person getPersonById(Long id) {
        return personRepository.findById(id).orElseThrow(() -> new RuntimeException("Not found"));
    }
}

Creating a repository

  • PersonRepository is a interface, which extends from JpaRepository - an interface provided by the Spring Data JPA framework, which simplifies the implementation of data access layers in Spring applications.
public interface PersonRepository extends JpaRepository<Person, Long> {
    Optional<Person> findById(long id);
    List<Person> findAll();
}

The final step

  • Update your application.properties file as below:
spring.application.name=spring-boot-rest-api
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/spring-rest-api-db
spring.datasource.username=postgresql
spring.datasource.password=password
spring.jpa.database=postgresql
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=create-drop

  • Now, this is time for data preparation before see the magic from APIs.
@SpringBootApplication
public class SpringBootRestApiApplication implements CommandLineRunner {

	@Autowired
	PersonRepository personRepository;

	public static void main(String[] args) {
		SpringApplication.run(SpringBootRestApiApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		Person person1 = new Person();
		person1.setName("John");
		person1.setAge(17);

		Person person2 = new Person();
		person2.setName("Alex");
		person2.setAge(18);
		List<Person> persons = List.of(person1, person2);
		personRepository.saveAll(persons);
	}
}

Time to testing ...

Postman is a powerful tool for API testing... Let's download and give it a try

Postman person list Postman person by Id