NodeJS POST API Tutorial



POST API Tutorial With Express











Table of Contents



1. Introduction
2. Code
3. Conclusion

Table of Contents



1. Introduction
2. Code
3. Conclusion



The Guide



Setting up an API can be a bit confusing. An API is an Application Programming Interface, and allows third party applications to access information or store information. In this article we will be going through a simple API using Node.js and Express. You can use other web frameworks, but I find that Express works well. If you would like a more basic tutorial, check out this tutorial.

The Code



To start off, let's go through our dependencies for this project. Before starting, be sure you have Node.js and npm installed. You can check if npm is installed by running npm version in a console or terminal. If you have them installed, go ahead and run the following in your console/terminal:
Those should be good for now. Let's go ahead and create a file called index.js for our server-side code. Let's also write our first lines in that file.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = 8000;
const app = express();
if (isNaN(port)) process.exit(1); // Exits the program if the port is invalid.
    
That is the basic code that I like to put in each express file. It allows us to change the port if needed by only changing the variable, and imports and defines dependencies. The code defines four variables: express, bodyParser, path, app, and port. The express, bodyParser, and path variables are modules that we will use later. Our port variable is for whichever port we would like our program to host on. The app variable defines a new express app. The server will then check if the port variable is invalid. If it is, the program will stop execution. Let's write our next chunk of code. Here, we will configure our app.
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(bodyParser.text());
                
Those three lines of code allow our server to interpret incoming requests. Now, it's time to get to the fun part. First, let's handle a basic request to http://localhost:(PORT)/. We will use app.get() for that and we will send our index.html file.
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html')); // Send the index.html file. Path is used to more reliably get files from their names and the directory.
});
                
The code above will listen for any GET requests to http://localhost:(port)/ and if it receives any, it will send the index.html file, which we still have yet to create. That's our basic handler. We will implement two more, one using app.all(), and one using app.post(). The app.all() function will handle ANY type of incoming requests to the specified address, which can include GET, POST, PUT, etc. We'll send simple JSON with it. Enter the following code.
app.all('/api/helloworld/', function(req, res) {
    res.send({ message: "Hello World!" });
});
                
This code above will configure the app to handle incoming requests to http://localhost:(PORT)/api/helloworld/. It will send JSON data back. Once we are done with the index.js file, you will be able to enter the address in your browser and view the JSON. But we're not done yet! Let's handle POST requests now. Enter the following code.
app.post('/api/helloworld/post_only', (req, res) => {
    res.send({ message: "Hello World! (POST)" });
});
                
This is a simple POST request handler. When a POST request is routed to http://localhost:(PORT)/api/helloworld/post_only, the request will receive JSON data as a response. We aren't quite done yet. Next, we need to tell the app to start listening. To do so, enter the following code.
app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}/`);
});
                
The code above will tell the app to start listening on the port. That's all for the index.js file! Next, let's quickly create our index.html file. Enter the following code.
<!DOCTYPE HTML>
<html>
<head>
    <title>Express.js API Tutorial Example</title>
    <meta charset="utf-8" />
    <style>
        #buttonContainer {
            text-align: center;
                margin: 10px auto;
            }
                            
            #main_text {
                text-align: center;
            }
    </style>
    <script>
        function sendPost() { // Define a new function
            var postReq = new XMLHttpRequest(); // Define a new XMLHttpRequest
            postReq.open("POST", 'http://localhost:8000/api/helloworld/post_only'); // Open the XMLHttpRequest
            postReq.send("Hi"); // Send the request
            postReq.onload = () => { // Will run when the request receives a response
                console.log(postReq.response); // Log the response
            }
         }
    </script>
</head>
                    
<body>
    <h1 id='main_text'>Hello World!</h1>
    <div id='buttonContainer'>
        <button onclick='sendPost()' value='Send POST Request' id='mb'>Send POST Request</button>
    </div>
</body>
                    
</html>
                
That code creates our index.html file. When you click on the button, it will send a request to your API and will log the response in the browser console.

Conclusion



To run the program, navigate to the directory in your terminal/console, type in node index.js, then navigate to http://localhost:8000/ (or whichever port you chose to use). You can add more files and paths. This just covers setting up a simple web server with Node.js. If you would like the full code, you can view it here.
Happy programming!

Related Articles