How to create a REST API with Spring Boot


As MuleSoft architects, we often focus on designing and managing APIs within the MuleSoft ecosystem. However, it's equally important to work with APIs built on other platforms to ensure seamless integration and test their behavior with 
Flex Gateway

One of the easiest ways to do this is by creating a simple Spring Boot REST API, which can serve as a non-Mule backend for gateway testing. In this guide, we’ll walk through the process of setting up a "Hello World" REST API in Spring Boot, configuring it to run on a custom port, and preparing it for testing with Flex Gateway.


Prerequisites

To follow this example, we’ll use a virtual machine (VM) running Ubuntu Server 24.04 LTS with Docker installed. This setup ensures a controlled environment for testing and makes it easy to containerize and deploy the REST API. Check out this post to know How to Install Docker on Ubuntu Server.

Before we start, we need Java and Maven installed


Install Java

We will install the Java JDK 21 with the following commands:

sudo apt-get update
sudo apt-get install openjdk-21-jdk

verify installation

java --version

Check out this post to get more details on 
how to install Java on Ubuntu server


Install Maven

We will install Maven version 3.9.9 for managing dependencies and setting up the Spring Boot project using archetypes. It helps simplify project configuration and builds.download maven. For that, download Maven with the command:

wget https://dlcdn.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.tar.gz

Then Unzip the file

tar -xvf apache-maven-3.9.9-bin.tar.gz 

Move the binaries to a specific folder

sudo mkdir /opt/maven
sudo mv apache-maven-3.9.9 /opt/maven

Lastly, set up the M2_HOME and PATH environment variables by editing the profiles file in Ubuntu. Open a text editor

vi ~/.profile

add the following content at the end of the file

export M2_HOME="/opt/maven/apache-maven-3.9.9"
PATH="$PATH:$M2_HOME/bin"
export PATH

Relaunch the profile file

source ~/.profile

Verify installation

mvn -version


Check out this post if you want futher details on How to Install Maven on Ubuntu Server


Create the Springboot API

Create the Project Using Maven (CLI)

Spring Boot removes the heavy lifting of setting up a Java project. Instead of using an online tool, we will create our project using Maven from the command line. Open a terminal and run the following command:

mvn archetype:generate -DgroupId=com.example -DartifactId=hello-springboot-api -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

This command creates a new Java project named 
hello-springboot-api with a standard directory structure where:
  • -DgroupId=com.example sets the package structure for the project.
  • -DartifactId=hello-springboot-api names the project folder and the final artifact (JAR file).
  • -DarchetypeArtifactId=maven-archetype-quickstart selects a basic Java project template.
  • -DinteractiveMode=false runs the command without prompting for user input.
This setup ensures a clean, well-structured project ready for Spring Boot integration. Navigate to the project

cd hello-springboot-api

Then open the pom.xml file and add the following:

  • Spring boot plugin

<build>
<plugins>
<!-- Spring Boot Plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.9</version> <!-- Ensure this version matches your Spring Boot version -->
<configuration>
<mainClass>com.example.HelloSpringBootAPI</mainClass>
<layout>JAR</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

  • Spring Boot dependency

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.9</version>
</dependency>
</dependencies>


Write the REST API

Create the main class. Create HelloSpringBootAPI.java inside src/main/java/com/example/:

package com.example;

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

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

Create a REST Controller:

A REST API needs an entry point. In Spring Boot, this is done with a controller. Create a new Java class inside src/main/java/com/example/, create HelloController.java:

package com.example;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class HelloController {

@GetMapping("/hello")
public String sayHello() {
return "Hello World from Springboot!";
}
}

Where:

  • @RestController tells Spring Boot this class handles HTTP requests.
  • @RequestMapping("/") sets the base path for all endpoints in this class.
  • @GetMapping("/hello") maps HTTP GET requests to the sayHello method.
  • The method returns a simple text response: “Hello World from Springboot!”


Create Properties file

Spring Boot uses port 8080 by default. If we want to use another port, we need to modify the pplication.properties or application.ymlfile. For that, create a file called application.yaml in the resources folder (create the resources folder if it does not exist)

vi src/main/resources/application.yml

Add this configuration (let’s say we want to use port 4000)

server:
port: 4000


Build and Run the application

Build the jar file using the maven command

mvn clean package


This generates a JAR file in target/:

ls target/

You should see something like:

hello-springboot-api-1.0.0-SNAPSHOT.jar

Run the application

java -jar target/hello-springboot-api-1.0-SNAPSHOT.jar

The API will start on the port you specified in the properties file


Test the API

Check if it's running locally:

curl http://localhost:4000/hello

If you see 
Hello World from Springboot!, it's working!


Keep the API Running in the Background

If you close the terminal, the app will stop. In a production environment we should run our API as a system service. For that, we need to create a service file

sudo vi /etc/systemd/system/springboot.service

Add this content

[Unit]
Description=Spring Boot Hello World API
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/hello-springboot-api
ExecStart=/usr/bin/java -jar /home/ubuntu/hello-springboot-api/target/hello-springboot-api-1.0-SNAPSHOT.jar
Restart=always

[Install]
WantedBy=multi-user.target

Reload systemd and enable the service

sudo systemctl daemon-reload
sudo systemctl enable springboot
sudo systemctl start springboot

Check the status

sudo systemctl status springboot


Containerize the API

To make our API portable and easy to deploy, we will containerize it using Docker. For that we'll follow the next steps:


Create a Dockerfile

Inside your project root directory, create a file named Dockerfile and add the following content:

FROM openjdk:21-jdk-slim
WORKDIR /app
COPY target/hello-springboot-api-1.0-SNAPSHOT.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]


Build the Docker Image

Run the following command to create a Docker image:

docker build -t hello-springboot-api .


Run the container

Once we've got the image, let's try to run a container from the image with the command

docker run -d -p 4000:4000 hello-springboot-api


Publish the image to Docker Hub

Lastly, let’s make our image available in Docker Hub so that we can download it from any machine. For that, we need to follow these steps:First, login to our Docker Hub account

docker login -u [YOUR_DOCKERHUB_USERNAME]

Tag the image for Docker Hub

docker tag hello-springboot-api [YOUR_DOCKERHUB_USERNAME]/hello-springboot-api

Last step, push the image to Docker Hub:

docker push [YOUR_DOCKERHUB_USERNAME]/hello-springboot-api


With that we can pull and run this image from any Docker host by running

docker run -p 3000:3000 [YOUR_DOCKERHUB_USERNAME]/hello-springboot-api

If you find the error "no matching manifest for linux/amd64 in the manifest list entries" that occurs when the Docker image you are trying to pull does not have a build compatible with your system's architecture(e.g., linux/amd64). 

That's probably because the image was built for a different architecture, most likely because the docker host where you build the image has a different architecture from the one you're trying to run the container. It happened to me when I built the image in my Mac and then try to deploy it on a Linux server.

Try rebuilding your image with multi-platform support:

docker buildx build --platform linux/amd64 -t [YOUR_DOCKERHUB_USERNAME]/hello-springboot-api:latest .
docker push [YOUR_DOCKERHUB_USERNAME]/hello-springboot-api:latest

Previous Post Next Post