🛢Connecting Your REST API to a Database (MySQL and MongoDB)

Once you have your API endpoints, it's time to make them dynamic by connecting to a database. In this blog, you'll learn how to integrate both MySQL and MongoDB into your Node.js or PHP backend.


🧩 Why Use a Database?

Databases allow you to persist data across sessions. For example, when a user adds a task, it should be saved so they can access it later.


🛠️ Node.js + MongoDB

Install Mongoose

npm install mongoose

Connect & Define Schema

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/tasksDB', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const taskSchema = new mongoose.Schema({
  title: String,
  completed: Boolean
});

const Task = mongoose.model('Task', taskSchema);

Create & Read

app.post('/tasks', async (req, res) => {
  const task = new Task(req.body);
  await task.save();
  res.status(201).send('Task added');
});

app.get('/tasks', async (req, res) => {
  const tasks = await Task.find();
  res.json(tasks);
});

🛠️ PHP + MySQL

Connect to Database

$mysqli = new mysqli("localhost", "user", "pass", "task_db");

Insert and Fetch

// POST: Add task
$data = json_decode(file_get_contents("php://input"), true);
$stmt = $mysqli->prepare("INSERT INTO tasks (title, completed) VALUES (?, ?)");
$stmt->bind_param("si", $data['title'], $data['completed']);
$stmt->execute();

// GET: Fetch tasks
$result = $mysqli->query("SELECT * FROM tasks");
$tasks = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($tasks);

✅ Summary

  • Use MongoDB with Node.js for a NoSQL approach.
  • Use MySQL with PHP for structured data storage.
  • Always sanitize inputs to avoid injection attacks.

Next up: Build a full CRUD API!

Leave a Reply

Your email address will not be published. Required fields are marked *