# Spring Boot CRUD API, Amazon RDS for MySQL, AWS Secrets Manager - example

There are many articles on how to build a real-world Spring Boot CRUD REST API or Application with MySQL as a 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 the 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://cdn.hashnode.com/res/hashnode/image/upload/v1654950648381/j69jUp0SZ.png align="left")

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://cdn.hashnode.com/res/hashnode/image/upload/v1654950650464/2daMUvJDQ.png align="left")

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** -&gt; **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://cdn.hashnode.com/res/hashnode/image/upload/v1654950652389/VFd3mo8P6.png align="left")

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://cdn.hashnode.com/res/hashnode/image/upload/v1654950654073/-VPAMGIJz.png align="left")

## 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.

%[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

* At 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://cdn.hashnode.com/res/hashnode/image/upload/v1654950655651/ReRIj5E-p.png align="left")

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://cdn.hashnode.com/res/hashnode/image/upload/v1654950657287/bfXP7WsPb.png align="left")

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

![GET request - API](https://cdn.hashnode.com/res/hashnode/image/upload/v1654950659023/uU1MwkrPY.png align="left")

Congratulations! 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 the 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 the IAM console if needed
    
* Delete the Secret in the AWS Secrets Manager console
    
* Delete the MySQL database in the 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!
