DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Running Serverless Service as Serverful
  • Low Code Approach for Building a Serverless REST API
  • Keep Your Application Secrets Secret
  • Node.js REST API Frameworks

Trending

  • How Can Developers Drive Innovation by Combining IoT and AI?
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example

Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example

This guide walks through the process of creating a RESTful API that talks to an Amazon Relational Database Service (RDS) instance, complete with examples.

By 
Vijay Panwar user avatar
Vijay Panwar
DZone Core CORE ·
Feb. 19, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
7.8K Views

Join the DZone community and get the full member experience.

Join For Free

Building a REST API to communicate with an RDS database is a fundamental task for many developers, enabling applications to interact with a database over the internet. This article guides you through the process of creating a RESTful API that talks to an Amazon Relational Database Service (RDS) instance, complete with examples. We'll use a popular framework and programming language for this demonstration: Node.js and Express, given their widespread use and support for building web services.

Prerequisites

Before we begin, ensure you have the following:

  • An AWS account and an RDS instance set up: For this example, let's assume we're using a MySQL database, but the approach is similar for other database engines supported by RDS.
  • Node.js and npm (Node Package Manager) installed on your development machine
  • Basic knowledge of JavaScript and SQL

Step 1: Setting Up Your Project

First, create a new directory for your project and initialize a new Node.js application:

PowerShell
 
mkdir my-api

cd my-api

npm init -y


Install Express and the MySQL database connector:

PowerShell
 
npm install express mysql


Step 2: Creating the Database Connection

Create a new file named database.js in your project directory. This file will set up the connection to your RDS database. Replace the placeholders with your actual RDS instance details:

JavaScript
 
const mysql = require('mysql');



const pool = mysql.createPool({

  connectionLimit: 10,

  host: '<RDS_HOST>',

  user: '<RDS_USERNAME>',

  password: '<RDS_PASSWORD>',

  database: '<RDS_DATABASE>'

});



module.exports = pool;


Using a connection pool is recommended for managing multiple concurrent database connections efficiently.

Step 3: Building the REST API

Create a new file named app.js. This file will define your API endpoints and how they interact with the RDS database.

JavaScript
 
const express = require('express');

const pool = require('./database');

const app = express();

const PORT = process.env.PORT || 3000;



app.use(express.json());



// Endpoint to get all items

app.get('/items', (req, res) => {

  pool.query('SELECT * FROM items', (error, results) => {

    if (error) throw error;

    res.status(200).json(results);

  });

});



// Endpoint to add a new item

app.post('/items', (req, res) => {

  const { name, description } = req.body;

  pool.query('INSERT INTO items (name, description) VALUES (?, ?)', [name, description], (error, results) => {

    if (error) throw error;

    res.status(201).send(`Item added with ID: ${results.insertId}`);

  });

});



// Start the server

app.listen(PORT, () => {

  console.log(`Server is running on port ${PORT}`);

});


In this example, we've created two endpoints: one to retrieve all items from the items table and another to add a new item to the table. Ensure you have an items table in your RDS database with at least name and description columns.

Step 4: Running Your API

To start your API, run the following command in your project directory:

PowerShell
 
node app.js


Your API is now running and can interact with your RDS database. You can test the endpoints using tools like Postman or cURL.

Testing the API

To test retrieving items from the database, use:

PowerShell
 
curl http://localhost:3000/items


To test adding a new item:

PowerShell
 
curl -X POST http://localhost:3000/items -H "Content-Type: application/json" -d '{"name": "NewItem", "description": "This is a new item."}'


Conclusion

You've now set up a basic REST API that communicates with an AWS RDS database. This setup is scalable and can be expanded with more complex queries, additional endpoints, and more sophisticated database operations. Remember to secure your API and database connection, especially when deploying your application to production. With these foundations, you're well on your way to integrating AWS RDS databases into your web applications effectively.

API AWS Database connection MySQL Node.js REST

Opinions expressed by DZone contributors are their own.

Related

  • Running Serverless Service as Serverful
  • Low Code Approach for Building a Serverless REST API
  • Keep Your Application Secrets Secret
  • Node.js REST API Frameworks

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!