Chapter 2: Developing RESTful APIs to Perform CRUD Operations
Activity 3: Connecting the Node application with MongoDB Atlas
Create a subfolder named config and create a db.js file inside config folder.
First, open server folder in the Blogging Application folder by using the keyboard combination Ctrl + O or Ctrl + k from Visual Studio Code and enable the integrated terminal with Ctrl + '. To accept default npm commands, create a package.json file using the following code:
npm init
Install mongoose and import Mongoose.
To install and import Mongoose, first open the db.js and type the following:
npm install mongoose -- save
To import Mongoose, type the following code:
const mongoose = require("mongoose");
Assign a MongoDB connection string to uri and declare the options settings using the following code:
var uri = "mongodb+srv://username:[email protected]/test?retryWrites=true"; const options = { reconnectTries: Number.MAX_VALUE, poolSize: 10, useNewUrlParser:true };)
Connect the application to MongoDB Atlas using the following code:
mongoose.connect(uri, options).then( () => { console.log("Database connection established!"); }, err => { console.log("Error connecting Database instance due to: ", err); } );
Create a folder named api (inside config), a subfolder models (inside api) inside it, and then create an Article.js.
Code for creating the api folder:
mkdir api
Code for creating the models folder:
mkdir models
Code for creating the Article.js file:
touch Article.js
Declare the schema and assign a schema class in the Article.js file. First we import Mongoose using the following code:
const mongoose = require("mongoose");
To declare and assign schema, we use the following code:
const Schema = mongoose.Schema;
To create the schema instance and add schema properties, use the following code:
const BlogSchema = new Schema({ title: { type: String, required: true }, body: String, tag: { type: String, enum: ['POLITICS', 'ECONOMY', 'EDUCATION'] }, createdOn: { type: Date, default: Date.now } });
Create the default Mongoose model.
To create the model, we first call mongoose on model() function to use the default mongoose connection using the following code:
mongoose.model();
Then, pass the model name as the first argument:
mongoose.model("ArticleModel");
Pass the schema name(BlogSchema) as the second argument:
mongoose.model("ArticleModel", BlogSchema);
Make model exportable using the following code:
module.exports = mongoose.model("ArticleModel", BlogSchema);
Create an output.js file and import model using the following code:
const Article = require("../models/Article"); if(Article){ console.log('Model Succesfully Imported'); }
Run the output.js file to confirm whether the model has been imported using the following code:
node output
You will obtain the following output:
Run node db.js inside the config folder to test the connection using the following code:
node db.js
You will obtain the following output:
Activity 4: Creating Controllers for API
Create a folder named controllers as a subfolder inside api, and then open the controllers folder and create an articleListController.js file.
To create the controllers folder, use the following code:
mkdir controllers
To create the articleListController.js, use the following code:
touch articleListController.js
Open the articleListController.js file and import the model using the following code:
const Article = require("../models/Article");
Create a controller to list all articles using the following code:
exports.listAllArticles = (req, res) => { Article.find({}, (err, article) => { if (err) { res.status(500).send(err); } res.status(200).json(article); }); };
Create a controller to create new articles using the following code:
exports.createNewArticle = (req, res) => { let newArticle = new Article(req.body); newArticle.save((err, article) => { if (err) { res.status(500).send(err); } res.status(201).json(article); }); };
Create a controller to read articles using the following code:
exports.readArticle = (req, res) => { Article.findById(req.params.articleid, (err, article) => { if (err) { res.status(500).send(err); } res.status(200).json(article); }); };
Create a controller to update articles using the following code:
exports.updateArticle = (req, res) => { Article.findOneAndUpdate( { _id: req.params.articleid }, req.body, { new: true }, (err, article) => { if (err) { res.status(500).send(err); } res.status(200).json(article); } ); };
Create controller to delete articles using the following code:
exports.deleteArticle = (req, res) => { Article.remove({ _id: req.params.articleid }, (err, article) => { if (err) { res.status(404).send(err); } res.status(200).json({ message: "Article successfully deleted" }); }); };
Activity 5: Creating the API Express Route and Testing a Fully Functional RESTful API
Create a routes folder within the api folder and create an articleListRoutes.js file using the following code:
touch articleListRoutes.js
Open the articleListRoutes.js and create a route function using the following code:
module.exports = function(app) { }
Import controller into route function using the following code:
module.exports = function(app) { var articleList = require('../controllers/articleListController'); }
Create route for get and post requests on /articles using the following code:
module.exports = function(app) { var articleList = require('../controllers/articleListController'); app .route("/articles") .get(articleList.listAllArticles) .post(articleList.createNewArticle); }
Create route for get, put, and delete requests on /articles/:articleid using the following code:
module.exports = function(app) { conts articleList = require('../controllers/articleListController'); app .route("/articles") .get(articleList.listAllArticles) .post(articleList.createNewArticle); app .route("/articles/:articleid") .get(articleList.readArticle) .put(articleList.updateArticle) .delete(articleList.deleteArticle); }
Install Express and the bodyParser module using the integrated command line.
To do this, first open server folder in the Blogging Application folder by using the keyboard combination Ctrl + O or Ctrl + k from VSC and enable the integrated terminal with Ctrl + '. Then, install Express and the bodyparser module using the following code
npm install express – save npm install bodyparser – save
Create a server.js file in the Blogging Application/config folder and then import Express and the body-parser module using the following code:
const express = require("express"); const bodyParser = require("body-parser");
Create the Express application using the express() function:
const app = express();
Define the connection port
const port = process.env.PORT || 3000;
Call the bodyParser middleware on the created Express app using the following code:
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());
Import the db connection:
require("./config/db");
Add CORS (Cross-Origin Resource Sharing) headers to support cross-site HTTP requests
app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); // allow preflight if (req.method === 'OPTIONS') { res.send(200); } else { next(); } });
Import the route using the following code:
conts routes = require('./api/routes/articleListRoutes');
Call route on the Express application using the following code:
routes(app);
Listen to the Express server
app.listen(port, () => { console.log('Server running at http://localhost:${port}'); });
Run server.js inside the server folder to test the connection using the following code:
node server.js
You will obtain the following output:
Open Postman and test the API.
Post a new article to localhost:3000/articles using the POST request as shown:
Get the posted articles by id on localhost:3000/articles/:id using the GET request as shown:
Get all posted articles by id on localhost:3000/articles using GET request as shown:
Update posted articles by id on localhost:3000/articles/:id using the PUT request as shown:
Delete posted articles by id on localhost:3000/articles/:id using DELETE request as shown: