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:
xxxxxxxxxx
const createLunchWeek = (lunchWeek) => {
// for Postgres, we need to specifiy what columns to return back
// from the insert statement with a call to `.returning()`
return knex('lunch_week').insert(lunchWeek).returning('lunch_week_id')
}
router.post('/', async function (req, res) {
const lunchWeek = req.body
try {
const insertResponse = await createLunchWeek(lunchWeek)
// Since you can insert more than one row with `knex.insert`, the response is
// an array, so we need to return the 0 position
const insertedLunchWeekId = insertResponse[0]
const response = {
lunchWeekId: insertedLunchWeekId,
}
res.send(response)
} catch (e) {
const message = `Error creating Lunch Week`
res.status(500).send({ message: message, error: e.toString() })
}
})
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:

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.

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.
Get unlimited access to Fullstack Svelte, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
