This video is available to students only

Adding Post, Put and Delete Endpoints

Adding Post, Put and Delete Endpoints to the Backend

Creating and Updating Data#

We need a way to be able to create and update rows on the lunch_week and lunch_day tables. For creating new records, we'll use a POST endpoint. For updating existing records, we'll use a PUT endpoint.

Let's start with a POST endpoint to create a row in the lunch_week table. When we create a new row, the database will generate an ID for that row. We'll return that ID back to the API caller:

Testing POST and PUT Endpoints#

We can only test GET endpoints in the URL bar of a web browser. Now that we have a POST endpoint to test, we need another tool. For this course, we are going to use Postman to test these endpoints.

Postman is a robust tool for making API requests. If you don't already have it, go ahead and install it now.

Once Postman is open, we can make a POST request to our new endpoint. One big difference between POST/PUT requests and GET requests is that they can have a JSON body.

When we submit a POST request with a body to Express, we can access the body as a JavaScript object by calling req.body as we did above. Therefore, in our Postman request, we'll need to provide a basic lunchWeek entity as the body.

Here's what it looks like in Postman:

postman-request

There are a couple of gotchas in getting this to work in Postman. First, make sure POST is selected to the left of the URL.

Second, click the Body tab, select the option for raw and select JSON (application/json) in the Content Type dropdown.

content-type selection

When everything is ready, hit the Send button in Postman to send the request. You should see the newly created lunchWeekId in the response. You can also run a select statement against the lunch_week table to verify that a new row was inserted.

Lunch Week PUT Endpoint#

Next let's create another endpoint to update rows on the lunch_week table. We'll use a PUT endpoint for this. The concept is similar to POST, but we'll use an update statement this time and the route will contain the ID to be updated.

In this case, the body of the request may contain a lunchWeekId as well, so it's a good idea to return a 400 Bad Request error if the route does not match the body.

Here's the code:

Give this one a try in Postman as well. Remember that the route for the PUT endpoint requires the ID to be in the route, e.g., api/lunch-week/6.

You can try toggling the isPublished flag. For example if isPublished is false for lunchWeekId 6, then you could set it to true with the following call:

 

This page is a preview of Fullstack Svelte

No discussions yet