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 init
to 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
app
variable. - Then
app.get
method 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:3000
as 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
models
and 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
PostSchema
method 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
express
server. - Then we need a
router
method from express server so in second line we are creating a new variable namerouter
and 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
Post
constant. -
Get Posts: Then, we are declaring a
router.get
method. 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
try
block we are using javascript'sfind
method to get all the posts we are getting from ourPost
model (imported above), then converting it into json format and storing it in thegetPosts
variable. In
catch
block, we are catching the error, only iftry
block fails to execute successfully.Submit new Post: To submit a new post to our server, we are using
router.post
method, 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.js
file in (models
folder).After that, we are declaring try/catch statement.
In
try
block we are using javascript'ssave
method to save our new post in our mongo database from ournewPost
variable we just declared above and converting it into a json format.In
catch
block, we are catching the error, only iftry
block 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
. Amiddleware
is 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)