Building a Basic REST API

Tutorial 4 of 5

1. Introduction

Goal of the Tutorial

This tutorial aims to guide you through the process of building a basic REST API. The API will be able to perform fundamental operations like creating, reading, updating, and deleting data (CRUD operations).

Learning Outcomes

By the end of this tutorial, you will be able to:
- Set up a server using Node.js and Express.js
- Define routes and controllers
- Interact with a database using MongoDB

Prerequisites

You should have a basic understanding of:
- JavaScript programming language
- Node.js and npm (Node package manager)
- MongoDB

2. Step-by-Step Guide

Setting up the Server

We will use Node.js and Express.js to set up our server. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Installing Node.js and Express.js

Before proceeding, ensure you have Node.js installed. If not, download it from the official Node.js website. Node.js comes with npm, which we will use to install Express.js.

To create a new Node.js application, create a new directory and initialize it with npm:

mkdir myapp
cd myapp
npm init

This will create a package.json file in your application directory.

Next, install Express:

npm install express --save

Creating a Simple Server

Create a new file named app.js and add the following code:

const express = require('express');
const app = express();
const port = 3000;

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

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Run your application with the command node app.js and visit http://localhost:3000 in your browser. You should see 'Hello, World!'.

3. Code Examples

Setting Up Routes and Controllers

Routes

Routes are used to determine how an application responds to a client request for a specific endpoint. Let's add a route for each of the CRUD operations:

app.get('/users', getUsers);        // Get all users
app.get('/users/:id', getUser);     // Get a single user by id
app.post('/users', createUser);     // Create a new user
app.put('/users/:id', updateUser);  // Update a user by id
app.delete('/users/:id', deleteUser); // Delete a user by id

Controllers

Controllers handle the logic for each route. Let's define these controllers:

function getUsers(req, res) {
  // Code to fetch users from the database
}

function getUser(req, res) {
  // Code to fetch a single user by id from the database
}

function createUser(req, res) {
  // Code to create a new user
}

function updateUser(req, res) {
  // Code to update a user by id
}

function deleteUser(req, res) {
  // Code to delete a user by id
}

4. Summary

In this tutorial, we have covered:
- Setting up a server using Node.js and Express.js
- Defining routes and controllers for various operations
- A brief introduction to interacting with a MongoDB database

For next steps, consider:
- Learning more about database interaction with MongoDB
- Exploring more advanced features of Express.js

5. Practice Exercises

  1. Create a new route and controller that allows the user to search for other users by username.
  2. Add error handling to your controllers. For example, if a user tries to update a user that doesn't exist, your API should return a 404 error.
  3. Refactor your code to separate your routes and controllers into different modules. This will make your code easier to manage as it grows.

Remember, practice is key when learning web development. Don't hesitate to experiment and try different things!