Employee API — Spring Boot [Part 1]

Saksham Gupta
Javarevisited
Published in
9 min readAug 7, 2021

Hello Everyone !!! This is my first article, written as a way to share a part of my learning during my summer internship at DBS Bank. This was a mock API that we had to make in order to get familiar with the Spring Boot.

Further task was to add two Database (NO-SQL and SQL) to the actual API made (not disclosing any confidential info.) . MariaDB and MongoDB were used in the actual implementation.Here in this article I will be going through the Employee Mock API which will be using H2 Database, which is an in-memory volatile database but suits our need to learn the Spring Boot and make an API. One of the key feature of this API is the search feature for specific keywords. (PS: the github link is provided at the end)

In part 2 of the Employee API, I will be adding a composite key for address and a composite primary key for unique identification.

In part 3 of this Employee API, I will be adding MongoDB in addition to the H2 DB to get to know how can we connect two databases within the same API.

Let me talk a little about Spring Boot from my perspective. I switched to Spring from NodeJS to create an API and personally being proficient in Java I found Spring to be really easy and so much less boiler code, plus the familiarity with Java made it easy for me to switch. Initially one might feel we need some 10 lines to run a server in Node which is very less compared to Spring but in Spring we need not mention any code to run the server, we only need to write our logic and see it work.

Starting with the actual implementation let's take a look at the directory structure to understand how things are connected.

.idea contains all the settings and config files for IntelliJ.

.mvn contains all the dependency files from maven.

src contains all the code files following separate packages for separate parts of code thereby making use of SOLID Principles.

target contains the build files.

.gitignore has the names of the files that need not be pushed to GitHub.

pom.xml has all the details and dependencies of the maven and spring including the version info and the project name.

To begin with the project we need to download the project setup zip from Spring Initializr where we will select our requirements and it will provide us with the configured project files.

Please make similar selections as shown in the image below. We add certain dependencies, to begin with, which are required by our API namely :

Lombok- It is used to add annotations in place of some basic code which is common and mostly repeated like the Getters and Setters, Parameterised and No-Arguments constructor, etc.

Spring Web- provides us useful features necessary to make a REST API, which is internally needed to run an application in Spring.

H2 Database- provides us with an in-memory database and we need not install any DB on our local to test our API. It's a SQL-based Database.

Spring Data JPA and JDBC- provides us with necessary libs. required to successfully make queries on our SQL DB.

Spring Initializr snapshot

Next we can unzip the .zip downloaded from above and open it in our IntelliJ and add some necessary plugins namely Lombok (required to read Lombok annotations) and SpringBootGen (required to make better suggestions while development) to make our development easier.

All the settings and configuration is done in the application.yml file in the resource folder, this includes the database connection and the H2 Console, etc. which looks like :

There are some other dependencies that we need to add in the pom.xml which includes the validation, swagger documentation, open-ui, etc. like this:

We are now done with the setup and ready to write code to make our API work. Our application starts from EmployeeApplication.java which contains the main function and the starting point of our application in com.api.employee package. We need to annotate our class with @SpringBootApplication after which spring identifies it as the main class and looks like this:

We need to mention the schema of our Employee object for which we create a package in employee called entity where we define our Employee POJO ( Plain Old Java Object) class, which looks like :

Here we can see how we make use of Lombok and skip writing all the getter, setter, and constructors. The @Entity annotation makes spring able to read it as an entity that is linked later to the database via repository. The @Id annotation tells that this field will be used to uniquely identify every employee and act as the primary key for our object.

We have further added Validations to our Employee entity such as the fields which can’t be empty are marked with @NotEmpty, we specify the size of entries in the fields with min and max range and we have also specified the pattern which is accepted for phone numbers and the error message that needs to be displayed if the format is incorrect.

You can notice all the attributes are private, this is to keep our data safe and any modification or retrievals can be done only via getters and setters.

Next, we will specify our dto (data transfer objects) in a package com.api.employee.dto , we do not want to expose all our data or our schema to the end user of our api and hence we make use of dto which will be the mode of communication between end user and api. For our case, we are going to skip the deptNo in the dto as we do not want to show the department of any employee to the consumer. EmployeeDTO class looks something like this:

Next, we can add a repository which will connect our entity with the database and enable us to run queries. We are using Pagination in our response body and therefore we need to supply a Pageable (includes page size, page number, and sort order) object to the findAll() function along with the Specification (includes the query in a structured format that we will define later and use in the service layer) and the return type being Page.

