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


This content originally appeared on DEV Community and was authored by Abayomi Ogunnusi

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

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

});

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

});

🥦

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

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

        }

     });

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

    }

});

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

    }

});

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


This content originally appeared on DEV Community and was authored by Abayomi Ogunnusi


Print Share Comment Cite Upload Translate Updates
APA

Abayomi Ogunnusi | Sciencx (2021-10-04T07:56:34+00:00) Build Simple Node Js API: no external package. Retrieved from https://www.scien.cx/2021/10/04/build-simple-node-js-api-no-external-package/

MLA
" » Build Simple Node Js API: no external package." Abayomi Ogunnusi | Sciencx - Monday October 4, 2021, https://www.scien.cx/2021/10/04/build-simple-node-js-api-no-external-package/
HARVARD
Abayomi Ogunnusi | Sciencx Monday October 4, 2021 » Build Simple Node Js API: no external package., viewed ,<https://www.scien.cx/2021/10/04/build-simple-node-js-api-no-external-package/>
VANCOUVER
Abayomi Ogunnusi | Sciencx - » Build Simple Node Js API: no external package. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/04/build-simple-node-js-api-no-external-package/
CHICAGO
" » Build Simple Node Js API: no external package." Abayomi Ogunnusi | Sciencx - Accessed . https://www.scien.cx/2021/10/04/build-simple-node-js-api-no-external-package/
IEEE
" » Build Simple Node Js API: no external package." Abayomi Ogunnusi | Sciencx [Online]. Available: https://www.scien.cx/2021/10/04/build-simple-node-js-api-no-external-package/. [Accessed: ]
rf:citation
» Build Simple Node Js API: no external package | Abayomi Ogunnusi | Sciencx | https://www.scien.cx/2021/10/04/build-simple-node-js-api-no-external-package/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.