Create your REST API with Express part 1

Today I wanted to create my own REST API using express, some friends told me about Express is allow create stateless APIS quick and easy and support HTTP verbs to able communicate with our resources getting the responses in JSON format.


This is what you’re going to need in order to follow along with this example:

– Node.js and npm installed on your machine; — A basic understanding of Javascript;

Once that stuff is out of the way, we can proceed.

Configure my project and Install express

I will to configure my project with Node and install express and also use nodemon which allows run node code and refresh for every change, to do so, head over to the terminal and run this:

npm install -g nodemon
npm init -y
npm install -s express

Create the server to listen to the requests.

Next point I create a file named expressapp.js, import express, create const which store our express instance, and call the method “listen” to start our server and get requests from the client.

const express = require("express")
const app = express()
const port = 3009;
app.listen(port, function () {
console.log("server is running.")

Using nodemon for run our app now, if you visit http://localhost:3009 you should see the message server is running

danys-imac:maincare dany$ nodemon app.js
[nodemon] 1.18.4 [nodemon] to restart at any time, enter rs
[nodemon] watching: *.*
[nodemon] starting node app.js server is running.

Using the middleware use for define routes and return data.

Now I will call the method use and send 2 parameters the path and a function, the function has 3 parameters req, res and next.

The path is the URL for my API like api/users (req, res, next).

(Req) is the request object sent by the client for our API.

(Res) is the server response send the information to the client.

(Next) Allow the request to continue to another middleware if exist to handle the request.

I can send one simple object like an array [] or {} object to the client, response object (res) has option to set the status of response like 200, 201, 500 and calling the method .json() I can send my data to client inside a custom object if I want.

app.use('/api/documents',(req, res, next) => {
const documents = [
{ id: 1, title: 'Invoice from ENDESA',
description:'Your total invoice is 4000€'},
{ id: 1, title: 'Invoice from Gas Natural',
description:'Your total invoice is 300€'}
console.log("get from client")
res.status(200).json({ message:'all data', documents: documents} ); });

There you have it! go and navigate to http://localhost:3009/api/documents and get the response.

{"message":"all data",
"documents":[{"id":1,"title":"Invoice from ENDESA",
"description":"Your total invoice is 4000€"}

Feel free to read more about express in