Simple Rest API With SpringBoot, Postgres and Docker

Pramod Shehan
5 min readApr 5, 2020

--

In this tutorial, we are going to use,

  1. SpringBoot
  2. Postgres
  3. Docker
  4. Docker compose

1. Create SpringBoot Application

There are several ways to create spring boot project. In here I am going to use Spring Initialiizr.

This is the pom.xml. All the dependencies are included here.

2. SpringBoot Rest API

This is application. properties file. All the configuration are included into this file. In this tutorial we are going to use postgres database. So all the database username, password, datasource url are included here.

application.properties

This is the Employee model. After that this model is going to be an Entity in the database.

@ Entity- Class is an entity and it is mapped to the database.

@ Table- This annotation specifies the name of the table in the database.

@ Id- This specifies the primary key of the table.

@ GeneratedValue- This annotation is defined the strategy of primary key generation.

@ Column- This annotation specifies the name of the column with mapping the attribute of the model.

This module deals with enhanced support for JPA based data access layers. There are various spring data repositories such as JpaRepository, CrudRepository and etc.

In here, I am going to use JpaRepository. JpaRepository is extended by CrudRepository and PagingAndSortingRepository.

@ Repository- This annotation is used to indicate the data access component in the persistence layer.(all the database actions such as save, delete, update , find and etc)

This is the way to create custom exception.

A controller contains the business logic of an application. Here we are using @ RestController annotation to implement Rest based API.

@ RestController- This is the controller to use for creating Rest API.

@ Autowired- Marks a constructor, field, or setter method to be autowired by Spring dependency injection.

@ RequestMapping- maps HTTP request with a path to a controller method.

@ GetMapping- the path of the endpoint to perform a Get method.

@ PostMapping- the path of the endpoint to perform a Post method.

@ PutMapping- the path of the endpoint to perform a Put method.

@ DeleteMapping- the path of the endpoint to perform a Delete method.

@ PathVariable- extract any value which is embedded in the url.

@ RequestBody- bind the HTTP request body with the domain object.

This is the Main class. @ SpringBootApplication annotation is come up with @ EnableAutoConfiguration, @ ComponentScan and @ Configuration annotation.

@ EnableAutoConfiguration- enables Spring Boot’s autoconfiguration mechanism to import important modules for the Spring Boot to run.

@ Component- Tells the compiler that the following class is a component which should be included when compiling the whole application.

@ ComponentScan- This one does the Scan of which packages we are going to use in the following Java class.

@ Configuration- allow to register extra beans in the context or import additional configuration classes

After that we use mvn clean package command to build the jar file.

This jar file contains embedded tomcat. So we can this as a normal java application.

In here jar file is created under target file.

embedded tomcat server

3. Dockerize SpringBoot Application

This is docker file which we use to dockerize this rest api application.

FROM openjdk:8
ADD target/first-0.0.1-SNAPSHOT.jar first-0.0.1-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "first-0.0.1-SNAPSHOT.jar"]

4. Use Postgres docker

There are several postgres versions in thie docker hub (link).

docker hub

First we should pull the postgres docker using below command.

docker pull postgres:9.5

5. Use docker-compose

Here, I am using docker compose to run the postgres and my rest api application.

docker compose is a tool for defining and running multi-container Docker applications.

version: "3"
services:
postgres:
image:
postgres:0.1
network_mode: bridge
container_name: postgres
volumes:
- postgres-data:/var/lib/postgresql/data
expose:
- 5432
ports:
- 5432:5432
environment:
- POSTGRES_PASSWORD=docker
- POSTGRES_USER=docker
- POSTGRES_DB=docker
restart: unless-stopped
# This is my rest api app*****************************************
myfirstapp:
image:
myfirst:0.1
network_mode: bridge
container_name: myfirst
expose:
- 8080
ports:
- 8081:8080
volumes:
- /home/pramod/Desktop:/var/tmp
restart: unless-stopped
volumes:
postgres-data:

This is the command to run docker compose.

docker-compose up

After this, postgres and rest api application dockers are up and running.

6. logs

In springboot application, I have added some logs when calling the every rest call. so that log file is created inside the docker. log file destination is defined in “application.properties” file.

logging.file = /var/tmp/mylog.log

we are going to mount this file to location of my machine. It is defined under myfirstapp configuration in docker-compose file.

volumes:
- /home/pramod/Desktop:/var/tmp

7. Rest APIs

1. Save employee

POST- http://localhost:8081/api/v1/employees

2. Get all employees

GET- http://localhost:8081/api/v1/employees

3. Get employee by id

GET- http://localhost:8081/api/v1/employees/1

4. Display error when trying to get not existing id

GET- http://localhost:8081/api/v1/employees/8

5. Update employee

PUT- http://localhost:8081/api/v1/employees/4

6. Delete employee

DELETE- http://localhost:8081/api/v1/employees/2

8. Check The Entities

Now we can check our database. In here I am going to use docker exec command to access the database. But we can use pgAdmin, DBeaver as postgres client.

docker exec -it postgres /bin/bash

within the docker container, we need to use psql command like this. Here I am using name of the database as “docker”.

psql -d docker

9. Resources

https://www.freecodecamp.org/news/how-to-build-a-rest-api-with-spring-boot-using-mysql-and-jpa-f931e348734b/

https://www.baeldung.com/spring-data-repositories

https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa

http://zetcode.com/springboot/annotations/

https://spring.io/projects/spring-data-jpa#overview

https://docs.docker.com/compose/gettingstarted/

https://www.springboottutorial.com/spring-boot-with-embedded-servers-tomcat-jetty

--

--