Step 11

Let's include a route to create a note.

Create Note
HTTP MethodPOST
API Endpoint/api/notes
Request Path Parameter
Request Query Parameter
Request BodyJSON object (note attributes)
Response BodyJSON object (created note)
Response Status201

Notes:

  • We use a POST method to create a note
  • The path (endpoint) is similar to the GET request we had earlier for receiving all notes. So you can think about it as we are posting to the collection of notes here (whereas before, we were going to read the collection of notes).
  • We need to provide the attributes (title & text) for creating the note. These attributes will be provided in the "body" (payload) of the request (we will see soon what that means!)
  • Once the note is created, we will return the newly created resource. This practice is expected in the design of APIs.
  • We send a status code of 201 to signal the resource creation succeeded.

Add the following route to index.js:

app.post("/api/notes", async (req, res) => {
  try {
    const { title, text } = req.body;
    const data = await notes.create({ title, text });
    res.status(201).json({ data });
  } catch (err) {
    res.status(err.status).json({ message: err.message });
  }
});

Notice how I have set the status code.

Also, notice how I have used req.body object to get the attributes of the note. The client is expected to provide these attributes as JSON data in the request body. To allow Express parse the request body, we must add the following line somewhere in index.js (after app is declared):

app.use(express.json());

Save the code, and then test this endpoint in Postman.

Also test for a case where an attribute is missing!