Aashman Verma
Aashman Verma's Blog

Follow

Aashman Verma's Blog

Follow
Create API using Express

Create API using Express

API introduction to beginners using Express, Postman, Node-js

Aashman Verma's photo
Aashman Verma
ยทDec 11, 2022ยท

3 min read

Play this article

First, make a basic node js server

To set up, up the server and install nodemon, express as your dependencies

Setup Server ๐Ÿ”ฅ

Add this in your server.js or in an index.js

//Load HTTP module
const http = require("http");
const hostname = "127.0.0.1";
const port = 3000;

//Create HTTP server and listen on port 3000 for requests
const server = http.createServer((req, res) => {
  //Set the response HTTP header with HTTP status and Content type
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World\n");
});

//listen for request on port 3000, and as a callback function have the port listened on logged
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Adding routes to your routes.js file

A route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), a URL path/pattern, and a function that is called to handle that pattern.

For example, if we are building the to-do app we need routes to :

  1. add a new task

  2. update a task

  3. delete a task

    // getting Router from express module to handle our routes
    const {Router} = require('express');
    const router = Router();
    
    // requiring functions from another will in order to operate some tasks when we will hit an endpoint
    const {getToDo,saveToDo, updateToDo, deleteToDo} = require('./controller/ToDoController');
    
    // providing different end points 
    router.get('/save',saveToDo);
    router.get('/update',updateToDo)
    router.get('/delete',deleteToDo)
    
    // exporting all routes so we can use them in our server.js file
    module.exports = router;
    

Handling response on getting a new endpoint

Creating a new file in the folder (controller) named ToDoController.js at the same level as routes.js

Now whenever a user goes on localhost:3000/save the saveToDo function will run and the same goes with localhost:3000/update and localhost:3000/delete

module.exports.saveToDo = async ()=> {
    console.log("successfully added new task"):
}
module.exports.updateToDo = async ()=> {
    console.log("successfully updated");
}
module.exports.deleteToDo = async ()=> {
    console.log("successfully deleted");   
}

Using the above router in our server.js so that they can work

app.use() command is used to mount a middleware function onto a specific path

for example: when a user requests the server of localhost:3000/save the app.use() will run to process the output and then the response is given to the user by logging

successfully added a new task

to the console.

Adding routes in server.js

//Load HTTP module
const http = require("http");
const hostname = "127.0.0.1";
const port = 3000;
const routes = require('./routes.js');


//Create HTTP server and listen on port 3000 for requests
const server = http.createServer((req, res) => {
  //Set the response HTTP header with HTTP status and Content type
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World\n");
});


// added app.use() function
app.use(routes);

//listen for request on port 3000, and as a callback function have the port listened on logged
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Now we will see how to use postman software to hit an endpoint

Once you click on send button it will hit the endpoint and in response, we will get a response in our console below. Make sure that your server is running using nodemon otherwise, you will get an error on clicking on send button

Set the request type in postman from POST to GET otherwise you will not get the desired result

End :

In case you find this helpful consider following me, in terms of difficulties you can contact me on Twitter id (@verma_aashman), that's it for now see you later ๐Ÿ˜€

ย 
Share this