This video is available to students only

Sveltekit Endpoints - How to Use Post, Put, and Delete

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#

This lesson preview is part of the Fullstack Svelte course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to Fullstack Svelte, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Fullstack Svelte