chris bailey

Basics of Creating Web APIs with Node.JS and Express

Fast, unopinionated, minimalist web framework for Node.js

Express is a web application framework built on node.js. This post will explain the basics of setting it up and creating a simple web application.

Setup

Let’s start this series of posts by creating a basic app that will send back a predetermined string to the web browser. First, create a new directory and cd into it.

mkdir hello-world && cd hello-world Once there, we need to create our package.json to store the required modules for our application and store basic information about the project. We’ll run the following npm init -y which will run through the process without asking us any additional questions; if you’d like the more verbose method, remove -y from the command. We now have a package.json that looks like this:

/* ./package.json */
{
    "name": "hello-world",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo "Error: no test specified" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
}

Let’s run through this line by line quickly.

Next up, let us install express with npm so we can access it in our application. In the hello-world directory, type the following in terminal npm i express. This will add express to our package.json under a new section called “dependencies.” And we now have access to express and can use it in our application. Let’s start by creating our index.js and filling it with a basic application to send a message to the browser when hitting the root path.

// index.js
const express = require('express');

const app = express();

app.get('/', (req, res) => {
	res.send('root path');
});

app.listen(3000, () => {
	console.log('listening on port 3000');
});

The Rundown

That’s it for this portion of my express series. We’ve created a primary server that sends a message back to us when we hit the '/' path on our localhost. Easy Peasy. Next, we’ll get into view rendering and some different types of engines we can use.