How to set up your first REST app with Node, Express | A guide for beginners
Most of the web services or mobile apps needs to have a database and a service to process all the data collection. The data is stored and processed at 1 place on server. To communicate between web service/app to server we need REST API. We will use NODE JS, NPM and EXPRESS to create a REST API.
Node.js
NodeJS is runtime environment which runs JAVASCRIPT out of browser. We can create HTTP server with it to communicate. From here you can download it.
NPM
NPM is Node Package Manager. It is used to manage dependencies in your project. It is default package manager for Javascript. Click here to download it.
After installation of both node and npm go to command line or terminal and write following commands to check if you installed them properly or not.
> node -v
v12.18.3> npm -v
6.14.6
Express
Express is a web server framework to create REST API’s. It is very widely used when creating API’s in nodejs environment. Remember nodejs is the environment which runs javascript and Express is actual server which will create API’s running on nodejs.
Setting up an Express server
To set up an Express server, first we need to create a directory for the project. Go to folder from command line where you want to create project.
Write the following command and hit enter
> mkdir my-first-app
Jump in the folder by entering the following command
> cd my-first-app
To install any Javascript dependency we need packages.json file.
package.json: this file exists at the root of the node project and holds the metadata of the the project. it is used to handle dependencies, scripts and versions of the app.
Write the following command to create packages.json file. (Parameter -y means default yes to any query by command, you can try without it and it will ask you about project name, description etc.)
> npm init -y
Its time to install Express package. Enter the following command in command line:
> npm i express
Dependencies are installed in node_modules folder, with their meta data in packages.json file.
If you are using VS CODE write code .
in root directory of project to open in editor or you can open the project folder from editor.
We are going to create a file named app.js that will be entry point of our server. In the app.js we are adding necessary dependencies to run our project.
Copy paste the following code in the app.js file:
const express= require('express')
const bodyParser= require('body-parser')const app=express()
const port= 4000app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true;
}))
- Line 1: we need express because it is a server and we need it to run any website or an api
- Line 2: we need to include body-parser because it extracts the data of the upcoming request and exposes it to req.body. we can’t acces the data from req.body without using body-parser middleware.
- Line 3: We’re creating server instance from
express()
- Line 4: I am setting my port to 4000, you can choose any port
- Line 5,6: Using body parser explained in line 2 to parse request parameters as json.
Now we need to make a route/endpoint to look for a Get
request
app.get('/', (req, res )=> {
res.json({app: 'The end point is working'})
})
.get
is simple GET request from url. For now it takes in 2 arguments , req which contains the request info and res which will be used to return api response.'/’
is root URLreq
object represents HTTP request and it can request query string, parameters, body, HTTP headers.res
object represents the response express app send when it gets an HTTP requestres.json
contains the response for the HTTP request in JSON
Now its time to listen to our request on port we defined. Copy it to your code.
app.listen(port, () => {
console.log(`Successful! The server is up and running on port ${port}`)
})
Now in command line, type the following command to start our server.
> node app.js
it will display the following message
Successful! The server is up and running on port 4000
Go to http://localhost:4000 on your browser to see if we if the app is running. You should see the following json in your browser.
{app: 'The end point is working'}
Our express server is running now and It is sending the data that we entered.
Following is the full code for app.js
const express= require('express')
const bodyParser= require('body-parser')const app=express()
const port= 4000app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true;
}))app.get('/', (req, res )=> {
res.json({app: 'The end point is working'})
})app.listen(port, () => {
console.log(`Successful! The server is up and running on port ${port}`)
})
So today we learned how to create a REST API with Express and Node js. We are not finished yet, you deserve some goodies after this great job. If you love to see your code formatted, you are going to love Prettier. Just try it out. I am sure you’ll love it.
I hope you enjoyed learning this. The next article is about setting up environment variables in node js, setting up nodemon and how to push your code on github.
Following is the link to the next article.
For any problem please leave a response and we will try to sort that out.