Before the controller and the service layer, we can first write the other utility classes which help us to efficiently make use of OOPs concepts and reduce code redundancy and also follow the SOLID Principles and industry level application structure.

These include the Exception Frameworks(required to send error response in a proper format), Specification(used for making query), ModelMapper (required to map entity to dto), OpenAPIConfiguration (required for the Swagger Documentation) and a Message Class. All these classes are witten in their own package(as stated at the top where directory structure is shown).

Exception Classes- We have broken the exception response into three classes, this is because currently we have a limited number of exceptions but on a large application there are many errors and all of them should follow the same response structure.

This class specifies the fields that every exception should have.
This Class mentions the different exceptions that can occur.
This Class acts as the exception listener i.e whenever an exception occurs the respective methods are triggered and send the exception response.

Specification Class- This class makes the different query structures for like and equals operation, we can also explicitly write the SQL queries in the repository but in order to make any change we need to edit the query which can be complex at times and isn’t advisable on a large scale application.

ModelMapper Class- it maps the attributes from the entity to the dto and vice-versa for transfer over the network.

OpenAPIConfiguration- has the setup for Swagger Documentation which is a GUI-based web app and shows all the operations available in the API and an option to execute them.

Message Class- this has a simple POJO structure if we want to send a specific message to the user we can make use of this.

We can now come to the most crucial part of the API and the Class that is exposed to the end-user — The controller. This has all the CRUD operations along with that it has an endpoint to add multiple employees together:

The key point to note in the controller is that it only receives the requests and transfers them to the service layer. The controller is annotated with @RestController(tells spring that this is controller class and to look for its url on receiving any requests) and @RequestMapping(specifies the url whose requests this controller will receive).

Each endpoint is represented by a function and is annotated with the type of request it handles like the GET, POST etc. The description provided in the @Operation annotation is added in the Swagger. The @Valid checks if the request body is in accordance with the validations that we have provided in the dto and entity.

We will now write the heart of our API i.e the service layer. All the requests transferred from the controller are processed here. All the utility classes that we have defined will be used in the service class.

We have followed the interface model for our service layer as we can have many implementations of the service layer but all of them need to follow the same parameters and the return types which is specified by our interface.

The class is annotated with @Service which tells the spring to include it in the service layer and if we have multiple implementations of the service interface and it is Autowired in the controller, @Qualifier can be used to specify which implementation of the interface to use.

The rest of the code in service is quite simple and makes use of the exceptions that we had written for our API, the queries in the getAllEmployees() function is generated through the specification class we mentioned and the entity is converted to dto before it is sent to the controller.

Since we do not have any data at the start of application I have added a push service which is called at the start of the application and reads a json file from resource folder and add all the employees to the db. This part of code is not mentioned here as this post has already been quite long and you can find it in the github repo link attached.

You can also have a look at the tables that are created in the H2 DataBase using the h2 console, on you browser go to this url ( http://localhost:8080/h2 ) and login with the id and password in the application.yml and the table would look like this:

Github Repo Link:-

And Hey we have written our first API following some industry level standards and if you have been wondering how Swagger Documentation looks ….. here you go!!!

All the endpoints are shown here and further details about their request and response structure is also provided.
An example endpoint of getAllEmployee based on the search keyword and the Page structure.
//This is the Response Body Structure
{
"totalPages": 0,
"totalElements": 0,
"size": 0,
"content": [
{
"empId": 0,
"empFirstName": "string",
"empLastName": "string",
"empEmail": "string",
"empContactNumber": "string"
}
],
"number": 0,
"sort": {
"sorted": true,
"unsorted": true,
"empty": true
},
"pageable": {
"offset": 0,
"sort": {
"sorted": true,
"unsorted": true,
"empty": true
},
"pageNumber": 0,
"pageSize": 0,
"paged": true,
"unpaged": true
},
"numberOfElements": 0,
"first": true,
"last": true,
"empty": true
}

Part 2 and Part 3 that were mentioned at the start of the post will be updated in due time as this was my first post and took some time to finish it.

Thank You for coming this far, I hope it added some value to your understanding of Spring and helped you in some way.

GoodBye and See you in my next Post.!!!

--

--

Saksham Gupta
Javarevisited

SWE II @ Google | Microsoft Research | DBS Bank | B.E. CSE BITS Pilani