Build Simple Node Js API: no external package
Tags: node, webdev, javascript, codenewbie
Published: 2021-10-04 07:56:34

## 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 <mark>os</mark>, <mark>fs</mark>, and so on. 

---

## TOC

[Import in-built module](#import)

[Create a server](#server)

[Listen to server](#listen)

[Routes](#router)

[Reading Data](#read)

[Content-Type and Status](#status)

## Let's start

![stone](https://media4.giphy.com/media/nDMyoNRkCesJdZAuuL/giphy.gif?cid=82a1493bql2igvv8wtf5nw585omfvttu0p2dlzgysjjn2l5r&rid=giphy.gif&ct=g)

🥦  Create a file `app.js`.

![raw9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihvzehlqu1ty27wj88n8.PNG)

 




Import the fs and url modules
<a name="import"></a>
```Javascript

const fs = require ('fs');

const url = require('url');

const http = require('http');

```

🥦 Next, in the sample `app.js` we create a server.<a name="server"></a>

```Javascript

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

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

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

});

```




## The next main thing is to listen to a server <a name="listen"></a>

```Javascript

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

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

});

```

## 🥦

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

![raw1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dn8b5fm0i2grunxu94eg.PNG)

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

```Javascript

     127.0.0.1:3001

```

![raw4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/so932ir0cgnx7uobeimy.PNG)

You also get a console log response.

![raw5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0q9nfezsec5c405dbznx.PNG)

---




## Routing <a name="router"></a>

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.

```Javascript

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');

        }

     });

```




## Writing Headers and Status Code<a name="status"></a>

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




```Javascript

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');

    }

});

```

## Let's test again

![raw11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yyz07fxhrh9uo6gucpj1.PNG)

 

---

## Reading data with fs module (asynchronously). <a name="read"></a>

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

![raw14](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gzp1m731wj1p9pw6fx6.PNG)

 

```Javascript

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');

    }

});

```

## Result

![raw2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agqw6ctd190h5d3i5xwl.PNG)

 

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

![raw4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tawebt0ucj6bs4h2yeh8.PNG)

![raw9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/amnpugu8r4itafbulupb.PNG)

 

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](https://user-images.githubusercontent.com/70065792/135759677-8a3a352f-515f-49ae-9baf-61ecc5b59fc8.mp4)

![raw8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qy1zf2tur656m5dxvub6.PNG)

 

---

## Conclusion

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

## Reference

[Video reference](https://www.youtube.com/watch?v=9MEEzJ_q9HQ)
[Node Js](https://nodejs.org/en/docs/)