umma.dev

Setting Up a Node.js API

Node.js enables you to program APIs using JavaScript. Below I have outlined the basics of getting started with Node.js to set up an API with various end points.

Installation Set up

Node.js

You are going to need Node JS. If you don't have Node.js, it can be downloaded via `https://nodejs.org`.

To check if Node is installed on your machine type the following command into your terminal: node -v

The Project Set Up

Folder Structure

  • Type mkdir <folder-name> in your terminal to create a new directory

  • cd <folder-name> to move into the directory

  • npm init to initialise a package.json file

File Structure

  • touch server.js to create a new file

  • Head over to your text editor and open up the folder

  • Insert the following code into server.js

'use strict';

const http = require('http');

const hostname = 'localhost';
const port = 3001;

const server = http.createServer((request, response) => {
    response.statusCode = 200;
    response.setHeader('Content-Type', 'text/html')
    response.end('Hello world');
})

server.listen(port, hostname, () => {
    console.log('server is running')
})
  • Go back to your command line and type node server.js

  • Head over to https://localhost:3001 and you should see hello world

  • Type the following into the terminal to install packages

npm install -g nodemon

npm install express

npm install body-parser cors

  • Create a file named data.js

  • Insert the following into data.js:

const data = [
    {
        "id": 1,
        "name": "testOne"
    },
    {
        "id": 2,
        "name: "testTwo"
    }
]
module.exports = data;

Setting Up End Points

GET Request

  • Navigate to your package.json file and in scripts type the following:
{
    ...
    "scripts": {
        ...
        "start": "node server.js"
        "dev": "nodemon server.js"
        ...
    }
    ...
}
  • Remove the line const http = require('http'); in server.js and replace it with:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
let info = require('./data.js')

app.use(bodyParser.urlencoded({ extened: true }));
app.use(cors());

app.get('/api/info', (request, response) => {
    if(!info) {
        response.status(404).json({ message: 'No info found!' })
    }
    response.json(info)
})
  • Head over to https://localhost:3001/api/info and you should be able to see the data