RESTful APIs / Introduction to RESTful APIs

Building a Basic REST API

This tutorial will guide you through the process of building a basic REST API. You will learn how to set up a server, define routes and controllers, and interact with a database.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the basics of REST architecture, its principles, and how it differs from other API designs.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Converter

Convert between different image formats.

Use tool

Favicon Generator

Create favicons from images.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help