Spring Boot Introduction And Building A RESTful Application

Jack Graver
13 min readFeb 28, 2021

Entire Project Located: https://github.com/JackGraver/SpringBootREST

What is Spring boot

Spring Boot is an open-source framework created by Pivotal. It is one of the top APIs for creating microservices, and in our case RESTful applications. It is a platform for Java developers to quickly create stand-alone industry grade applications that you can “just-run”. The selling features of the API are its auto-configuration tools that will configure and build your project based on the dependencies that you stated, which is another important part of it, it’s very easy to add to a huge list of dependencies to give developers tons of freedom, from which database you are using, to even some third-party libraries that help you out in your project. The last big point is in comparison to Spring, the API that Spring Boot is built off of, they aimed to have as little complex XML writing for developers as possible, which is very helpful in both learning the API and writing applications quicker than ever.

What is RESTful application?

REST stands for representational state transfer, it is an API that uses HTTP requests to access or manipulate data. They allow applications to create mappings to specified links and then perform operations based on what kind of mapping it is and the kind of input provided. There are four parts to a request

· The Endpoint (the link)

· The Method

· The Header

· The Body (Data)

All of those aspects are handled and used by the REST API, and we will explore those using Spring Boot today.

Getting Started

Today we will be building a very simple RESTful application using Spring Boot that will allow us to view, update and delete data from a MySQL database. We will be walking through it part by part, and by the end of this blog you will have a simple application up and running, which you can take the concepts you will learn today to create more complex applications in the future!

Spring Initializer

When you’re just first starting your application, it is generally recommended you use the Spring Initializr to set up your project, though you are welcome to do it from scratch, it is easy and less prone to human error if you use the Initializr. It is found at this site; https://start.spring.io/

Default look of start.spring.io

Project

The first option you need to choose is if your project is ‘Maven’ or ‘Gradle. If you are unfamiliar with those, they are ‘build automation tools used for Java Projects that, as the name suggests, is used for project build, dependency, and documentation. I will choose Maven for this project, you are welcome to use Gradle, both have advantages and disadvantages.

Language

Next, you are asked to choose a language, if you are familiar with another of the other 2 languages than Java, you are welcome to choose any of them, but I am going to be using Java. They all do the same thing they are just different languages.

Dependencies

Now here’s the interesting part! A big part of Spring Boot applications is the dependency injection, this tap is where you choose some of your starter dependencies. For now, I am going to choosing are;

· Spring Web; for building web applications

· Spring Data JPA; for persisting data using JPA, Spring Data and Hibernate

· MySQL Driver; for connecting to our MySQL database

We are only starting with the 3 dependencies, but it is very simple to add more later on, which you will see.

Project Metadata

I am leaving all default values for the metadata as is, you can set them to any values you want, be aware of making sure you write the correct information if it calls for it in your application. You can always change these values in your project later on.

Java

I will be using Java 15 for this project, any version of Java will work, be aware there might be some bits of code that in my project that do not work in other versions of Java.

Once you have finished configuring your application, you can click on “Generate” at the bottom of the page and it will download a .zip file that contains your application. Unzip it and place it somewhere you will remember, now we start coding!

Creating Our Application

First things first we need to open up our project in the IDE of your choice. I am going to be using IntelliJ, you can use any IDE that is your favorite. Eclipse is popular as we are doing lots of Java programming, VSCode is also a good option. Here’s what your project looks like from the file we downloaded from the Initializr.

File Structure of Basic Spring Boot Application

And we are just going to do “clean-up” to ensure we can run our application without it throwing some errors. If you edit the ‘pom.xml’ file and comment out the JPA and MySQL dependencies so your ‘pom.xml’ 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>15</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>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>

Some Quick Background Information

Some quick information here about some of the files and folders that were created for you so you can have a better idea of how your project is being structured and what does what.

· Java — where all the java classes are kept

· DemoApplication — the driver class for the application

· Resources

· (static/templates) — stores all HTML content

· application.properties

· test — where all the tests are for the application

· pom.xml — an XML file that has the information about the project, pretty much everything you configured in the Initializr, and where we would add more dependencies if needed

The other files are important for your application, but we will not be tinkering with them as much as the ones I listed

Basic Concepts

Let’s do some coding!!! So were first going to start with the absolute basics of the program. If we open up our DemoApplication file (Note: this might be called something different if you changed some of the Project Metadata fields, but it will end with ‘Application’) and take a look at what’s going on inside of it.

package com.example.demo;

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

