How to create an API with Node and Express

Starting a new project

The first thing I like to do is to create a brand new folder for the following project:

mkdir api
cd api

After that, we just need to start our node app. I prefer to use yarn instead of npm but you can choose whatever package manager you want.

yarn init -y

Dependencies

Let's start with 2 important libraries: Express and Body-Parser.

Express is a minimal, flexible and open source Node.js web aplication framework that provides a very robust set of features for web and mobile apps. With Express we'll create routes and handle http requests.

Body-Parser is a Node.js body parsing middleware that parses incoming http request bodies before your api handlers, giving you, for example, a JSON parsed request body for you to work with.

Now, just run the following command in the terminal:

yarn add express bodyparser

A node_modules folder will be created in the process. This folder is where Node.js put all the dependencies of the project.

Organizing

In order to separate your source code from these initial and autogenerated files, it's convenient to create a src folder to put all your code in. Let's take this chance to create our application entrypoint file index.js as well. In the terminal:

mkdir src
touch src/index.js

Let's change the main file of the project from index.js to src/index.js in the package.json file. The package.json will be as follows:

{ 
  "name": "api",
  "version": "1.0.0",
  "main": "src/index.js",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }
}

And we're all set!

The API

To put together the core of our API you just need to:

  • Import express and bodyParser;
  • Instantiate the express;
  • Create the jsonParser and urlencodedParser middlewares;
  • Pass them to express;
  • Finally, the app will listen to port 3000 (you can choose another one);
const express = require('express')
const bodyParser = require('body-parser')

const app = express()

const jsonParser = bodyParser.json()
const urlencondedParser = bodyParser.urlencoded({extended: false})

app.use(jsonParser)
app.use(urlencondedParser)

app.listen(3000)

bodyParser.json([options]) returns a middleware that only parses json and only looks at requests where the Content-Type header matches the type option. By default the type is application/json.

bodyParser.urlencoded([options]) returns a middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 enconding and, in our case, we used the option: {extended: false} to accept url-encoded data with the querystring library.

Routes

An API without routes doesn't do anything. The routes are the endpoints that will respond to http requests. To create that you just need to:

const express = require('express')
const bodyParser = require('body-parser')

const app = express()

const jsonParser = bodyParser.json()
const urlencondedParser = bodyParser.urlencoded({extended: false})

app.use(jsonParser)
app.use(urlencondedParser)

// Routes
app.get('/', (request, response) => {
  response.send({message: 'Hello, world'})
})

app.listen(3000)

It's time to test your first API. In the terminal just type:

node src/index.js

You'll notice that as soon as you type enter to execute the command, the terminal won't give to you any feedback. To see a feedback on which por express is running, we need to change the app.listen(3000) to:

const port = 3000
app.listen(port, () => console.log(`Please, visit: http://localhost:${port}`))

Execute the app again to see the difference:

node src/index.js

After that visit: http://localhost:3000

Source

Feel free to access the github repo and clone the project node-express-api to you computer:

git clone https://github.com/almeidacavalcante/node-express-api.git

Thank you for reading this and stay tuned for more tutorials.