Spring Boot CRUD API, Amazon RDS for MySQL, AWS Secrets Manager - example
Tags: beginners, aws, mysql, java
Published: 2022-06-11 12:04:23

There are many articles on how to build a real world Spring Boot CRUD REST API or Application with MySQL as Relational Database. In this post, we are not only going to show how to create a Spring Boot CRUD operations API, but we will also dive deeper into using a remote MySQL DB provided by [Amazon RDS](https://aws.amazon.com/rds/). To top it off, we'll see how to securely manage database credentials through [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/).

## Prerequisites

1\. Have an [AWS account](https://console.aws.amazon.com/console/home)

2\. Know how to configure AWS credentials on the local machine

3\. Be familiar with Spring Boot project


## Create MySQL DB instance using Amazon RDS
In this section, you will step-by-step create a MySQL DB instance using the AWS Management Console. At the end of this section you will have an online database ready to use :muscle:.

1\. Go to [AWS Management Console](https://console.aws.amazon.com/console/home) and sign in.

2\. Choose the AWS Region you want and type _RDS_ in the **Search for services** ... search bar and select it.

![AWS Management Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zgd16nyx7gmgm1x6mwp.png)

3\. [RDS console](https://console.aws.amazon.com/rds/) will open. In the navigation pane, choose **Databases** then **Create database** on the top-right of the **Databases** table to open the below page :

![Amazon RDS console : create database page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y617bk0ofb812sb85ldy.png)
 
4\. **Choose a database creation method** : _Standard create_ 

5\. **Engine options** : _MySQL_

6\. **Templates** : _Free tier_

7\. **DB instance identifier** : _mydemodb_

8\. **Master username** : _admin_

9\. **Master password** & **Confirm password** : _adminadmin_

10\. **DB instance class** : _db.t2.micro_

11\. **Public access** : _Yes_ 

12\. Click **Additional configuration** -> **Initial database name** : _demodb_
> _Step 12 will make RDS create a database named **demodb**_

13\. Leave all other options as is and then click **Create database**

Once the database is created, click on mydemodb in the **Databases** list to view its summary. We can use it at this point with basic information such as: _endpoint, port, principal user name, principal password and database_.


## Create AWS Secrets to protect DB credentials

We have created the MySQL database, now, to avoid hard coding  its credentials in our Spring Boot project, we'll use AWS proven service that helps easily rotate, manage, and retrieve database credentials, API keys, and other secrets through their lifecycle : [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/). 

1\. Once more, sign in to the AWS Management Console and open the Amazon Secrets Manager console [here](https://console.aws.amazon.com/secretsmanager/) then make sure you choose the same AWS Region as that of the MySQL database

2\. In the navigation pane, choose **Secrets** then **Store a new secret** on the top-right of the **Secrets** table to open the below page:

![AWS Secrets Manager console : store a new secret](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/drpf0w7do81s8s3op7qh.png)

3\. **Secret type** : _Credentials for Amazon RDS database_

4\. **User name** : _admin_

5\. **Password** : _adminadmin_

> _For steps 4 and 5, use the same username and password as the database_.

6\. **Database** : choose _mydemodb_ DB instance and click **Next**

7\. **Secret name** : _demodb/dev_, leave default options and click **Next**

8\. Leave all the default options again and click **Next** to go to the **Review** page.

9\. Click **Store**

10\. Once the Secret is created, click on it to preview its details.

![AWS Secret details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pv4wcrhbccavnpv0vmm5.png)


## Create a programmatic IAM user

> _**Note**: If you have already configured AWS credentials on your machine locally, please skip this entire section and go to **Create Spring Boot**._

In order to user AWS Secrets we've created, we need an AWS IAM user with **_AdministratorAccess_** policy. Please follow [these steps](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config) to create an Admin IAM User and configure your local machine.


## Create a Spring Boot Project
For this lab, clone the project [here](https://github.com/wilkom2009/docker-demo2.git) and open it in your IDE, then follow the explanations.

1\. Let's explore some core dependencies necessary for the project in the _pom.xml_ file :

```xml
<!-- Spring Boot JPA dependency -->
<dependency>		 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL dependency -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- AWS Secrets Manager dependency -->
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-secretsmanager</artifactId>
    <version>1.11.355 </version>
</dependency>
```

2\. The **SecretValue** Java class in _utils_ package
**SecretValue.java** class aims to map the Secret value key/value data (DB credentials) retrieved from AWS Secrets Manager into a java object for use in the data source. 

```java
public class SecretValue {
    private String username;
    private String password;
    private String engine;
    private String host;
    private String port;
    private String dbname;
    private String dbInstanceIdentifier;

    // Add Getters & Setters
}
```

3\. The **JavaConfig.java** class
In this class, the retrieval of the secret value we  created in AWS Secrets Manager is implemented.
{% embed https://gist.github.com/wilkom2009/d16f0e62d7f01170d04f2a0b95106bb8 %}

> Line 41: the secret name created in AWS Secrets Manager
> Line 42: the AWS Region where the secret is created_


## Test the REST API
Our REST API is ready, in this section, we'll test it with Postman.

1\. Build the project

- In the root of the project, run the following command line:
`mvn clean package`

- If everything is configured correctly, the result should look like this:

![Build success](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ol0jr74au8hc7t11c6sc.png)

2\. Run the project
Please run the API and make the following API call:

- Open Postman

- Make a POST request : localhost:8080/api/team/2022

![POST request - API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6ky9wfd6qapo2uxx6by.png)

- Make a GET request : localhost:8080/api/team/2022

![GET request - API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8adhgzlrfsn7tcbi54ok.png)

Congratulations :clap::clap::tada:! You are almost at the end of the project. 


## Bonus : Deploy the CRUD REST API on AWS Fargate
As in production we need to deploy our REST API, I suggest you try creating a docker container for the API, pushing it to the Docker hub and deploying it to Amazon ECS using AWS Fargate deployment option. Please follow these simple steps outlined in this [article.](https://dev.to/aws-builders/how-to-easily-deploy-a-spring-boot-application-on-aws-fargate-38nh).
> _**Note**: To allow ECS Task to access the AWS Secrets Manager service, make sure you have **AmazonECSTaskExecutionRolePolicy** and **SecretsManagerReadWrite** as Permissions policies for the **Task role**._

## Cleanups
After testing the REST API locally and remotely, sign in to the AWS Management Console and perform cleanups:

- Delete the IAM user we created in IAM console if needed

- Delete the Secret in AWS Secrets Manager console

- Delete MySQL database in RDS console.


In this post, we showed how to create a Spring Boot CRUD REST API and how to manage Spring Boot MySQL connection. We also saw how to use AWS Secrets Manager in Spring Boot to protect database credentials in your REST API code. Your suggestions are welcome. Thanks for reading :pray:!