Building An Express App Using Node JS

Building An Express App Using Node JS

Altaf Shaikh

Published on Mar 29, 2021

16 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hey there!!

Welcome to this blog post in this blog we will learn how to build a Simple Hello World Express Application using Node JS, previously in this series here we learn the fundamentals of Node JS, So if you are not familiar with Node JS and new to it then kindly check out the series to proceed further.

Later on, we will build a Full Fledge Express Backend using the tech stack Node JS, MongoDB, and Express. So stay tuned and follow along with me : )

You can Watch My Hands-On Workshop on Building A TODO REST API BAckend

So let's Get Started!!

What is Express?

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

  • Write handlers for requests with different HTTP verbs at different URL paths (routes).
  • Integrate with view rendering engines in order to generate responses by inserting data into templates.
  • Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response.
  • Add additional request processing middleware at any point within the request handling pipeline.

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more.

You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

Now before proceeding to build the Express App let's understand the concept of API and REST APIs.

What is an API?

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other.

To explain this better, let us take a familiar example.

Imagine you're sitting at a table in a restaurant with a menu of choices to order from. The kitchen is the part of the system that will prepare your order. What is missing is the critical link to communicate your order to the kitchen and deliver your food back to your table. That's where the waiter or API comes in. The waiter is the messenger -- or API -- that takes your request or order and tells the kitchen -- the system -- what to do. Then the waiter delivers the response back to you; in this case, it is the food.

api example.png

Technically:

When you use an application on your mobile phone, the application connects to the Internet and sends data to a server. The server then retrieves that data, interprets it, performs the necessary actions, and sends it back to your phone. The application then interprets that data and presents you with the information you wanted in a readable way. This is what an API is - all of this happens via API.

api-example-technical.png

What is Rest API?

Let's say you're trying to find videos about Batman on Youtube. You open up Youtube, type "Batman" into a search field, hit enter, and you see a list of videos about Batman. A REST API works in a similar way. You search for something, and you get a list of results back from the service you're requesting from.

rest-api.png

An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.

REST determines how the API looks like. It stands for "Representational State Transfer". It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL.

Each URL is called a request while the data sent back to you is called a response.

The Anatomy Of A Request

It's important to know that a request is made up of four things:

  • The endpoint
  • The method
  • The headers
  • The data (or body)

The endpoint (or route) is the url you request for. It follows this structure:

 root-endpoint/?

The root-endpoint is the starting point of the API you're requesting from. The root-endpoint of Github's API is https://api.github.com while the root-endpoint Twitter's API is https://api.twitter.com, and Hashnode's root-endpoint API is https://api.hashnode.com/

The path determines the resource you're requesting for. Think of it like an automatic answering machine that asks you to press 1 for a service, press 2 for another service, 3 for yet another service and so on.

The Method

The method is the type of request you send to the server. You can choose from these five types below:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

These methods provide meaning for the request you're making. They are used to perform four possible actions: Create, Read, Update and Delete (CRUD).

MethodsRequest Meaning
GETThis request is used to get a resource from a server. If you perform a GET request, the server looks for the data you requested and sends it back to you. In other words, a GET request performs a READ operation. This is the default request method.
POSTThis request is used to create a new resource on a server. If you perform a POST request, the server creates a new entry in the database and tells you whether the creation is successful. In other words, a POST request performs an CREATE operation.
PUT and PATCHThese two requests are used to update a resource on a server. If you perform a PUT or PATCH request, the server updates an entry in the database and tells you whether the update is successful. In other words, a PUT or PATCH request performs an UPDATE operation.
DELETEThis request is used to delete a resource from a server. If you perform a DELETE request, the server deletes an entry in the database and tells you whether the deletion is successful. In other words, a DELETE request performs a DELETE operation.

The Purpose of APIs and REST APIs

When We talk about API and REST APIs we are talking about the DATA and NOT about the HTML pages from the Server.

  • Server generally serves you or returns you the HTML (UI- Look Of the Webpage) and your browser knows how to render the HTML onto the screen.

  • But you can also allow your server to send only DATA - no HTML. The Data sent is in the form of JSON or either XML.

  • With Modern Web architectures like JAMstack we are separating the Data and the UI.

  • So we have the data on the servers like Django, Express JS, Spring, etc. Which exposes API Endpoints to Access the Data. These are commonly known as Backend Servers

  • And we use Frontend frameworks and libraries like REACT, VUE, Plain Javascript, and Angular to create the UI by using the API Endpoints made available to us by backend server to Fetch the Data and create the HTML Markup so that your Browser can renders the HTML onto the screen as your browser only understand HTML (Structure the webpage), CSS (beautify's your webpage) and Javascript (to program the behavior of web pages)

  • These allows no dependencies on creating the UI and you can use the data the way you want to and you can scale your system easily.

  • These gave rise to the CMS (Content Management System), Large Distributed Web Applications systems, Microservices architecture, etc.

Routes vs Endpoints

Endpoints are functions available through the API. This can be things like retrieving the posts, updating a post, or deleting a comment. Endpoints perform a specific function, taking some number of parameters and returning data to the client.

A route is the “name” you use to access endpoints, used in the URL. A route can have multiple endpoints associated with it, and which is used depends on the HTTP verb.

For example, with the URL teachmebro.com/post/javascript-asynchronous..:

The “route” is post/javascript-asynchronous-programming-and-callbacks – The route doesn’t include domain name because domain name is the base path for the API itself.

Routes

Routes in the REST API are represented by URIs. The route itself is what is tacked onto the end of https://ourawesomesite.com/wp-json. The index route for the API is '/' which is why https://ourawesomesite.com/wp-json/ returns all of the available information for the API. All routes should be built onto this route, the wp-json portion can be changed, but in general, it is advised to keep it the same.

We want to make sure that our routes are unique. For instance we could have a route for books like this: /books. Our books route would now live at https://ourawesomesite.com/wp-json/books. However, this is not a good practice as we would end up polluting potential routes for the API. What if another plugin we wanted to register a books route as well? We would be in big trouble in that case, as the two routes would conflict with each other and only one could be used.

Building The Express Application

Let's learn how to start developing and using the Express Library. To start with, you should have the Node and the npm (node package manager) installed. If you don't already have these, go to the Node setup to install the node on your local system. Confirm that node and npm are installed by running the following commands in your terminal.

node --version

npm --version

You should get an output similar to the following.

v5.0.0

3.5.2

Now that we have Node and npm setup lets start,

Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project.

Step 1 - Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it -

Step 2 - Now to create the package.json file using npm, use the following code.

npm init -y

Step 3 - Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command -

npm install --save express

Tip - The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us.

This is all we need to start development using the Express Library. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command -

npm install -g nodemon

We have set up the development, now it is time to start developing our first app using Express. Create a new file called app.js and type the following in it.

// import module
var express = require('express');

// initialize express app
var app = express();

// accept request and send a response
app.get('/', function(req, res){

   res.send("Hello world from server!");

});

// listen on PORT 3000 for incoming HTTP request
app.listen(3000);

Save the file, go to your terminal and type the following.

nodemon app.js

This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following demo.

Hurrayy!! We learned the fundamentals of APIs and learned how to use the Express Library in Node JS to build the Backend Application.

If you learned something new from this article then do like this article to make me feel good and to motivate me to write more : D : D

 
Share this