Easily build a REST API with Spring Framework

Rafael AS Martins
Analytics Vidhya
Published in
9 min readDec 14, 2020

The capacity to learn is a gift; the ability to learn is a skill; the willingness to learn is a choice. — Brian Herbert

Most rookies, whenever they hear the word API in a conversation or an article, some interesting thoughts may come to their minds, like complexity, unknown, difficulty, etc.

There’s no problem with that, we all must start from somewhere right? Once before, I was someone who didn’t even know what the API acronym stood for, and then, like you, I started reading, wondering, trying… and now look at me, as a software engineer, I create them almost every day, and I love it!

Today’s goal is to show you that the words previously mentioned are just representations of what we fear about the unknown. And then, I want you to wonder how you ever even considered such feelings.

We will create a simple example from scratch, explaining every step, every choice, and how we can, with Spring Framework, in just10 minutes, have a working REST API.

# The Concept

Before I even start explaining how to create an API, you should first know what this thing called API” is.

To begin with, API stands for Application Programming Interface, Wikipedia explains it as:

A computing interface that defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc.

Let’s try mapping it to a specific example: Imagine you have a portfolio web page, where you share some information about yourself, like interests, side-jobs, professional experience, projects, and so on. Now you want people who follow you, to be always up to speed about your Spotify preferences.

You may think about manually going to your Spotify account and copy your liked songs, it may work if you are an inactive user, however if not, it will quickly become a cumbersome task.

That’s when the API word comes in, Spotify and a lot of other companies already developed their APIs, so people like you can avoid problems like this.

developer.spotify.com

In such a context, you will simply need to contact their API and request all the data that may fulfill your needs. In this case, your liked songs.

An API can be described as an application that exposes services without the need of having a front end.

Let’s now create our API example so we can easily understand what has been explained so far.

# Implementing an API

# Creating the initial project structure

Spring Framework was the chosen tool due to the following factors:

  • Easy to set up;
  • Easy to understand;
  • Easy to map the main concepts within the code;

Note: In case you don’t have Maven or at least JDK 8 installed, use the respective links to install them.

Spring has a nice project start-up page, called Spring Initializr, where you can easily create your project structure with the needed dependencies.

  1. Access spring initializr and define the following properties.
  • The project can be either Maven or Grandle, for rookies, I suggest Maven due to the great number of examples you have out there.
  • The example below will be in Java so that’s why we choose Java;
  • Select the 2.4.1 version so we can have a stable version.
  • And then some metadata, like your project name and a brief description.
  • The Jar option is selected so we can run our example without needing any application server.
  • Any Java version displayed below will do the job.

2. In the “Add dependencies” button, choose the following dependencies:

Spring Web
  • Spring Web — For exposing services to the world, like Spotify does to expose the service that gives you all your liked songs.
  • Spring Data JPA — So we can map our Java entities with SQL tables and execute CRUD operations.

Note: CRUD stands for Create, Read, Update, and Delete SQL operations.

H2 Dependency
  • H2 — An in-memory database that allows simulating a real database within our codebase.
Lombok Dependency
  • Lombok — Reduces boilerplate code, for instance, with the @Getter annotation you can avoid writing all the attributes getter methods.

And that’s it, we now have all we need to create our API, in the end, you should have something similar to this:

Spring Initializr with all properties set

3. Click on “Generate” and a zip file should be downloaded.

4. Import it into your favorite IDE;

Note: The example will be shown in IntelliJ, however, all the steps should be the same in some other IDE.

# Defining the package structure

The package structure is an important step in every project, in time, your class number will increase, and we will need to conceptually organize them so we don’t lose track of them and so we can find whatever we need easily.

My suggested package structure is:

  • controller - Where all you REST controllers are;
  • model - Where all mapped Java/SQL entities are;
  • repository - Where all JPA Repositories are. These repositories will contain all the CRUD operation explained above;
  • service - Where we will, from the data retrieved by the client, handle the business logic;
Package Structure

Note: All the code is available on the GitHub page, so you can confirm and test everything whenever you need it.

# Defining the Java/SQL entity

As you probably noticed in the dependencies section, we added something called JPA (Java Persistence API) and can be described as:

Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer, you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

In the “modelpackage create a class called Client and the following attributes and annotation:

