Java Spring Boot:
Spring Boot is an open-source Java framework used to create a Micro Service. Spring boot is developed by Pivotal Team, and it provides a faster way to set up and an easier, configure, and run both simple and web-based applications. It is a combination of Spring Framework and Embedded Servers. The main goal of Spring Boot is to reduce development, unit test, and integration test time and in Spring Boot, there is no requirement for XML configuration.
RESTful Web Services:
REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of HTTP protocol. It uses the concepts and verbs already present in HTTP to develop web services. We can build REST web services using many representations, including both XML and JSON, although JSON is the more popular option. An important thing to consider is that REST is not a standard but a style whose purpose is to constrain our architecture to a client-server architecture and is designed to use stateless communication protocols like HTTP.
AWS Elastic Beanstalk:
Elastic Beanstalk is a service for deploying and scaling web applications and services. Upload your code and Elastic Beanstalk automatically handles the deployment—from capacity provisioning, load balancing, and auto scaling to application health monitoring. Elastic Beanstalk is a Platform As A Service (PAAS) as it allows users to directly use a pre-configured server for their application.
Prerequisites:
1. Java 17
2. AWS Account
3. Eclipse/IntelliJ IDE with Maven
4. Postman or any client
Steps to create Spring Boot Mock Rest API
Create a Spring Boot Application using Maven or Spring Initializr - https://start.spring.io/
2. Created project framework will look this
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
</parent>
<groupId>com.example</groupId>
<artifactId>demoAWS</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demoAWS</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- Spring Boot Application.java
package com.example.demoAWS;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MockAwsApplication {
public static void main(String[] args) {
SpringApplication.run(MockAwsApplication.class, args);
}
}
3. In a Spring Boot REST API, DTOs are used to define the structure of request and response payloads, ensuring data validation and transformation between the client and server.
Create DTOs for Login and Physician module request and response payloads.
LoginRequest.java
package com.example.demoAWS.dto;
public record LoginRequest(String username, String password) {}
LoginResponse.java
package com.example.demoAWS.dto;
import java.util.List;
public record LoginResponse(String username, Integer userId, String token, List<String> roles) {}
PhysicianRequest.java
package com.example.demoAWS.dto;
public record PhysicianRequest(String firstname, String lastname, String email, String authBearer
) {}
PhysicianResponse.java
package com.example.demoAWS.dto;
public record PhysicianResponse(String firstname, String lastname, String email, int physicianId, String password) {
}
4. In Spring Boot, a REST controller is a class that handles incoming HTTP requests and sends back responses in a RESTful manner. It's annotated with @RestController, which combines the functionality of @Controller and @ResponseBody.
Create MockController.java to handle our HTTP request
package com.example.demoAWS.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demoAWS.dto.LoginRequest;
import com.example.demoAWS.dto.LoginResponse;
import com.example.demoAWS.dto.PhysicianRequest;
import com.example.demoAWS.dto.PhysicianResponse;
@RestController
public class MockController {
@PostMapping("/login")
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginReq) {
return ResponseEntity
.ok(new LoginResponse(loginReq.username(), USER_ID_SEQ++, generateToken(), List.of("User_admin")));
}
@PostMapping("/createPhysician")
public ResponseEntity<PhysicianResponse> createPhysician(@RequestBody PhysicianRequest physicianReq) {
PhysicianResponse phyres = new PhysicianResponse(physicianReq.firstname(), physicianReq.lastname(),
physicianReq.email(), PHYSICIAN_ID_SEQ++, generatePassword(8));
PHYSICIAN_MAP.put(phyres.physicianId(), phyres);
return ResponseEntity.status(201).body(phyres);
}
@GetMapping("/getPhysician/{physicianId}")
public ResponseEntity<?> getPhysicianbyId(@PathVariable int physicianId) {
PhysicianResponse res = PHYSICIAN_MAP.get(physicianId);
return ResponseEntity.ok(res);
}
@GetMapping("/getAllPhysicians")
public ResponseEntity<?> getAllPhysicians() {
return ResponseEntity.ok(PHYSICIAN_MAP.values());
}
@DeleteMapping("/deletePhysician/{physicianId}")
public String deletePhysician(@PathVariable int physicianId) {
PHYSICIAN_MAP.remove(physicianId);
return "Deleted physicianId: " + physicianId;
}
public static String generateToken() {
return UUID.randomUUID().toString();
}
public static String generatePassword(int length) {
RandomGenerator random = RandomGeneratorFactory.of("L64X128MixRandom").create();
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
StringBuilder password = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length());
password.append(characters.charAt(index));
}
return password.toString();
}
private static int USER_ID_SEQ = 1;
private static int PHYSICIAN_ID_SEQ = 1;
private static Map<Integer, PhysicianResponse> PHYSICIAN_MAP = new HashMap<>();
}
spring.application.name=demoAWS
server.port=9090
6. Final Project Framework structure,
7. Run MockAwsApplication.java. Now, Our Spring Boot application is running in Tomcat Server on localhost:9090
8. To deploy our application to AWS, we need to build the jar file.
In pom.xml, Run as -> Maven install to build the application.
9. Once build is success, our application demoAWS-0.0.1-SNAPSHOT.jar file created under target folder.
Steps to deploy Spring Boot Mock Rest API on AWS Elastic Beanstalk
An application is a top-level container in Elastic Beanstalk that contains one or more application environments.
- Open AWS Console and Create Application and Elastic Beanstalk Application.
- In Configure Environment, Provide Application name
2. In Platform, Select Java from dropdown,
3. In Application Code, Select Upload your code, enter Version label and upload application jar file from local and
click next
4. In Configure service access, select Use an existing service role and select aws-elasticbeanstalk-service-role from dropdown. For EC2 key pair, select your EC2 and EC2 instance profile and click Skip to review
5. In Review page, under Configure updates, monitoring, and logging and click Edit,
In Environment properties, Click Add environment property and set JAVA_HOME , SERVER_PORT values,
JAVA_HOME /usr/lib/jav/java
SERVER_PORT 5000
Now, Click Next.
Click Submit.
6. Elastic Beanstalk will launch your application environment. This will take few minutes , Once successfully launched, the dashboard will look like this,
Click the link under Domain, our mock API will open in the browser. Now, Our API is ready for testing.
Testing our mock Rest API in Postman
Provide AWS Domain url with valid endpoint and start unit testing in your environment.
Our Post, Get and Delete methods are working as expected in Postman.
Successfully, We deployed our Spring Boot mock Rest API into AWS EBS for testing environment.
Happy Learning!!