RESTful APIs + Spring Boot

PAUL DAVIES
9 min readJun 1, 2019

--

Hello guys,

Today we are going to learn how we can create RESTful end points using spring boot. If you have been following I have already explained what web services are here.

I have also written a sweet blog on how to work with JPA and hibernate for data persistence here.

One of the building blocks in java projects are POJOs. I have explained in simple and detailed way here.

The above forms the basis of what i will be writing about.

Lets get going guys….pee peeep

We are going to create a simple API that return a list of students in the database; Also, pass a parameter to get a list based on that parameter.

To start off, we need to create a spring boot project. I am using netbeans as my IDE but you can choose to use any. To create the project we need an initializer. There are two ways to achieve this. Either

From the Spring Initializr website or

Through the IDE if you have integrated it with Maven.

In the Spring Initializr website you will be required to provide the information below:

Creating Project through spring web

By default it will choose maven for you.

Enter the group- Any name you wish to. This will form part of your package name.

Artifact- The name of your project

Search dependencies- In this case I will want you to pick web, H2, JPA and MySql driver.

The click Generate Project- you will get a zipped file.

Unzip it to the place you want your project to be stored (your working environment).

Import it or open it on your IDE. It will automatically download all the required dependencies for you upon loading or on your first build.

If you want to create the project through the IDE (In this case netbeans, though you can use any like eclipse) then follow the steps below:

Open netbeans and click on “create new project” to get the below snippet.

New project snippet

On the categories choose “maven” and on projects choose “Spring Boot initializr Project

Press next to get the below snippet.

Project Information

As you can see, the information required above is same as the one on the spring boot website. Therefore fill it following the same procedure as highlighted before.

Let us look at some folders formed in the project created.

Project Structure

Quite a number of folders and files there. But I will only talk of the ones highlighted in yellow for now.

Source packages- As the name suggests. it contains all the classes and packages with the source code. Simply where we shall place all our source codes.

Application.properties file- this file allows us to define the properties that will be used to run the application.

Dependency folder-Contains all the dependencies for this project.

pom.xml- a very important file for spring boot projects. It contains the version of maven, and a list of all the dependencies in use.

Those are the ones that we shall be interacting with for now. You can open each and see what contained in them.

Now, we are going to structure our project into five packages. Come on, don’t be scared. It is not complex. It helps segment the project. We The packages are as follows:

Parent package- This one is created by default when you create the project. It is the one containing the main class.

Entities package- Contains the entity classes.

Services package- We shall place our service classes here. The service classes are only a bridging to the controllers. We are going to use them to do all our database queries. This can also be done in the controllers but for the sake of keeping out controllers clean, let us have them do the dirty work for us.

Repository package- This package contains interfaces for each and every entity class. As the name suggests, the repository interfaces help us interface with the database. We shall see how this is achieved.

Controller package- Contains all our controller classes. This classes define the methods that form our end points. The methods are what we shall be annotating with the URLs we need to call from ether postman or browser.

Below is a screen snippet showing you how I have created my packages in the “source packages” folder. You can create the same packages or create yours with suitable names.

Project Packages

As you can see apart from the first one, the rest bear the name of the components they are supporting. As explained before; this means all my controllers will go into the controllers package while entity classes will go into the entities package.

Now, in your entities package create an entity class and call it Student as shown below.

Entity class

In the class, declare the variables

private Long id;
private String surname;
private String firstname;
private String passport_number;

Take note that variables are created normally just like any java class.

Create the getters and setter methods for the each variable. See mine below.

Entity Code Snippet

Notice something in my entity class? yes, some annotations. For spring to know that this is an entity class, you should annotate it with @Entity annotation. This tells spring boot to check if there is a table by the name student in the database and if there is none then spring creates one for you. This happens at run time. For more information on how this happens please read this and this.

Next, let us create a repository for the above entity. In the repository package create an interface called StudentRepo. Annotate the class with @Repository. This way, spring boot knows that this is the interface between the student entity class to the data source. See my code snippet below.

Repository Interface Snippet