Client.java
  • @Data will generate all the getters and setters defined in our Client class;
  • @AllArgsConstructor creates a constructor with all the attributes;
  • @NoArgsConstructor creates an empty constructor;
  • @Entity defines this class as a mapped SQL entity/table;
  • @Table(name=”client”) says that this class is mapped to a SQL table named client;

Our client entity will contain 4 attributes: an ID, that will identify univocally from all the others, a name, an age, and an address.

The ID is, as you can see, is annotated with @Id and @GeneratedValue, this will allow the attribute to be handled as the client identifier and to be automatically incremented every time a new client is added to the client table.

Each column as you can see is annotated with @Column(name=”…”), where the name is the SQL column name that will be mapped.

# Defining our entity repository

The entity repository is the place where methods that have to interact with the database are, like delete an entity by id, fetching by id, and so on.

It’s straightforward to define one, you just need to create a new interface named ClientRepository extending the CRUDRepository at the repository package:

ClientRepository.java

The @Repository annotation will allow Spring to identify this class as such. Inside the CrudRepostiory diamonds, the “Client, Integer”, means that this repository will map the Client entity where the ID is identified by an Integer.

By default, when extending CrudRepostiory, some methods will be instantly available like:

  • findById
  • count
  • save
  • deleteById
  • existsById and way others.

In this example, the default findById does the job we need.

# Defining our service

In our service package, we will create a new class called ClientService. This class’s main responsibility will be to receive and connect the controller client requests to the actual operations that will be performed.

Our ClientService will contain:

ClientService.java

As you probably noticed, we have our class annotated as @Service, this indicates that it’s holding the business logic. So there’s not any other specialty except using it in the service layer.

Then we have a constructor, this constructor will inject the dependency clientRepository, just by adding the @Autowired, Spring does this automatically for us. When we inject a dependency, we are asking Spring to give us an implementation of that type, all the rest it’s up to Spring.

The last method is finally one of those methods that introduce business logic. In this context, we are calling one of those default methods that CRUDRepository has, in this case, we are finding a client with findById.

# Expose our API

At the highest level, we have our controllers. The main goal of these controllers is to receive outside requests and process them, and then they may return an answer accordingly.

To define the controller we must create a class (ClientController) in our controller package and then annotate it as @RestController.

ClientController.java

Within our @RequestMapping annotation, we are saying that all the requests to http://localhost:8080/client should reproduce a JSON response.

As you can notice below, what ClientService does with the ClientRespository, works by the same logic. We inject the ClientService so we can have access to it.

Then we have the method that will expose all our work done until the moment, we first start by adding the following annotation:

@RequestMapping(value = “/{id}”, method = RequestMethod.GET)

We are saying that all requests with the endpoint http://localhost:8080/client/{id} and with the GET operation, should be received by this method.

We then say through the @PathVariable annotation that the variable in the id position should be mapped to the id integer variable. To finish we call our service method that will return the client with the given id;

Note: The most used HTTP operations you may use can be:

# Populating our DB

Keeping in mind we are currently using an in-memory database, we need to introduce some data into it. Spring has in its startup an easy way to execute some actions, in our case, some data inserts.

To do it so, create a new class next to the ClientApplication (class automatically created by spring initializr) named DataLoader with the following content:

DataLoader.java

The only new concept is that this class implements the ApplicationRunner interface, this tells Spring to execute everything inside the run method on the application startup.

And that’s it! We just created an API purely using only 5 classes.

To test it, you can easily start the service up by executing the following command on the project folder:

  • mvn clean install
  • java -jar target/client1–0.0.1-SNAPSHOT.jar

After you see the following output you will be able to start requesting data from your API:

Spring Framework Logs

You can now go, for instance to your browser and request for http://localhost:8080/client/3 and this answer should come out!

# Conclusion

I hope this tutorial helped you understand that creating APIs is not as difficult as it may seem. As you witnessed, in only 10 minutes we managed to create one. I tried to give you the most simple and concise explanations, however, feel free to share any questions you may have and feedback on if this tutorial helped you or not.

See you in the next article.

--

--

Rafael AS Martins
Analytics Vidhya

As a software engineer, creating good and reliable solutions is my everyday goal. Within my articles, I try to express all the excitement and passion around it!