How To Create an Express Js REST Api

All you need to learn to create a basic rest API with expressjs.
If you like this type of posts follow me :) I’ll appreciate it too much ❤.

YJDev
3 min readDec 2, 2021

What is a REST API?

A REST API, or RESTful API, is an application programming interface (API or Web API) that conforms to the limits of the REST architecture and enables interaction with RESTful web services.
https://www.redhat.com/es/topics/api/what-is-a-rest-api

Let’s do it!

First, you need to create a directory where you prefer and type on the command line npm init -y

> cd \user\Documents
> mkdir api-example
> npm init -y

After that you should have a package.json file.

Now we can create an index.js file and start downloading our dependencies for the project.

In this case we only need nodemon and expressjs.

nodemon -> for refreshing the server everytime we make a file edit

expressjs -> for creating the server

> touch index.js
> npm install express
> npm install nodemon -D

The -D on the npm install nodemon is used for installing a dev dependencie, it means that it only be used for developing purposes.

Then, to config our npm command we need to edit our package.json file on the “scripts” key:

"scripts": {
"dev": "nodemon index.js",
"start": "node index.js"
},

Now we can start coding. 🎉

To use express we need to import it on our index file and create and express app. It should look like these:

Also, if you want to support JSON on your request yo no to add the json middleware.

const express = require("express");
const app = express();
// For supporting json
app.use(express.json());

After that we can create all endpoints we want, you should follow this structure:

GET Method

app.get('/', function (req, res) {
res.send('Hello World!');
});

POST Method

app.post('/', function (req, res) {
res.send('A POST request');
});

PUT Method

app.put('/', function (req, res) {
res.send('A PUT request');
});

DELETE Method

app.delete('/', function (req, res) {
res.send('A DELETE request');
});

In this case we will only use the GET request.

Finally, let’s create the web server on our localhost with the 3000 port:

const PORT = 3000;
const server = app.listen(PORT, () => {
const port = server.address().port;
console.log("Listening at http://localhost:" + port + "/");
});

Well done! we have created a REST API 👏🎉

To see your project working you need to go to the command line on the project root and type:

//You need to navigate to your project root
>
npm run dev

After that you can open your browser and navigate to http://localhost:3000

See you in the next post :D

Do you want to become a Front End Developer?

Follow this 2021 Front End Developer Road Map

Follow me 👇
Twitter: https://twitter.com/YJDev_

Medium: https://yjdev.medium.com/

Any suggestions? Leave your comment :)

--

--

YJDev

Software and Android Developer. Writing in English and Spanish for helping devs.