Building a Todo List API with a Database
To demonstrate the concepts discussed, let’s create a simple API using Node.js and MongoDB. We’ll create an endpoint /todos
that retrieves a list of todos from a MongoDB database.
First, we need to set up our Node.js project and install the necessary dependencies:
mkdir todo-api
cd todo-api
npm init -y
npm install express mongoose
Explanation:
mkdir todo-api
: This creates a new directory namedtodo-api
where our project will be located.cd todo-api
: This changes the current directory totodo-api
so we can work inside it.npm init -y
: This initializes a new Node.js project in thetodo-api
directory with default settings, creating apackage.json
file.npm install express mongoose
: This installs theexpress
framework andmongoose
library as project dependencies. Express is used for handling HTTP requests and routes, while Mongoose simplifies interaction with MongoDB, our database choice for this project.
Next, let’s create our index.js
file:
const express = require('express');
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/todos', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Create a schema for our todo collection
const todoSchema = new mongoose.Schema({
title: String,
completed: Boolean,
});
// Create a model based on the schema
const Todo = mongoose.model('Todo', todoSchema);
// Create an Express app
const app = express();
// Define a route to fetch all todos
app.get('/todos', async (req, res) => {
try {
// Retrieve all todos from the database
const todos = await Todo.find();
res.json(todos); // Send the todos as a JSON response
} catch (err) {
res.status(500).json({ error: 'Internal Server Error' }); // Handle any errors
}
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
- It requires the
express
andmongoose
modules for handling HTTP requests and interacting with MongoDB, respectively. - It connects to a MongoDB database named
todos
running on the default port27017
. - It defines a schema for the
todo
collection withtitle
(String) andcompleted
(Boolean) fields. - It creates a model
Todo
based on the schema, allowing us to perform CRUD operations on thetodo
collection. - It creates an Express app and defines a GET route
/todos
to fetch all todos from the database and return them as a JSON response. - It starts the server on port
3000
and logs a message to the console indicating that the server is running.
How Does an API Work with A Database?
APIs define methods and protocols for accessing and exchanging data, allowing developers to integrate various services and functionalities into their applications seamlessly. On the other hand, databases store data in a structured manner, enabling efficient storage, retrieval, and management of information.
Together, APIs and databases form the backbone of modern software systems, facilitating communication and data management.
Understanding how APIs work with databases is crucial for developers building robust and scalable applications. In this article, We will learn about How Does an API Work with A Database by Understanding APIs and Databases along with an Example of Building a Todo List API with a Database and so on