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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Transforming Your Node.js REST API into an AI-Ready MCP Server
  • Implementing Budget Policies and Budget Limits on Databricks
  • Running Serverless Service as Serverful
  • Low Code Approach for Building a Serverless REST API

Trending

  • Time to First Token: How Long Does It Take for a Large Model to Start Responding?
  • Tracing Dangerous Python Code Paths With rce-path
  • Three Measured Outcomes of Manually Scaling Fleet in Prod
  • Prompt Caching for LLMs, Part 2: Semantic Caching in Production

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Feb. 19, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Transforming Your Node.js REST API into an AI-Ready MCP Server
  • Implementing Budget Policies and Budget Limits on Databricks
  • Running Serverless Service as Serverful
  • Low Code Approach for Building a Serverless REST API

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook