Building a simple REST API with NodeJS and Express.
Tags: javascript, node, beginners, tutorial
Published: 2022-06-17 05:06:58

Have you been working on front-end technologies and been feeling like you’re missing out something in the whole development process? Well, here’s a good place to start. If you’re been building apps using HTML, CSS and JavaScript, you may want to learn how to build servers that serve content to these front end technologies. For a more interactive in-depth tutorial, you can refer to this YouTube video I made for this article.

**Static files and data.**

First, you’ll need to recognize the difference between serving static assets and serving data. Serving static files is serving your HTML, CSS and JavaScript pages as they are. The reason they’re called static files is because they are not changed by the server nor run, they’re merely sent back as files for your browser to parse through. This is what you’ve most probably been doing without even realizing.

Express is a really cool Node framework that’s designed to help JavaScript developers create servers really quickly. NodeJS may be server side, but it can do a whole lot more than just serve pages and data. NodeJS is a powerful platform that lets you run JavaScript on your shell similar to how you’d run Python.

To get started, head over to https://nodejs.org and download the most stable release of NodeJS. It’s noteworthy to remember not to download the latest version since it may contain bugs and features that could be removed from the final version. Once you download NodeJS binaries, install it into your machine using the instructions provided on the page relative to your platform.

To confirm installation, close any open cmd instance that may be running and start a new instance. Type the following two commands to display the version of Node installed and NPM. NPM is the Node Package Manager and is a tool for installing, uninstalling and maintaining package modules for your app.

```
npm -v
node -v
```

**Initialize a new app.**

There are three ways to initialize a new express app. I’ll go over them briefly explaining each but will only showcase the second one.

The first way is creating the files by hand. A basic Node app contains a .js file and a package.json file. The package.json file contains a couple of properties. First one is name which holds the name of the app, second is version which shows the version of your app, a description of your app, main that points to the entry point of your application. There’s also scripts, that can be run when you need to perform some repetitive tasks, author name, licence, dependencies and devDependencies.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xk0n2zu9afofh50shht1.png)

The package.json describes the app. It is very important. When uploading your app, your dependencies will be listed avoiding duplication and excessive data transfer. An angular 6 app node modules is around 230MB, that will take a lot of time to download or upload. So we omit these modules and just list them instead, then use the package.json to install the modules whenever we need to run the app on another machine. To understand this concept, I’ll explain it better when making an introduction to Git tutorial.

The second way you can initialize an app is using the npm tool. It’s the simplest but not the fastest way. All you have to do is open up your cmd in the folder you want to create your app in and type npm init to interactively create your package.json file.

The third way is the simplest, but a little complex for beginners as it creates files that you will be unfamiliar with especially if you’ve never done NodeJS. It also required you to install the express tool to generate a complete express template and not just the package.json.

```
npm install -g express-generator
```
This installs the express-generator tool that generates a complete express app. As I told you before, npm is a useful tool in installing modules that you might need. But wait a minute, what does the -g flag do? When installing modules to use in JS, you might want to use the modules in that specific app like installing mongoose so you can use mongoose methods to query data from your MongoDB instance. But then, you can also install modules/tools that you can use anywhere on your computer. These tools are available on the command line but only available if you install them globally. The -g flags specifies that you’re installing the module globally to use anywhere within your computer. Not using the -g flag will install the tool/module into that specific folder and will not be available outside that scope.

**Installing Express.**

Please use the second method to generate a package.json file almost similar to the one pictured above. Second thing we want to do is install Express into our app. Note, we aren’t going to install express globally as we need to use it in this specific folder/app. Use the command below to install Express.

```
npm install express --save
```

The save flag is used to edit your package.json file and add express as a dependency. After the installation is complete, open up your package.json to see express listed as a dependency. With this, you could send just your code and package.json file to a friend and request them to use npm to install the dependencies on their computer saving you some amount of data. To install, your friend will have to open up cmd inside the app folder and use the command npm install.

```
var express = require("express");
var app = express();
app.listen(3000, () => {
 console.log("Server running on port 3000");
});

```

Congrats! You just made your first useless express server! So let’s go through the code and learn why our server is useless and why it’s not implementing the REST protocol yet. The first line requires express and uses the express variable to represent it. The second line initialized express using the brackets which initializes an express server and puts the initialized server into the variable app. So now whenever we want to use our express server, we would need to use the app variable which represents our app! We then set our app to listen to port 3000 and create a callback function that says our server is running on port 3000.

Your app will now be accessible using http://localhost:3000, but hitting that endpoint now won’t get you anything since you haven’t configured your server to listen to any events.

**Setting request handlers.**

A server receives requests, processes them and returns a response. So you need to use routes to handle this requests. The requests have three major types, a GET request that get’s data, a POST request that sends data securely, a PUT request that updates data and a DELETE request that deletes data.

Let’s create a simple GET request that returns a list of users. Under var app = express(), write down the following code.

```
app.get("/url", (req, res, next) => {
 res.json(["Tony","Lisa","Michael","Ginger","Food"]);
});
```

This simple function makes the express app to use the url handle “/url” to trigger the callback that follows it. The callback accepts three parameters, req is the request body and carries information about the request. The res is the response body and is used to handle response functions like .render() to render templates and .json() to return json data.

**Running your app.**

To run your app, use the command below.

```
node app.js
```

This is what your cmd should look like after running this command.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y47g437ye24ojhr18762.png)

This means our app is now successfully running on port 3000. To view our data, open up your browser and enter http://localhost:3000/url. You’ll expect to see something like this on your browser.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lcw9rso0oafdpxy4p2ua.png)

The data returned is an array of string. This is raw data.

**How it all fits as a REST based API.**
  
You might be wondering where the REST attribute comes in. REST stands for REpresentational State Transfer. This means there is no state between the client and the server. There are no webpages served to be parsed, just data. And this gives you all the freedom you need. All you need to do is write some logic on a specific URL that connects to a database, uses it’s logic to process the data and return it in JSON format. Your client can now be an Android app made in Java, or a Windows desktop app made in C# or an Arduino project.

This is the whole point of using REST, it makes the connection stateless therefore any client that utilizes the HTTP protocol can access this data. Now you can iterate through the data and display it anywhere you want.

Unbelievable as it seems, this is a basic REST based API. You make a request to a specific endpoint and get data back in a stateless manner. Very simply put. No complexity here. This is the most basic API you’ll need to do to understand how REST APIs work. In future tutorials, I’ll show you how to connect to a database, query data and return the data using REST protocol.

Below is an image of my PostMan app querying the same server.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g7v8pcwvgeo5lir5bjro.png)

So as you can see, our server isn’t restricted to browsers only. You can use Native apps and IoT devices as well to get data as long as it implements the HTTP protocol.

If Express is really exciting for you, you might wonder where to use this knowledge. Well, there are a number of ways I’d suggest. Express is a backend framework, you might want to expand to the frontend as well after learning how the backend works, that would make you a full stack developer that can develop both the technology that generates and stores data and the one that consumes and displays the data. The MEAN Stack would be a great model to learn with, although I must admit it is more of preference. The best thing about the MEAN Stack is the use of JavaScript syntax across your entire product, from frontend, backend to even the database. MongoDB saves data in BJSON which looks strikingly identical to JSON making it super easy to learn. If you choose to learn the MEAN Stack, here is a great article I made that get you started in a couple of minutes.

Thanks for going through my article, hope it helped you.

 
Socials:

Github: https://github.com/Dinesh-Talwadker