THE EXPRESS JOURNEY: [The basics] — build your CRUD API

THE EXPRESS JOURNEY: [The basics] — build your CRUD API

PREREQUISITES

  • Javascript basics

  • Postman for testing

I’m back 🙈 was the water break long? Well, I hope it wasn’t. Let’s continue our express journey; if you haven’t read the first article, I recommend you do so to ensure we are all on the same path. Here’s a link to the article.

Let’s look at what a RESTful API is, but first, let’s review what an API is.

An API, or Application Programming Interface, is a collection of rules and protocols that enables various software applications to communicate with one another. It states the processes and data forms the applications may use to request and share information. For an even more practical understanding, let’s consider this scenario;

Say you visit a restaurant and you want to order food. You can’t just go into the kitchen and start making your food. Instead, you communicate with the waiter or waitress, who takes your order to the kitchen and returns your meal when it is ready.

You are the client/user.

Waiters and waitresses act similarly to APIs.

The kitchen is the system or service with which you are dealing.

So, just as the waiter is a link between you and the kitchen, an API connects various software applications or systems.

REST, or Representational State Transfer, is an architectural methodology for developing networked applications. A RESTful API follows the REST principles and allows clients to carry out CRUD (Create, Read, Update, Delete) processes on resources using common HTTP methods (GET, POST, PUT, DELETE).

Let’s get back to doing what we do best: writing code.🙈

We need to add a body parser to our index.js file. Body Parser is a middleware module for web application frameworks such as Express.js. It is usually used in middleware to parse incoming request bodies before handlers, as indicated by the req.body attribute.

  • First, install body-parser.
npm install body-parser
  • Integrate body-parser into our express application using import. Your index.js file should look like this;
import express from "express";
import bodyParser from "body-parser";
import dotenv from "dotenv";

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;app.use(
  bodyParser.json()
);

app.get("/", (req, res) => res.json("Hello World!"));
app.listen(PORT, () =>
  console.log(`Server running on port: ${PORT}`)
);

UPDATE APPLICATION STRUCTURE

  • Create two folders in your application’s root directory: controllers and routes. Our routes folder will include our route definitions and the controller assigned to each route, our controller will contain the methods/processes we want to execute whenever we access a route.

  • Create a noteRoutes.js file in the routes folder and a notes.js file in the controllers folder.

AHAN! BACK TO CREATING MAGIC

  • Create a controller method for adding a note. For this tutorial, we’ll store our data in a variable.

  • Create a method for handling add notes. But before we do that, we need to install and import a package called uuidv4. This package will assist us with adding dynamic ids to our notes.

//run this command in your terminal.
npm i uuidv4
//import uuidv4 in your controller file 
import { v4 as uuidv4 } from 'uuid';

Great! We’re ready to create our addNotes method in our controller file.

  • Keep in mind our method will accept two parameters a request object (req) and a response object (res). Our request object will contain the data the user wants to store in the req.body and our response will have the message or action to be performed upon fulfillment of the user’s request.
import { v4 as uuidv4 } from 'uuid';

//create a notes variable
let notes = []export const addNotes = (req, res) => {
    //what the user sends in the body
    const note = req.body    //add id to the note
    notes.push({...note, id:uuidv4()});
    //send a response to the user
    res.send(`note with title ${note.title} added successfully`)
}
  • Import our controller in our routes file (noteRoutes.js) and create a route for adding notes.
import express from 'express';
import { addNote } from '../controllers/notes.js';
const router = express.Router();//add notes route
router.post('/', addNote);export default router;
  • To expose our routes and make them accessible we need to use it in our app.js.
import express from "express";
import bodyParser from "body-parser";
import noteRoutes from "./routes/notesRoutes.js"

const app = express();

const PORT = 3000;app.use(
  bodyParser.json()
);

//use or expose notesRoutes
app.use("/notes", noteRoutes);

app.get("/", (req, res) => res.json("Hello World!"));
app.listen(PORT, () =>
  console.log(`Server running on port: <http://localhost>:${PORT}`)
);

We’ll repeat the same procedure for other methods, but before we continue let’s test addNotes in Postman to be sure it works. Your postman should look like what we have below. You can add more notes based on your preference.

RETRIEVE NOTES

We’ll follow the same steps we used for adding notes. Write our controller method, define our route, and test in Postman.

  • Create a getNotes method in your controller file.
export const getNotes = (req, res) => {
//display notes in response
  res.send(notes);
};
  • Import the getNotes method in your notesRoutes file and define our route for retrieving notes.
//get notes
router.get("/", getNotes);
  • Test getNotes on Postman. But first, add notes before getting them. From the response you get in Postman, notice you didn’t add an id manually in your body but an id was added in your note object; that’s the power of the uuid package.
[
    {
        "title": "My first note",
        "description": "This is my first note and I'm happy to express my thoughts.",
        "id": "8e43f906-433a-4952-96b0-9af0f4a3282e"
    },
    {
        "title": "Hello World!",
        "description": "Hello World! I'm a shy person.",
        "id": "dc6176ff-dbb5-45cf-8d98-969e167500ed"
    }
]

RETRIEVE NOTES BY ID

Over here, we want to retrieve just one note based on the id we pass in our request params.

  • Create a getNote method in our controller file
export const getNote = (req, res) => {
//access id from params
    const { id } = req.params;

//find note using id
    const note = notes.find((note) => note.id === id);

    if (!note) {
      res.send(`Note with id ${id} not found`);
    }

    res.send(note);
}
  • Import getNote in our notesRoutes file and define our route.
//get a note
router.get("/:id", getNote);j
  • Test getNote in Postman to ensure our method works well.

Add notes and retrieve your notes. Copy your preferred id to retrieve the note you want. Add the id in your postman request URL like this “**http://localhost:3000/notes/d3545b57-f004-43c4-a1c5-9a166675ee85**”. Try a random idea like 123 for id, you should get “Note with id 123 not found”.

//getNote with id response
{
  "title": "My first note",
  "description": "This is my first note and I'm happy to express my thoughts.",
  "id": "d3545b57-f004-43c4-a1c5-9a166675ee85"
}

DELETE A NOTE

In this section, we’ll handle the deletion of a note. To delete a note, you need the note id.

  • Create the deleteNote method in our controller file.
export const deleteNote = (req, res) => {
    const { id } = req.params;

    notes = notes.filter((note) => note.id != id);

    res.send(`Note with the id ${id} has been deleted`);
}
  • Import deleteNote in our notesRoutes file and define our route.
//delete a note
router.delete("/:id", deleteNote);
  • Test deleteNote in Postman to ensure our method works well. After running the delete action, you can run the Get notes again to be sure you deleted the note.
//response from deleteNote in postman

Note with the id 852d09b5-ed6b-4bdd-8e0e-920e8e2666f6 has been deleted.

EDIT A NOTE

  • Create the editNote method in our controller file.
export const editNote = (req, res) => {
  const { id } = req.params;
  const { title, description } = req.body;

  const note = notes.find((note) => note.id === id);
  if (title) note.title = title;
  if (description) note.description = description;

  res.send(`Updated note with the id ${id} successfully. ${note}`);
};
  • Import editNote in our notesRoutes file and define our route.
//edit note
router.patch("/:id", editNote);
  • Test editNote in Postman to ensure our method works well. After running the delete action, you can run the Get notes again to be sure you edited the note.

Woah! That was a long ride. Thanks for joining this ride.

I hope you learned something and feel free to expand your methods in your controller and play around with it. Remember, we only learn by making mistakes and solving them.