I would you to notice a few this about this interface.

It extends JpaRepository — because what we are creating here is just an abstraction of the DAO. DAO contains a number of methods that help in CRUD operation of the database.

It is an interface; not a class.

It has an entity class as an argument and the Long type- Reason being, it is specifically a repository for the entity student. This means if we created another entity class we will have to create a repository for it and pass it as an argument to the repository. The type Long is type of the primary key. Remember that in our entity class, we annotated the type id with @Id which tells spring that that field is the primary key for the table resulting from that entity class. Note that the type of the field is long. It is not however always the case. It can take other types as well.

The method findAllById() is justt but one declared method that comes from the DAO because we extended JpaRepository. There a number of methods including findAll(). The first one requires us to pass an ID as we shall see soon.

Let us now create the service. The service will help us fetch data from the database. This is where all the crud operations will be done.

In the service package create a class called StudentService. Annotate the class with @Service. This is to tell spring boot that this a service class.

Since we want to access the services of the repository class we do what is called auto-wiring. Allow me explain this a little. It is very important.

Assume you have two classes A and B. And that you want the services of class A in class B. This calls for you to create an instance of the object of class A in B then call the required methods and pass parameters. Now, if class a for example has a method that requires you to pass three parameters and requirements come in that you add a fourth parameter in the method. It means that you have two places to change. One, in the method in class A. And also, in the class B where you are calling the method.

What auto-wiring does is remove this whole process so that you don’t care what changes have been made in the method. All you care about is using it. So instead of creating an instance of the class A, we just mention that we shall need to use the class. That is it.

Now, see my service class code snippet below:

Service class

Look at the highlighted in yellow. The annotation @Autowired notifies spring boot that look, I will be using the interface called StudentRepo, and I don’t care how it is implemented.

Next I am declaring two methods. One getList() without any parameter while another requires a parameter. The first is meant to return all the students while the second one only returns one student with the provided ID.

Notice the usage of the the autowired interface. If you went back to the interface you won’t see the method findAll(). This is because by declaring the interface as a repository, you are telling spring to use all the available default methods of manipulating data. So the two methods are returning the data for us. You can do delete and update and add as well.

Let us now make use of the services. We need to create a controller class. The controller forms the access point of the end points. It is where we create access URLs. Look at the snippet below:

Controller class snippet

A very simple class yet very useful. Remember when I said we need to make our controller clean? yes, I have only auto-wired the service class (Remember the concept of auto-wiring) and I am simply calling the methods in it.

I wish you note the usage of @Autowired annotation here again. We are telling spring that look, I will be using the service class.

Note the following as well:

@RestController annotation indicates to spring boot that this class is the controller. This is what informs the application where to get the end point URLS.

@RequestMapping annotation- The annotation helps us define the URL. each method in this controller forms an end point. Whether for adding data to database, getting list, updating or deleting. The first method for example returns all the students if you accessed it using http://localhost/getList URL. It is that simple. Mark the last part in the URL and look at what the value in the annotation @RequestMapping is. The second method has an additional declaration in the @RequestMapping annotation. the parameter variable name. Note the declaration in the curly brackets and how it is called in the method.

The annotation @PathVariable enables us to extract the variable from the URl. Then we pass it to the method in the service class.

It is not over yet. How does our application know where the database is? How does it know where to connect to? How does it know the type of database? How does it know how to connect?

All those questions are answered by the properties file. This file allows allows you to define the run time parameters. When the Application launches it first checks this file for the properties to use. Look at mine below:

Properties File

From the file, you can see I have told my application which port to use; 9001 in this case. The database is H2 and other params. Remember you can change to suit your environment and your dictionary to properties should be this.

Now all said and done, run the application. use postman or your browser. Below is my result.

Result

Guys, it has been a journey but am sure when you get this right it will be short and sweet. See you in the next blog and don’t forget to leave a comment and a clap.

--

--

PAUL DAVIES
PAUL DAVIES

Written by PAUL DAVIES

Software Developer; Java, Angular2+,RxJS,Spring boot,Android

No responses yet