@SpringBootApplication
public class DemoApplication {

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

So, this is what the driver for the application looks like, as you can see there is an Annotation, and I hope you like Annotations because Spring Boot is all annotations! The one we see here ‘@SpringBootApplication’ signifies that this is the driver for the application. We’re going to edit this class a bit and do some cool stuff to start giving you an idea of what Spring Boot can do.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

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

@GetMapping("/hello")
public String hello() {
return "Hello World";
}
}

So lets look at the changes I made to the class. I added another Annotation ‘@RestController’, this represents that this class contains code for REST services, which is what the next change we see is which the ‘@GetMapping(“/hello”)’ annotation, this tells the application that the GET requests that are mapped to the link ‘/hello’. So now we can run our application, and if we were to go on our browser and go to the website ‘localhost:8080/hello’ it will display “Hello World” for us!

Now let’s make one last change and see what that does for!

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@SpringBootApplication
@RestController
public class DemoApplication {

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

@GetMapping("/hello")
public List<String> hello() {
return List.of("Hello", "World");
}
}

So, we change our ‘hello()’ method a little bit here, instead of returning a simple String it returns a List of Strings, which contains “Hello” and “World”. So, if we restart our application and go to the same website it will display the list in a similar format to JSON, which is what Spring Boot uses a lot of for data. Once you are done playing with this, you can delete all the code we added and reset the DemoApplication class to its original state, and we will continue working on making our application more complex, exciting!

Setting Application Properties

Were now going to edit the application.properties file to set configuration details for connecting to our database. I would recommend copying my code and editing them to fit your needs

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto
=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Going line by line now;

· Identifies what driver we are using, in my case MySQL

· Where the database is located

· The username to login to the database

· The password to login to the database

· Displays the SQL commands to standard out

· Depending on the value, it changes if we want to create the database every time the application is started, update means it does not recreate the database

· Specifies the type of database being used to ensure Hibernate is generating SQL statements that work with the database type

Creating a Model

Before we start, we are going to have to uncomment the two dependencies we commented earlier on in pom.xml so that we have access to annotations for JPA to create our model.

Once your pom.xml is all reset, we are going to create a Model that will help us with working with our data. We are going to first create a new package under com.example.demo and call it ‘Models’. Inside of the models package we are going to create a Java class called ‘Person’.

package com.example.demo.models;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {

@Id
private int id;
private String firstname;
private String lastname;
private String email;

public Person() {}

public Person(int id, String firtname, String lastname, String email) {
this.id = id;
this.firstname = firtname;
this.lastname = lastname;
this.email = email;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}

So, here’s our Person model. Some of the new Annotations are ‘@Entity’ which represents that this class is to hold data that we are gathering and manipulating. As well as ‘@Id’ to show that the id field is the primary key for this Entity.

Creating a Repository

The next step in creating our application is going to be creating a class that has loads of methods to help us use our data, and these classes are called ‘Repositories’, so we are going to place them in a new package called ‘repository’ and create a new interface inside that package called ‘PersonRepository’ which will look like this;

package com.example.demo.repository;

import com.example.demo.models.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
}

A very simple class indeed, but very powerful. Because when we extend the ‘JpaRepository’ class we are using all the functionality inside of that, it contains methods for finding, updating, deleting and more that we will see the true power of very soon here. We have to specify the datatypes inside the diamond operators, the first one is the Entity or Model that this repository will be using, and the second is the datatype of the primary key for that entity. We also used the ‘@Repository’ annotation which plainly indicates this class is a repository.

Create a Service Class

We are now going to create a service class, this is the class that talks to the repository, calling all those methods from inside methods of it’s own, which will then be called by the next layer in the controllers. A very basic service for our Person entity that only gets all the person entities in our database looks like the follow;

package com.example.demo.service.PersonService;

import com.example.demo.models.Person;
import com.example.demo.repository.PersonRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {

private final PersonRepository personRepository;

public PersonService(PersonRepository personRepository) {
this.personRepository = personRepository;
}

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

}

Where we have the ‘@Service’ annotation to indicate this class is a service class for the application. And a reference to the repository that we can see is being used in the getAllPersons() method to find all those entities, with the method .findAll(), which if you remember we did not implement, which is just one of many examples of how easy and powerful the repositories and Spring Boot are.

Creating a Controller class

The very last class we have to create before we are able to see our application do some magic is a controller class, this class will talk to the service class, which as we know talk to the repository classes, creating a good separation of concern design for our application .As always, we have to create another package to maintain the separation of concerns, call it ‘controller’ and create a new file inside of it called ‘PersonController’ and they are very similar to the service classes but with a couple extra annotations to deal with the REST requests;

package com.example.demo.controller;

