10.11. Building a Basic REST API with NodeJS and ExpressJS: API Documentation

Página 76

NodeJS, along with ExpressJS, is one of the most popular tools for building REST APIs. In this chapter of our e-book, we'll learn how to create a basic REST API using these technologies, and also how to document the API for ease of use by other developers.

1. Configuring the Environment

First, we need to install NodeJS and ExpressJS. NodeJS can be downloaded and installed from the official website. After installing NodeJS, we can install ExpressJS using the npm package manager, which is installed along with NodeJS. In the terminal, run the following command:

npm install express --save

2. Creating the Basic Structure of the API

Next, let's create the basic structure of our API. First, create a new file called app.js. This will be the entry point for our API. Add the following code to the file:

const express = require('express');
const app = express();
app.listen(3000, () => {
  console.log('API is running on http://localhost:3000');
});

This code simply creates a new ExpressJS server that listens on port 3000.

3. Adding Routes

REST APIs are based on routes, which are URLs that represent different resources. Let's add some basic routes to our API. Add the following code to the app.js file:

app.get('/', (req, res) => {
  res.send('Welcome to our API!');
});

app.get('/users', (req, res) => {
  res.send('List of users');
});

app.get('/users/:id', (req, res) => {
  res.send(`User with ID ${req.params.id}`);
});

These routes respond to GET requests. The first route responds to the base URL (/) with a welcome message. The second route responds to the /users URL with a dummy list of users. The third route responds to the URL /users/:id, where :id is a parameter that can be any value. This route returns a dummy user with the specified id.

4. Creating a Dummy Database

To make our API a little more interesting, let's create a dummy database of users. Add the following code to the app.js file:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

app.get('/users', (req, res) => {
  res.send(users);
});

app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) res.status(404).send('User not found');
  else res.send(user);
});

The /users route now returns the list of users from our dummy database, and the /users/:id route returns the user with the specified id, or a 404 error if the user is not found.

p>

5. Documenting the API

Documentation is an essential part of any API. It allows other developers to understand how to use the API. There are several tools available for documenting APIs, but one of the most popular is Swagger. Swagger allows you to create interactive documentation for your API that can be viewed in a web browser.

To add Swagger documentation to our API, we first need to install the swagger-ui-express package:

npm install swagger-ui-express --save

Next, we can add the following code to the app.js file:

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

This code adds Swagger documentation to the /api-docs route. The swagger.json file contains the API documentation in JSON format. This file needs to be created manually and must follow the OpenAPI specification.

API documentation is a complex topic that deserves a chapter of its own, but we hope this short tutorial has given you an idea of ​​how to create a basic REST API with NodeJS and ExpressJS and how to document it. In the next chapter, we'll explore how to add authentication to our API.

Now answer the exercise about the content:

What is the purpose of the 'npm install express --save' command mentioned in the text?

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

You missed! Try again.

Next page of the Free Ebook:

7710.12. Building a Basic REST API with NodeJS and ExpressJS: Automated Tests

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text