00: Create a simple REST API with Spring Boot

Q1. What is the key benefit of using Spring boot?
A1. The key benefit is that you can “build a production ready application from scratch in a matter of minutes”.

Over the years since its inception, Spring has grown to be very complex in terms of the amount of configuration an application requires. This is where Spring Boot comes in handy to simplify the configuration with opinionated defaults & inclusion of the libraries for you to get started quickly.

1) The Spring jars dependency management and versioning are simplified as demonstrated below with https://start.spring.io/.

Spring Boot’s main benefit is its ability to configure resources based on what it finds in your classpath. If your Maven POM includes JPA dependencies and a PostgreSQL driver, then Spring Boot will setup a persistence unit based on PostgreSQL. If you’ve added a web dependency, then you get Spring MVC configured with sensible defaults.

2) Spring boot is based on an HTTP server. Spring Boot has an embedded version of Tomcat by default, but gives you a way to opt for Jetty server if you wish.

Step 1: Go to https://start.spring.io/ to create a skeleton spring-boot application. Add “Spring Web“, “Spring Boot Actuator“, “Spring HATEOS” and “Spring REST Docs“.

simple REST API with Spring Boot

Generate & download the project skeleton artefacts by clicking on the “Generate” button. Copy the “simple-rest-api.zip” to the projects folder and unzip it. Open this folder via “Visual Studio Code” editor.

Step 2: The pom.xml file.

Step 3: Create a REST service. Create a new folder “controller” under “com.example.simplerestapi” in “src/main/java“.

HelloController.java

SimpleRestApiApplication.java in “com.example.simplerestapi” in “src/main/java“.

SimpleRestApiApplication.java

Step 4: Open a new terminal window. Build & run .

This builds: ~projects/simple-rest-api/target/simple-rest-api-0.0.1-SNAPSHOT.jar

Step 5: Open a new browser window and type

http://localhost:8080/hello

Outputs: hello from simple REST API

Changing the port from default 8080 to 8888

ctrl+c to kill the service from the terminal window.

Step 6: Open “application.properties” in “src/main/resources” folder and add the property “server.port”.

application.properties

Step 7: Build & run.

This builds: ~projects/simple-rest-api/target/simple-rest-api-0.0.1-SNAPSHOT.jar

Step 8: Open a new browser window and type

http://localhost:8888/hello

Outputs: hello from simple REST API

Spring Boot Actuator for monitoring

URL: http://localhost:8888/actuator

Outputs:

Now try:

URL: http://localhost:8888/actuator/health

Outputs:

print


Why wait 5-10 when you can fast-track in 1-2 ?

open all | close all
Top