🎓 A1Learner
🔍
0 of 50 lessons completed

A Small Notes API

A small notes API lists notes and adds notes. One array in memory holds the notes.

Add a note

This command adds a note to the API.

curl -X POST http://localhost:3000/notes -H "Content-Type: application/json" -d '{"text":"Buy milk"}'

List the notes

This command lists the notes in the API.

curl http://localhost:3000/notes

Example

const express = require("express");

const app = express();
const notes = [];

app.use(express.json());

app.get("/notes", (req, res) => {
  res.json(notes);
});

app.post("/notes", (req, res) => {
  const note = { id: notes.length + 1, text: req.body.text };
  notes.push(note);
  res.status(201).json(note);
});

app.listen(3000, () => {
  console.log("Notes API running on http://localhost:3000");
});

Key points

  • A notes API lists notes and adds notes.
  • One array in memory holds the notes.
  • In memory means the data lives only while the server runs.
  • A GET route at /notes sends the whole array.
  • A POST route at /notes adds one note to the array.
  • Each note gets an id, a number that names it.

In this example, notes starts as an empty array. The GET route sends the whole array as JSON. The POST route builds a note from the sent body. The id comes from the array length plus one. The new note joins the array. The route sends it back with status 201. A POST ask adds a note, and a GET ask then shows it in the list.

Note

A restart clears the array, so the notes are gone.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where do the notes live in this API?