import com.example.demo.models.Person;
import com.example.demo.service.PersonService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/demo")
public class PersonController {

private final PersonService personService;

public PersonController(PersonService personService) {
this.personService = personService;
}

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

As shown here, we have the ‘@RestController’ annotation which if you have a good memory we used earlier to create the simple hello world mapping. We also have the ‘@RequestMapping(“/demo”)’ which tells the application that any requests to the link /demo/… to be directed to this controller. And lastly the ‘@GetMapping(“/all”)’ annotation, which again is the same one we saw earlier on.

Let’s Rock and Roll!

Now that we have created our model, repository, service and controller, we are finally ready to run our application and see what it can do! So, once you start the application, navigate to the link ‘localhost:8080/demo/all’ which should then display all of the data from our database in a JSON like format on your browser! How cool is that?

Adding More Functionality To Our Application

We have now created a very simple Spring Boot REST application that can fetches data from our database, but wait! What if we only want to find one person? Or update a person? Or maybe were mad at our friend and we want to delete them from our database, then you calm down and want to add them back. That’s the next and last part we are going to add to our application, it’s as simple as a few more methods in the service class, and then some new mapping in the rest controller!

Here’s our updated PersonService class with the new functionality:

package com.example.demo.service;

import com.example.demo.models.Person;
import com.example.demo.repository.PersonRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {

private final PersonRepository personRepository;

public PersonService(PersonRepository personRepository) {
this.personRepository = personRepository;
}

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

public Person getPersonById(int id) {
return personRepository.findById(id).orElse(null);
}

public Person addPerson(Person person) {
return personRepository.save(person);
}

public Person updatePerson(Person person) {
Person personUpdated = personRepository.findById(person.getId()).orElse(null);

if(personUpdated != null) {
personUpdated.setFirstname(person.getFirstname());
personUpdated.setLastname(person.getLastname());
personUpdated.setEmail(person.getEmail());
return personRepository.save(personUpdated);
}
return personUpdated;
}

public void deletePerson(int id) {
personRepository.deleteById(id);
}

}

The 5 new methods we added do all of

· getPersonById() — returns a single person depending on the ID provided

· addPerson() — adds a new person to the database

· updatePerson() — updates the information of a person

· deletePerson() — removes a person from the database from the ID provided

And the updated PersonController class to add the new functionality we saw in the PersonService class;

package com.example.demo.controller;

import com.example.demo.models.Person;
import com.example.demo.service.PersonService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/demo")
public class PersonController {

private final PersonService personService;

public PersonController(PersonService personService) {
this.personService = personService;
}

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

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

@PostMapping("/add")
public Person addPerson(@RequestBody Person person) {
return personService.addPerson(person);
}

@PutMapping("/update")
public Person updatePerson(@RequestBody Person person) {
return personService.updatePerson(person);
}

@DeleteMapping("/delete/{id}")
public void deletePerson(@PathVariable int id) {
personService.deletePerson(id);
}
}

The new annotations are all very similar to the ‘@GetMapping’ that we are familiar with, but for different actions and some new links, the {id} represents input which is given through the controller, service and repository

· ‘@PathVariable’ for getting the input data from the link

· ‘@PostMapping’ for inserting a new person into the database

· ‘@RequestBody’ represents the person data given when accessing that link

· ‘@PutMapping’ for updating a person that is already in the database

· ‘@DeleteMapping’ for deleting a person from the database

Running and Playing With Your Application

The very last thing I am going to throw at you guys is how you have to test the links that are anything but GET. This is because when you were accessing it through your browser you were always sending GET requests, and to test the other you have to send POST, PUT, DELETE requests. Therefore, we use a tool called ‘cURL’, which can be done through the windows command line. Below are some default commands you can run to test your application, I have also included the JSON files I was using for these commands, after you run one you can go back to your browser and run the GET request /all to see the changes to the data!

· POST: curl -d “@add.json” -H “Content-Type: application/json” -X POST http://localhost:8080/demo/add

· PUT: curl -d “@update.json” -H “Content-Type: application/json” -X PUT http://localhost:8080/demo/update

· DELETE: curl -X DELETE http://localhost:8080/demo/delete/4

And then just a big of terminology to help you guys with running these commands.

· -d “@_.json”: is the data you are sending to the application through the json file

· -H “Content-Type: application/json”: let’s the application know that the file you are sending is of type JSON

· -X: the kind of request you want to send (POST/PUT/DELETE”)

That’s all that I have to show you today about building a RESTful application with Spring Boot! I hope you guys learnt something new are able to apply this new knowledge to build some awesome and complex applications! Thank you for your time.

--

--

Jack Graver
0 Followers

Fourth Semester Software Development student at SAIT