Step 10

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. You can think about it as we are going to post to the collection of notes here (whereas before we were going to read the collection of notes).
  • We need to provide the attributes (content & author) for creating the note. This attribute 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 is just a common pattern 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", (req, res) => {
  const content = req.body.content;
  const author = req.body.author;
  const note = notes.create(content, author);
  res.status(201).json(note);
});

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 a 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());

You will not be able to test a POST request in your browser (where you typically write URLs is for GET requests). You must test this endpoint in Postman.