The Notes API: List and Create
The notes API is the set of routes that serve the notes app. This lesson builds its first two routes, list and create.
Listing notes
The route reads the notes and sends them back.
app.get('/api/notes', async (req, res) => {
const notes = await Note.find().sort({ title: 1 });
res.json(notes.map((n) => ({ title: n.title, done: n.done })));
});Creating a note
The route saves the body as a new note.
app.post('/api/notes', async (req, res) => {
const note = await Note.create(req.body);
res.status(201).json({ title: note.title, done: note.done });
});Asking for the list
curl asks the server for the notes.
curl http://localhost:3001/api/notesExample
import express from 'express';
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({ title: String, done: Boolean });
const Note = mongoose.model('Note', noteSchema);
await Note.create({ title: 'Buy milk', done: false });
await Note.create({ title: 'Ship MERN', done: true });
await Note.create({ title: 'Read a book', done: false });
const app = express();
app.use(express.json());
app.get('/api/notes', async (req, res) => {
const notes = await Note.find().sort({ title: 1 });
res.json(notes.map((n) => ({ title: n.title, done: n.done })));
});
app.post('/api/notes', async (req, res) => {
const note = await Note.create(req.body);
res.status(201).json({ title: note.title, done: note.done });
});
const server = app.listen(0);
const port = server.address().port;
const base = `http://localhost:${port}`;
const list = await fetch(`${base}/api/notes`);
console.log(await list.text());
const created = await fetch(`${base}/api/notes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Water plants', done: false }),
});
console.log(await created.text());
server.close();
await mongoose.disconnect();Key points
- The notes API starts with two routes, list and create.
- GET /api/notes returns every note, sorted by title.
- POST /api/notes saves the body as a new note.
- Both routes send notes without _id or __v.
- The list route reads from the model, and the create route writes to it.
In this example, the script connects to the notes database and saves the three notes. It builds an Express app with the first two routes of the notes API. GET /api/notes lists the notes, sorted by title. POST /api/notes saves the body as a new note and answers 201. The script asks for the list, then creates a note called Water plants. The two printed lines are the list body and the new note body.
Note
These two routes are the base for the rest of the API.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which two routes does this lesson build for the notes API?