DEV Community

Cover image for Build Simple Node Js API: no external package
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

Build Simple Node Js API: no external package

Raw Node:

Frameworks like Express Js or Kao Js have made writing APIs a lot easier. Nonetheless, it is expedient that a developer knows how to write code from the ground up using the in-built module like os, fs, and so on.


TOC

Import in-built module

Create a server

Listen to server

Routes

Reading Data

Content-Type and Status

Let's start

stone

🥦 Create a file app.js.

raw9

Import the fs and url modules


const fs = require ('fs');

const url = require('url');

const http = require('http');

Enter fullscreen mode Exit fullscreen mode

🥦 Next, in the sample app.js we create a server.


const server = http.createServer((req,res)=> {

    console.log('puppies are friendly...')

    res.end('puppies are friendly...');

});

Enter fullscreen mode Exit fullscreen mode

The next main thing is to listen to a server


server.listen(3001, '127.0.0.1', ()=> {

    console.log('server is running on port 3001');

});

Enter fullscreen mode Exit fullscreen mode

🥦

The moment of truth. Now let's run node app from our terminal

raw1

Visit any browser (in my case, Fire 🦊...) and test your endpoint.


     127.0.0.1:3001

Enter fullscreen mode Exit fullscreen mode

raw4

You also get a console log response.

raw5


Routing

Let's create multiple endpoints using the url module. As it is, any endpoint/resource we hit will get returned to back to the home page.

To make this work we use the >url> module.


const server = http.createServer((req,res)=> {

    const endPoint= req.url;

        if(endPoint === '/' || endPoint === '/dogs'){

            res.end('This is the puppy landing page');

        } else if (endPoint === '/adopt-a-puppy') {

            res.end('Adopt our cute puppies');

            } else {

                res.end('... 404!!!, page not found');

        }

     });

Enter fullscreen mode Exit fullscreen mode

Writing Headers and Status Code

Let's write headers and responses, i.e., what kind of response are we sending, either html/text or application/json


const server = http.createServer((req, res) => {

    const endPoint = req.url;

    if (endPoint === '/' || endPoint === '/dogs') {

        res.end('This is the puppy landing page');

    } else if (endPoint === '/adopt-a-puppy') {

        res.end('Adopt our cute puppies');

    } else {

        res.writeHead(404, {

            'Content-type': 'text/html',

            'drsimple-header': 'no puppies response'

        });

        res.end('... 404!!!,  Page not found');

    }

});

Enter fullscreen mode Exit fullscreen mode

Let's test again

raw11


Reading data with fs module (asynchronously).

Next, we will create data.json and read all registered puppies 🐕🐕🐕. Here, we will set our Content-type to application/json

raw14


const server = http.createServer((req, res) => {

    const endPoint = req.url;

    if (endPoint === '/' || endPoint === '/dogs') {

        res.end('This is the puppy landing page');

    } else if (endPoint === '/adopt-a-puppy') {

        fs.readFile('./data.json', 'utf-8', (err, data) => {

            const puppyData = JSON.parse(data)

            res.writeHead(200, {

                'Content-type': 'application/json',

                'drsimple-header': 'no puppies response'

            });

            res.end(data)

        })

    } else {

        res.writeHead(404, {

            'Content-type': 'text/html',

            'drsimple-header': 'no puppies response'

        });

        res.end('... 404!!!,  Page not found');

    }

});

Enter fullscreen mode Exit fullscreen mode

Result

raw2

Now let's check our developer console, network tab to be specific. (On windows, hit f12)

raw4

raw9

In the picture above, you can see the 200 status code, which means OK. Just to confirm if our headers went through...double click on the 200 status code. Here you will see the headers I wrote deliberately and the content type.
demo result link

raw8


Conclusion

This is just a basic introduction to what you can do with raw node. Check the NodeJs Docs for more.

Reference

Video reference
Node Js

Top comments (0)