Before starting our guide let me introduce myself. I am Hammad Hassan a front-end (React) Developer.
Pre-Requisites
I am assuming that you have some basic understanding of JavaScript and have already installed NodeJS too.
- First you have to create a folder and run a command of
npm initto create our package.json file.
Packages we need in this guide.
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");
So all you need is to install these packages by running a following command
npm i express mongoose dotenv body-parser nodemon
- After installing these packages, You have to make an app.js file (You can give any name) and add the following code in it.
const express = require('express');
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Node js");
})
app.listen(3000);
Now, go to your terminal and run node app.js
- Here we are importing our express server package and we are storing it in our
appvariable. - Then
app.getmethod is simply stating our route with second argument of callback function in which we are sending what we want to print on our browser. -
app.listen(3000)is telling us on which port we want to see our server has responded. (Instead of 3000 you can name it whatever u want). - Now, open your browser and hit
http://localhost:3000as url and you should see "Hello from Nodejs" printing up in your browser.
Creating GET and POST API's
Now, when you have learnt how to run the server in NodeJS, let's see how to create the the API's in NodeJS. We will be building an API to GET and POST some random data on to the server.
Models
- Now, create a new folder in your root directory name as
modelsand in this folder create a new file ofPosts.js(you can give any other name you want) and in this file add up the following code.
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
firstname: {
type: String,
required: true,
},
lastname: {
type: String,
required: true,
},
});
module.exports = mongoose.model("Posts", PostSchema);
- Here, in our first line we are importing mongoose (a package, where data will be store).
- Then, we are creating a method, named as
PostSchema(give name of whatever you want) and in this method we are creating an object which is classifying the Schema (content) of our API. - After that we are simply exporting the file so we can use this
PostSchemamethod in our other files (components) too.
Routes
Now comeback to your root directory and create a new folder name as routes and then create a new file in this folder name as posts.js (give whatever name you want) and in this file add up the following code
const express = require("express");
const router = express.Router();
//importing model
const Post = require("../models/Posts");
//Get the posts
router.get("/", async (req, res) => {
try {
const getPosts = await Post.find();
res.json(getPosts);
} catch (error) {
res.json({ message: error });
}
});
//Submit a post
router.post("/", async (req, res) => {
const newPost = new Post({
firstname: req.body.firstname,
lastname: req.body.lastname,
});
try {
const savePost = await newPost.save();
res.json(savePost);
} catch (error) {
res.json({ message: error });
}
});
- In first line we are importing the
expressserver. - Then we need a
routermethod from express server so in second line we are creating a new variable namerouterand storing ourexpress.Router()method in it. - In 3rd line we are importing our Posts.js file from models folder so we can access the schema of our API we had created in that file and storing in the
Postconstant. -
Get Posts: Then, we are declaring a
router.getmethod. In this method we are taking two arguments. First is specifying the route of the API and in second we are declaring a callback with two parameters ofreq(request) andres(response). - After that, we are declaring try/catch statement.
- In
tryblock we are using javascript'sfindmethod to get all the posts we are getting from ourPostmodel (imported above), then converting it into json format and storing it in thegetPostsvariable. In
catchblock, we are catching the error, only iftryblock fails to execute successfully.Submit new Post: To submit a new post to our server, we are using
router.postmethod, here we are also taking two arguments. First is specifying the route of the API and in second we are declaring a callback with two parameters ofreq(request) andres(response).Then, we are making a new variable name as newPost. In this, we are creating an instance of the object we had created in our
Posts.jsfile in (modelsfolder).After that, we are declaring try/catch statement.
In
tryblock we are using javascript'ssavemethod to save our new post in our mongo database from ournewPostvariable we just declared above and converting it into a json format.In
catchblock, we are catching the error, only iftryblock fails to execute successfully.
Here, we are done with our GET and POST API requests. Now, just comeback to your app.js file and add these lines of code.
//Importing routes
const postsRoute = require("./routes/posts");
//Adding middleware
app.use(bodyParser.json());
app.use("/posts", postsRoute);
//connect to DB
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true }, () => {
console.log("Connected to DB");
});
app.listen(8080);
- Here first we are importing the route file.
- Then we are adding
middleware. Amiddlewareis actually a function that can access the request and response objects. -
app.use(bodyParser.json());means whenever route request will execute a bodyParser will run. -
app.use("/posts", postsRoute);means whenever we are on posts routes then this middleware will be called. - Then, we are connecting our server to mongo DB. That topic is a bit lengthy so I haven't covered it here. You can create your free account to access mongoDB here at this: Link.
So, here we go. We have successfully made our first API in NodeJS.
If you like this article then hit a favorite button to give it a big cheers up ❤
Top comments (0)