Skip to main content

Command Palette

Search for a command to run...

Creating your first API server in Node.js

Published
2 min read

Hello,

This is my first post about creating APIs using Node.js.

Node.js is a JavaScript runtime environment that makes it easy to create APIs in minutes. Node.js has a lot of built-in modules which can be helpful and speed up your development process. Today, we will be using the built-in http module to create the server and receive API requests and serve the response.

Node.js has a lot of built-in modules which can be used without any installation. To use any module, you will need to call the require function to get the reference of that module. Create a file with the name index.js in a new folder and write the following code in it:

const http = require('http');

Now using the http variable, you can create a server with the following code:

const serve = function (req, res) {
    res.write('Hello. This is first API');
    res.end();
}

const server = http.createServer(serve);

As you can see, we have created a function called serve and passed it to the createServer function of http module.

The createServer function will internally start a server and will forward all the incoming requests to the serve function. It will also pass two arguments req and res to your serve function.

We will later understand the in-depth functionality of these parameters, but for now, we are using the write and end functions of res object. The write function tells the server what data we need to send in response and the end function tells the server that we are done sending the data and the request should be ended.

Now you will need to bind it with a port to listen for incoming requests.

const port = 9090;
server.list(port);

The code is completed. Now you can open a terminal in the same folder and execute the following command:

node index.js

This command will tell node.js to execute the code of index.js file.

You can now open your browser and navigate to the following url: http://localhost:9090.

You will see the following response: Hello. This is first API.

Voila! You have just created your first API server using node.js.