Build a REST API with Node.js and Express

What is REST? What is an API? Learn how to build a simple RESTful API with Node.js and Express

Photo by Fahim Muntashir on Unsplash

Before jumping into REST, an API (Application Programming Interface) provides a way to connect and interact with something, whether that is a component, an application, a computer, etc.

RESTful APIs are the most famous type of API. REST APIs are APIs that follow standardized principles, properties, and constraints. You can access resources in the REST API using HTTP verbs.

Let’s start by creating an empty directory and initializing a project by running the following command:

mkdir rest-api
cd rest-api
npm init -y

The next step is to create an empty JavaScript file. The file name could be anything, in this case, it’s index.js.

Next, we’ll install Express (Express is a minimal and easy-to-learn framework for Node.js):

npm install express

Now that everything is ready, it’s time to code our actual API.

Let’s start with the server.

In the below code snippet, we are initializing our app and starting the local server at port 3000. Run node index.js to start the server.

const app = require('express')();
app.listen(3000, () => console.log('App is running'));

For more context, listen() function is used to establish the connection on specified host and port. It takes two params: — The first is the port number or host. The second (optional) is a callback function that runs after listening to a specified host or value.

Moving forward, let’s try to access “localhost:3000” in the browser and see what we are getting. We are getting a “404 Not Found” response which is correct as we haven’t defined any endpoints yet.

As now our server is running successfully at port 3000, let’s create an endpoint.

The get method allows us to create HTTP GET requests.

It accepts two params:

  • the first is path/route;
  • the second is a callback function that handles the request to the specified route.
app.get('/path, () => {});

The callback function itself accepts two arguments:

  • the first is the request which is the data to the server;
  • the second is the response which is the data to the client.
app.get('/path'. (req, res) => {});

Suppose you want to display all the users whenever the client requests the “/users” endpoint. To return the data from the server to the client, we have the send method.

In the code snippet below, we send an array of objects with name and id fields.

app.get('/users, (req, res) => 
res.status(200).send([
{name: 'John', id: 1},
{name: 'Sunil', id: 2},
]);
});

Let’s restart the server by running the node index.js command:

You can make as many endpoints as you want using the same technique. For demonstration purpose, let’s quickly create a POST request endpoint.

const express = require('express');
const app = express();
app.use(express.json());

We are defining a POST endpoint at the “/user/3” route. We implemented the logic of throwing a “400 Bad Request” status code if the user forgets to pass the name value in the request body.

app.post('/user/3', (req, res) => {
const {name} = req.body;
if (!name) {
res.status(400).send({ message: "Please add name of user"});
}
res.send({ name: name, id: 3});
});

Let’s try to access this endpoint now.

As you can see, we are getting a response.

Great! You can add as many endpoints as want.

This is how we build a REST API using Express and Node.js.

Conclusion

We have learned how to make API Endpoints for our backend server using Node.js and Express. I hope you have found this useful. If so, be sure to let me know in the comments.

Use any component in all your projects

Up until now, you used to build features hidden inside larger projects.

But what if you were to develop independent features first, and then easily compose and manage them in many applications? Your development will become faster, more consistent, and more scalable every day. Create a component once, and truly use it anywhere to build anything.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing them to applications. You can start small with a nice project, some shared components, or even trying out Micro Frontends. Give it a try →

An independent product component: watch the auto-generated dependency graph


Build a REST API with Node.js and Express was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Adarsh gupta

What is REST? What is an API? Learn how to build a simple RESTful API with Node.js and Express

Photo by Fahim Muntashir on Unsplash

Before jumping into REST, an API (Application Programming Interface) provides a way to connect and interact with something, whether that is a component, an application, a computer, etc.

RESTful APIs are the most famous type of API. REST APIs are APIs that follow standardized principles, properties, and constraints. You can access resources in the REST API using HTTP verbs.

Let’s start by creating an empty directory and initializing a project by running the following command:

mkdir rest-api
cd rest-api
npm init -y

The next step is to create an empty JavaScript file. The file name could be anything, in this case, it’s index.js.

Next, we’ll install Express (Express is a minimal and easy-to-learn framework for Node.js):

npm install express

