If you’d like to know a little about RESTful API or how you can create one in less than 5 minutes using Spring Boot, this article might be all you need to read. This guide will take you through the requirements you need to have before implementing the steps described below.
Let’s say we have two applications that need to communicate — a frontend component and the backend. For communication to work, we need to define a set of rules and mechanisms both of the components know and follow. This set of rules and mechanisms is called an API, short for “application programming interface”. In this article, I’ll use JSON
as the format of the data.
API Basic Operations and HTTP Methods
We have four basic operations that form the CRUD concept (Create, Read, Update, and Delete). Each operation uses a different HTTP method:
GET
for retrieving the data (read operation)POST
for creating data (create operation)PUT
for updating existing data (update operation)DELETE
for deleting data (delete operation)
Of course, you can combine the HTTP methods with the CRUD operations as you wish, somehow we are forced by the business logic not to follow the above table. Just keep in mind that combination represents a best practice.
HTTP Status Codes
We saw the methods responsible for handling the data, but how do we know if the request was successful or failed? Well, let me introduce you to the HTTP status codes! There’s no chance you aren’t familiar with the 404 Not Found
or 500 Internal Server Error
. These are the status codes, well, just two of them. The list is quite long and we have them split into five categories.
1xx
- Informational (e.g.101 Switching Protocols
)3xx
- Redirection (e.g.301 Moved Permanently
)4xx
- Client Errors (e.g.400 Bad Request
,403 Forbidden
)5xx
- Server Errors (e.g.502 Bad Gateway
)
API Design
In REST (representational state transfer), all resources are entities. They can be independent (e.g. retrieve information about an author) or dependent (e.g. retrieve all articles written by an author). Another important thing to mention is the structure of the URL. It’s like a sentence, a command, and it is good structured when you can say what that operation does just from the URL. Let’s take a few examples.
GET {hostname}:{port}/api/authors
this should retrieve a list of authors on the blogGET {hostname}:{port}/api/authors/2
this should retrieve a single author, the one with theid = 2
GET {hostname}:{port}/api/articles
this should retrieve a list of articles on the blogGET {hostname}:{port}/api/authors/2/articles
this should retrieve a list of articles written by the author withid = 2
The above picture is a screenshot from an application’s documentation. It’s very important for us to document our API and an open-source tool is Swagger. The documentation from the picture was generated automatically in Spring, based on the annotations from a controller.
- Java 8
- Maven
- An IDE (e.g. IntelliJ, Visual Code)
We need to generate our Spring Boot application and to do that we’ll use an awesome tool called Spring Initializr. Fill in the group, artifact, and the name of the application as desired and add the dependencies as shown in the picture. We need Spring Web to create our REST controller. The Lombok dependency is optional, but it helps us get rid of getter, setter, constructors, etc. For example, you can use the @Getter
annotation, and it will generate the getters for you. Use @AllArgsConstructor
and you won't need to define manually the constructor which takes all parameters and builds the object. Another annotation I'm using frequently is @Builder
to generate the builder method.
Generate the project and we’re good to go to the next step.
Let’s create a simple entity Book
with a few properties. To do this, I'll create a package called model
, and inside I'll create a new Java class called Book
.
Notice that I’ve also included the @Builder
annotation. This will allow us to create a new Book
with the following instruction:
For the controller part, let’s create a new package called controller
, and inside we'll create a new Java class called BooksController
.
The @RestController
is a new annotation introduced in Spring that combines the @Controller
and @ResponseBody
. The @ResponseBody
annotation tells a controller that the object returned is automatically serialized into JSON
.
The @RequestMapping
tells Spring the endpoint of our resource. That means, our calls will be made to {hostname}:{port}/api/books
. In our case, localhost:8080/api/books
.
Now let’s add two methods, one that will return a list of all books, and the other one will return only one book, by its title
. We don't have a database so we'll mock one.
We now have our database, let’s create the GET
methods.
Notice the @GetMapping
annotation. This will result in retrieving the list of books when we make the following call: GET /api/books
. Also, the ResponseEntity
return type is an extension of HttpEntity
that adds a HttpStatus
status code.
Now, for the second method, the @GetMapping
annotation has a parameter "/{title}"
which will make every call to GET /api/books/Book 1
to return the book where the title
is Book 1.
Also, the getByTitle()
function has a parameter of type String
called title annotated with @PathVariable("title")
which basically will map the title
value from the URL to the title
parameter of the function.
We should mention @PostMapping
, @PutMapping
, and @DeleteMapping
which will be triggered when the HTTP method is POST
, PUT
, and DELETE
.
The full code for BooksController
looks like this:
In the end, the structure of my project looks like this:
Building a REST service using Spring Boot is taking less than five minutes. This type of architecture is widely used across the web, and learning how to create a RESTful API in Spring might be the best starting point for everyone.