Creating first Spring Boot RESTful API with PostgreSQL

Časlav Nedeljković
5 min readDec 30, 2020

Spring Boot is an open source framework that helps you create production-grade Spring based applications efficiently and without effort.

PostgreSQL is one of the most popular open source object-relational database system, backed by more than 20 years of community development. It is used as the primary data store for many web applications, like IMDB or Reddit.

Creating the project

First things first we need to create our project. Best way to do that is with Spring Initializr. The Spring Initializr is a web application that can generate a Spring Boot project structure for you. It is the fastest and easiest way to pull in all the dependencies you need for an application and it does a lot of the setup for you.

Generating project

Today we’re going to work with Gradle, so first of all choose Gradle Project. Spring Boot version should always be the latest (but not snapshot). Dependencies we added :

  • Spring Web: for building web applications
  • Spring Data JPA: for persisting data
  • PostgreSQL Driver: for JDBC connection
  • Lombok: to reduce boilerplate code

Next step is to import the generated project into your IDE.

The following picture include complete directory structure of the project:

We are going to create the required packages and classes one by one in the coming sections, but first let’s take a look on the main class.

Main class

package rs.caslav.SpringExample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringExampleApplication {

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

}

Look at @SpringBootApplication, behind this annotation, there are:

  • @SpringBootConfigurationindicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.
  • @EnableAutoConfiguration annotation auto-configures the beans that are present in the classpath. This simplifies the developers work by guessing the required beans from the classpath and configure it to run the application.
  • @ComponentScanHere we can specify the base packages to scan for spring components, for example @ComponentScan("rs.caslav.*") .

Properties

In the application.properties file we configured Spring Boot for PostgreSQL usage. Spring-Data uses spring.datasource properties to locate the postgres instance and connect it. You can do that by adding database url, username, and password.

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.datasource.url=jdbc:postgresql://localhost:5432/springexampledb
spring.datasource.username=postgres
spring.datasource.password=123
spring.jpa.hibernate.ddl-auto = update

Last two lines are for Hibernate, first we specified the current database dialect, and ddl-auto property is used to automatically create the table based on entity class.

Model

To create a table in PostgreSQL, you have to create an Entity class, for example, Student. It maps to table “student”. Let’s define the Student entity.

Student

Here comes Lombok annotation: @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together. In other words @Data generates all boilerplate code.

Serialization is the conversion of a Java object into a static stream (sequence) of bytes which can then be saved to a database or transferred over a network.

Each entity must have at least two annotations defined: @Entity and @Id. @Entity annotation specifies that the class is an entity and is mapped to a database table. @Table annotation specifies the name of the database table to be used for mapping. The @Id annotation specifies the primary key of an entity and the @GenerationType.AUTO is used to generate id automatically whenever a new student is added.

package rs.caslav.SpringExample.model;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;

@Data
@Entity
@Table(name = "student")
public class Student implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "firstname")
private String firstname;
@Column(name = "lastname")
private String lastname;
}

Repository

Student repository

Now we need to create StudentRepository interface that extends @JpaRepository<Student, String> providing JPA related methods such as save(), findAll(), and so on, that we’re going to use in our controller for CRUD operations.

@Repository: Indicates that an annotated class is a “Repository”.

package rs.caslav.SpringExample.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import rs.caslav.SpringExample.model.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, String> {}

Controller

This class let’s us to interact with outside world, it handles incoming HTTP requests and send response back to the client. Last we need to do is to write basic REST endpoints inside controller for performing CRUD operations:

  • Create a resource: HTTP POST
  • Retrieve a resource: HTTP GET
  • Update a resource: HTTP PUT
  • Delete a resource: HTTP DELETE

We are going to write post and get method.

StudentController

@RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.

The @Autowired annotation is used to autowire JPA methods from StudentRepository.

@RequestBody is used to convert the body of HTTP request to the java class object. This annotation will be used in the method parameter and the body of the http request will be mapped to that method parameter.

package rs.caslav.SpringExample.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import rs.caslav.SpringExample.repository.StudentRepository;
import rs.caslav.SpringExample.model.Student;

import java.util.List;

@RestController
@RequestMapping("/api/student")
public class StudentController {

@Autowired
StudentRepository studentRepository;

@PostMapping
public String create(@RequestBody Student student) {
studentRepository.save(student);
return "Student is created";
}

@GetMapping
public List<Student> getAllStudents() {
List<Student> students = studentRepository.findAll();
return students;
}

}

GitHub:

We’re done building our REST API’s. Now let’s run application in Postman.

Postman

Postman is an API client used, in our case, to test HTTP request, as well as to read their responses. Download Postman here.

POST request

We are using http://localhost:8080/api/student API, but different requests. For POST request make sure that POST is selected for the method.

Now we have to add Request Body to our POST request. Click on raw and select format type as JSON. This endpoint expects JSON body witch contains the details of the new user. Finally press Send and see the Response Body and Response status, which should be: Status: 200 OK”, meaning that the request has succeeded.

This is what we should get in database:

PostgreSQL

GET request

To show Student that we have created, select GET method, with same API, and then press Send.

--

--