Malindu Panchala · Follow
Published in · 9 min read · Mar 2, 2021
--
Hello guys! In this post, I will guide you to build a simple REST API using the Spring boot framework. Before look into the detailed guide, let’s see what the Spring boot framework is.
Spring is an open-source Java framework that you can build powerful applications. Frequently, this is used to build web applications and microservices. Spring boot is a spring-based framework that makes building spring applications very convenient.
Spring boot provides auto configurations for spring applications and it is used for building microservices. Spring boot helps developers to reduce time in the development and testing and lets developers focus on their business logic and other things. For more details about these frameworks, you can head to the following links and spend some time reading and get a better understanding.
https://spring.io/projects/spring-boot
Let’s see how to start your application.
You can start your spring application from the spring initializr. On this website, you can select preferred configurations and generate your template. Or you can start your project with your IDE too. (Continue if you want to start the project using IDE. I will give instructions for IntelliJ IDEA and Eclipse)
I’m using this same data to generate the project, but you can change the necessary information. Make sure that you are using the latest spring boot version (In this case, 2.4.3), not the snapshots. And also, here I have selected the maven project.
After this, you have to select the necessary dependencies. The following image will show you the dependencies that I am going to use in this project.
You can select these dependencies by clicking the “Add dependencies” button (Or pressing CTRL + B).
Spring boot DevTools is used to deploy the project to test the application. As it is mentioned in the image, it provides fast restarts, live reloads, and configurations.
Spring Web is used to build our application and it uses the tomcat server to deploy the application.
Spring Data JPA helps us manage data with our database.
Since I am going to MySQL as my database (in the xampp server), I have also added the MySQL driver to connect with the database.
Before generating the project, you can preview it by clicking “Explore”(CTRL + SPACE).
Here, the “pom.xml” file contains all the dependencies. So, if you need to add another dependency to your project later, you can do it here. For now, this file looks like this.
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>Demo project for Spring Boot</description><properties><java.version>11</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
After this, you can generate the project and open it with the preferred IDE. I will be using IntelliJ IDEA.
If you wish to use your IDE also to generate the project, then you can follow these steps. If have already done this, then you can skip these steps.
In IntelliJ IDEA, you need to download a plugin to generate. I have used a plugin called “Spring Assistant”. To download this, Go to File > Settings > Plugins (CTRL + ALT + S > Plugins)and select the Marketplace tab. Then Search for Spring and it will show you all the plugins available. You can install any plugin but I recommend you to use the “Spring Assistant” plugin.
Then go to File > New > Project and you will see this window.
Select Spring Assistant (Or installed the plugin) and click “Next” (Check whether Default is selected). Then you will get the form to fill out the project details like in the Spring initializr. Here also, I’m going to use the default data but you can change it as you want.
By clicking “Next”, you will be redirected to another window to select dependencies. You can select all the dependencies that we did in Spring initializr. (If you skipped that part, scroll up and you can find an image with necessary dependencies).
After clicking “Next” you will see a window to provide the location to save the files. Go ahead and give a location, and then click “Finish”. The project will be generated after this and maven will sync your project and download all the libraries. Let’s see how to do the same thing with Eclipse IDE.
Also in Ecplise, you need to have a plugin to generate a spring application. I am going to use Spring Tool Suit 4 (STS4), and it is available to install in the eclipse marketplace. You can go to the eclipse marketplace by following Help > Eclipse marketplace. Then search for “spring tool suite” and install STS 4.
Then you can go to File > New > Other and then select Spring boot starter project under spring boot. And by clicking “Next” after that, you can go to the “New Spring starter project” window. In there, you can change the details and click “Next”.
After that, you will get a window to select dependencies. You can select the necessary dependencies.
Then you can finish and the eclipse will download the libraries and let you start developing your application.
I think that would be enough about starting. Let’s start writing our code to build the API. Here I will be making an API to manage Users (create, update, delete, read).
After you have created a starter project successfully, you can see your main class (DemoApplication.java in my case), and it should look like this.
You can see the “@SpringBootApplication” annotation above the class declaration. This defines your spring application and spring boot can identify this class as the main class. Let’s start writing our code.
First, we need to create our entity/model class, which is “User”. Let’s go and create a package named “com.example.demo.entity” to make our class inside it. Here, you can use your own package name that you used when you creating the starter project and adding “.entity” to the end. After that, you can see a folder named “entity” created inside your package.
Inside the newly created package, let’s create a class named “User.java”. Inside the class. write the relevant variables and create getters and setters for them. To make it work with JPA we need to add the annotations in the following class. Make your entity class according to this code.
This will define your user table in the database. But JPA won’t do anything if you don't create an interface extended from JpaRepository class. To do that create another package inside your working package (like entity package) named repository. Inside that create an interface and I named it as “UserRepository”.
Then, we need to write the database configurations in the application.properties file, which is inside the src > main > resources folder. Then write these configurations.
Here, I have not included the “spring.datasource.password” property because my database doesn’t have a password. But make sure you are writing this if your database has a password. You can edit the URL too. URL format should be “jdbc:mysql://{your database ip}:{port}/{database name}”. If you don't want any execution messages in your console, then you can remove “spring.jpa.show-sql” line.
After this, let’s go create a service class to implement the necessary methods to use our UserRepository. To create this, you have to create another package named “services” inside the main package (mine is com.example.demo.services ).
Now we can implement a controller class to define our API URLs and use the service class to manage data. For that, create another package named “controller” inside the main package (com.example.demo.controller in my project). Inside the package, I created a UserController class to define my APIs.
In this class, you can define your API URLs as you like to. If you need to use custom URLs then you can use @RequestMapping annotation and pass the path as a string to the annotation as I have done before the declaration of the class.
Now we have done everything. Let’s start our database and run our application. Before running the application check whether your database has the table named after the given entity name(users). After running the application you can see these messages in your console
Now let’s go and check our database.
If you have followed all the steps correctly, then you can see a table has been created automatically after running the database. Yaayy!!!!
We have to check whether our application working correctly. To do that I am using Postman. If you don't have postman then follow this link to download.
First I have tested adding a user from postman as the following image and it returned the added user successfully. And in there, you can see that JPA as automatically given the user an “id”.
And In my database, a new record was created!
Then I tested my get methods after adding some more users. After testing /users API call. I got every user I have sent to the API.
It also returned the user by the id given in the URL.
After this, I have updated the second user and it returned the sent data. That means, API successfully updated the given record. But here, I have only sent the object and didn't include the id in the URL. But my function in the service class updated the record by getting the id from the passed object. But if you wish to pass the id by the URL, you can do that too. You just have to define the @PathVariable in the updateUser function in the controller class and add {id} to the string parameter of @PutMapping.
The Database now looks like,
Finally, I have performed the delete request and this is the result of it.
You can see the record with id 4 is now deleted and it returned the response “OK”. You can change this to another HTTP response in the deleteUser method.
Now we have successfully created a RESTful API with CRUD operations using the Spring boot framework(phew….). After this, you can refer to other resources and practice to gain more skills with this framework. Good Luck and thank you for reading this guide. If you spot any mistakes or if you have a better way to do something in this post, please leave a comment. Thank you!❤
Resources for you: https://spring.io/guides
Code in this post: https://github.com/MalinduPanchala/Springboot_api.git