Now that everything is ready, it’s time to code our actual API.

Let’s start with the server.

In the below code snippet, we are initializing our app and starting the local server at port 3000. Run node index.js to start the server.

const app = require('express')();
app.listen(3000, () => console.log('App is running'));

For more context, listen() function is used to establish the connection on specified host and port. It takes two params: — The first is the port number or host. The second (optional) is a callback function that runs after listening to a specified host or value.

Moving forward, let’s try to access “localhost:3000” in the browser and see what we are getting. We are getting a “404 Not Found” response which is correct as we haven’t defined any endpoints yet.

As now our server is running successfully at port 3000, let’s create an endpoint.

The get method allows us to create HTTP GET requests.

It accepts two params:

  • the first is path/route;
  • the second is a callback function that handles the request to the specified route.
app.get('/path, () => {});

The callback function itself accepts two arguments:

  • the first is the request which is the data to the server;
  • the second is the response which is the data to the client.
app.get('/path'. (req, res) => {});

Suppose you want to display all the users whenever the client requests the “/users” endpoint. To return the data from the server to the client, we have the send method.

In the code snippet below, we send an array of objects with name and id fields.

app.get('/users, (req, res) => 
res.status(200).send([
{name: 'John', id: 1},
{name: 'Sunil', id: 2},
]);
});

Let’s restart the server by running the node index.js command:

You can make as many endpoints as you want using the same technique. For demonstration purpose, let’s quickly create a POST request endpoint.

const express = require('express');
const app = express();
app.use(express.json());

We are defining a POST endpoint at the “/user/3” route. We implemented the logic of throwing a “400 Bad Request” status code if the user forgets to pass the name value in the request body.

app.post('/user/3', (req, res) => {
const {name} = req.body;
if (!name) {
res.status(400).send({ message: "Please add name of user"});
}
res.send({ name: name, id: 3});
});

Let’s try to access this endpoint now.

As you can see, we are getting a response.

Great! You can add as many endpoints as want.

This is how we build a REST API using Express and Node.js.

Conclusion

We have learned how to make API Endpoints for our backend server using Node.js and Express. I hope you have found this useful. If so, be sure to let me know in the comments.

Use any component in all your projects

Up until now, you used to build features hidden inside larger projects.

But what if you were to develop independent features first, and then easily compose and manage them in many applications? Your development will become faster, more consistent, and more scalable every day. Create a component once, and truly use it anywhere to build anything.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing them to applications. You can start small with a nice project, some shared components, or even trying out Micro Frontends. Give it a try →

An independent product component: watch the auto-generated dependency graph

Build a REST API with Node.js and Express was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Adarsh gupta


Print Share Comment Cite Upload Translate Updates
APA

Adarsh gupta | Sciencx (2022-02-01T10:02:55+00:00) Build a REST API with Node.js and Express. Retrieved from https://www.scien.cx/2022/02/01/build-a-rest-api-with-node-js-and-express/

MLA
" » Build a REST API with Node.js and Express." Adarsh gupta | Sciencx - Tuesday February 1, 2022, https://www.scien.cx/2022/02/01/build-a-rest-api-with-node-js-and-express/
HARVARD
Adarsh gupta | Sciencx Tuesday February 1, 2022 » Build a REST API with Node.js and Express., viewed ,<https://www.scien.cx/2022/02/01/build-a-rest-api-with-node-js-and-express/>
VANCOUVER
Adarsh gupta | Sciencx - » Build a REST API with Node.js and Express. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/01/build-a-rest-api-with-node-js-and-express/
CHICAGO
" » Build a REST API with Node.js and Express." Adarsh gupta | Sciencx - Accessed . https://www.scien.cx/2022/02/01/build-a-rest-api-with-node-js-and-express/
IEEE
" » Build a REST API with Node.js and Express." Adarsh gupta | Sciencx [Online]. Available: https://www.scien.cx/2022/02/01/build-a-rest-api-with-node-js-and-express/. [Accessed: ]
rf:citation
» Build a REST API with Node.js and Express | Adarsh gupta | Sciencx | https://www.scien.cx/2022/02/01/build-a-rest-api-with-node-js-and-express/ |

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.