Free Ebook cover How to create APIs in NodeJS from basic to advanced

How to create APIs in NodeJS from basic to advanced

5

(1)

149 pages

Building a Basic REST API with NodeJS and ExpressJS: Error Handling

Capítulo 73

Estimated reading time: 4 minutes

Audio Icon

Listen in audio

0:00 / 0:00

NodeJS and ExpressJS are two powerful tools you can use to create REST APIs. A REST API, or Representational State Transfer, is a style of software architecture that uses a set of protocols and standards to build web applications. In this section, we'll learn how to create a basic REST API with NodeJS and ExpressJS and how to handle errors.

Setting the environment

Before we start, we need to make sure we have NodeJS and npm (Node Package Manager) installed on our system. If you don't have them yet, you can download them from the official NodeJS website. After installation, you can verify that they are installed correctly by running the following commands in the terminal:

$ node -v
$ npm -v

Next, we need to install ExpressJS, which is a web framework for NodeJS. You can install ExpressJS using npm with the following command:

$ npm install express

Creating the REST API

First, let's create a new file called 'app.js'. This will be our main file where we will configure our REST API. In the 'app.js' file, let's start by importing the ExpressJS:

const express = require('express');

Next, let's create a new instance of Express:

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

const app = express();

Now, let's define some routes for our API. For example, let's create a GET route to '/users' that returns a list of users:

app.get('/users', (req, res) => {
  res.json({ users: ['John', 'Jane', 'Bob'] });
});

Finally, let's make our application listen to port 3000:

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Error handling

Error handling is a crucial part of any application. In ExpressJS, you can handle errors using error middleware. An error middleware is a function that takes four arguments: (err, req, res, next).

You can define an error middleware as follows:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

This error middleware will catch any error that occurs in the application and will log the error stack to the console, and then send a response with status 500 and the message 'Something broke!'.

It is important to note that the error middleware must be defined after all other routes and middleware, because it will only catch errors that occur in the middleware and routes that are defined before it.

In addition, you can create custom error middleware to handle different types of errors in different ways. For example, you can create an error middleware to handle validation errors and another to handle authentication errors.

Conclusion

In this chapter, we learned how to create a basic REST API with NodeJS and ExpressJS and how to handle errors. ExpressJS makes it very easy to create REST APIs and offers many useful features such as error middleware that allow us to handle errors effectively.

In the next chapter, we'll learn how to add authentication to our API and how to secure our routes with JWT (JSON Web Tokens).

Now answer the exercise about the content:

What is a REST API and what tools are used to create it?

You are right! Congratulations, now go to the next page

You missed! Try again.

A REST API, or Representational State Transfer, is described in the text as a style of software architecture that utilizes a set of protocols and standards for building web applications. It specifically mentions the use of NodeJS and ExpressJS to create REST APIs, which matches the details given in Option 2.

Next chapter

Building a Basic REST API with NodeJS and ExpressJS: Authentication and Authorization

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.