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

Adding Post, Put and Delete Endpoints to the Backend

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

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.

This video is available to students only
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

In the last lesson, we connected our express backend to our Postgres database, and we used next to fetch data and return that in our Git endpoints for our API . And now we need a way to create, update, and delete data. So we're going to do something similar here in this lesson, but we're going to use post, put, and delete endpoints. For creating new records, we'll use post, and for updating existing records, we 'll use put. We can get started with the post endpoint, and that endpoint will create a row in the lunchweek table. Then when we create a new row, the database will generate an ID for that row, and will return that ID back to the API caller. So we're going to use a helper function called create lunchweek, and then we'll add a router.post endpoint, and that'll listen for post requests coming into the server. So let's start with this helper function here. Over in the backend. So in our lunchweek.js file, we're going to create a new helper function here. And then with next and postgres, we need to specify what columns to return back from the insert statement. And we do that by using dot returning. So this is going to perform a SQL insert statement on the lunchweek table. It's going to insert the lunchweek object that we pass in, and it's going to return the lunchweek ID from the new row that gets created. So that's our helper function. And you can see VS code showing showing this function grayed out. That's because it's not used. So it's declared, but its value is never read. So next, we'll add the actual endpoint here. And post and also put endpoints can contain a body. So the caller is going to send in a JSON body. And that'll be the data that we're going to insert. And so that's why we have this rec.body call. And so this is going to listen for a post request. It's going to read the body out of the request. And then it's going to call our helper function. And one more caveat here is you can insert more than one row with next dot insert. And so the response coming back from that function is going to be an array. But in our case, we're just going to insert one row. So we'll return the zero position from that array. And so our response back will create a little object with just that lunchweek ID. And then we'll send that response back. And then we'll also handle our errors and send a 500 in the event that we have an error. Okay, so that's the backend code for this endpoint. And one cool thing that I like about our overall architecture is our front end is loosely coupled to the back end. So we can actually test the backend in isolation without even using the front end. And so testing post and put in points is a little different. Previously, we just opened our get endpoint in the browser. And we saw the results here. But when you paste a URL into a browser, you can only perform a get. And now we need to perform put in post request. So in order to do that, we're going to use a new tool called postman. And post man is a nice robust tool for making API requests. If you don't already have postman, go ahead and install it now. And once post man is open, then you can make requests to an API from it. And so what we're going to do is test our new endpoint with postman. And we're going to put a little JSON body in there. So over in postman. So on the left hand side, you'll create a new request here. You'll choose post. We'll do local host 3000/api/lunchweek. So that's our route to this endpoint. And then there are a couple of caveats here. So under body, we need to use raw. And then right here, we're going to select JSON. And what that's going to do is provide a header that says content type JSON. And then under the body, we'll create our JSON object here. So let's see, we're going to say week of and then is published faults. So JSON uses double quotes around the properties and around the values. Okay, so this is a simple lunch week object that follows our model. And we don't have a lunch week ID in this one because we haven't generated one yet. So we're going to let the database generate one. Okay, so let's check the back end, make sure it's running. And that looks good. So then go ahead and hit the send button. And so now we've got our response back. So we got lunch week ID six. And you can also double check this in PG admin. So previously we had inserted just five rows. So now if we run select star from lunch week. Now we can see our sixth row. So we inserted this row via our API. And then we got the ID back. Okay, so that's how we insert rows. And up next, we're going to create another endpoint that will update an existing row. So we'll use a put HTTP request for this one. Now the concept is pretty similar to a post. But this time we're going to use an update statement instead of an insert statement. So we'll use a update statement with next. The put request also contain a body. So we'll send in a body just like we did with the post. And then in this case we're going to need to send in an ID of the row that we want to update. And so our route for the put endpoint, we're going to add a dynamic variable to the route here and use the lunch week ID. And then the body is also going to contain the ID. And so it's a good idea to make sure that the ID in the route matches the ID in the body. And if that's not the case, we'll return a 400 error. And then just one more caveat here. In an express endpoint, when you call rest dot send, it doesn't actually end the function. So we want to make sure to also call return in these cases. If we didn't have the return statement, it would call rest dot send. And then the rest of this code would still continue to run. And that could cause some issues. Okay, so let's paste our helper function over. So our helper function says next. Select from the lunch week table, or excuse me, update from the lunch week table, where lunch week ID equals the ID that we pass in. And then update it with this new lunch week object that we pass in. And then we'll paste in our endpoint here. And again, make sure that you parse int the ID coming in, because it will come in as a string. And then assuming we pass this error checking, we'll await the update lunch week helper function. And then we'll just send an empty response back. Otherwise, we'll send a 500 error back. So let's give this a try. So back in postman, you can actually right click and choose duplicate tab. And then that'll bring the body over. It'll bring the headers over and so forth . And then we'll change it to put. And then our route convention here, we're going to pass in the ID. And then let's say we pass in ID six. And then the body here is going to also need that ID. So we'll say lunch week ID six. Okay. And we'll toggle the is published flag to true. So that'll be the actual change that we're making in the data. And then we'll check in PG admin currently for ID number six is published as fault. So if we go ahead and send this in. Make sure I saved this file here. There we go. So I hadn't saved the file. So the endpoint didn't exist yet. Okay. So that was successful. We got a 200. Okay back. Let's check in PG admin and just make sure that it actually stored the update in the database. So there you go. You see it toggled lunch week ID six to true. So cool. So we've got our put endpoint working. Let's test our error code as well. That's pretty easy now that we've got this in postman. So one of our error scenarios was if I were to pass in seven here and then I have six in the body. So that's going to give us a 400 bad request. IDs do not match. Okay. So we also can implement a delete endpoint. Same process again. We'll have a helper function that calls a next.del to delete a row where we pass in the ID. So let's add this one next. And then we'll use router dot delete and we'll pass in the ID of the row we want to delete. So these get a little bit easier once you've done a few. We'll parse the integer from the ID here and then we'll await our delete lunch week helper function. So back in postman copy this tab again. We'll change this to a delete and we'll say lunch week six. Hit send and we get a 200. Okay. Let's check this in PG admin. And that rose deleted. So that one's working as well. Okay. So that kind of deals with our lunch week object, which is the parent object representing a whole lunch week. But then we're going to have child lunch day objects and child lunch day rose in our database. So before we can finish this lesson, let's create some endpoints for the lunch day records. And these are kind of going to be copy and paste from what we just did. But we'll use a little bit of a different route convention. So it's nice to have a route that makes higher article sense. So the lunch day is essentially a child of a lunch week. So we'll use lunch week, then we'll pass in the lunch week ID. And then we'll use lunch day after that for the post. And then we'll do lunch week lunch week ID lunch day lunch day ID for the put. Okay. So at this point, you could try to challenge yourself and create these endpoints without looking at the endpoints. Otherwise, the final code for these endpoints is below. So I'm going to copy that in. So we're going to need create and update lunch day helper functions. And then we'll need endpoints for those as well. So this will be our post and put endpoints for the lunch day. Okay. And we can test those in postman the same way. Now, one thing to remember is a lunch day row needs to reference a lunch week row. And so we have a foreign key set up and that's going to enforce that rule that it actually exists. So we can do some testing around that as well. But let's try a lunch day post. So let's say post will use lunch week ID one and then lunch day. So that was our convention there. And let's check our data model here. So we're going to run select star from lunch day. So we don't have any rows on this table yet. But we've got a lunch week ID, a lunch day ID. That's the PK or primary key. Lunch week IDs are FK or foreign key. And we've got a day and a menu details field. So let's say lunch week ID. We'll say one. This should match the one from the URL. We'll say day. We'll say 2020 dash 10 dash 01. And then menu details. We'll say test menu. Okay. So this should insert a row into our lunch day table related to the existing row, the existing lunch week row ID one. So let's go ahead and send that. Okay. So we got our ID back. You can run our select statement again and check it. So there it is in the database. Okay. And let's try the put endpoint for this. So I'm going to copy this. And so our lunch day ID was also one. So for the put endpoint, we need to have that ID in there. And then in the body, we'll say test updating menu. So we change that to put. We've changed a little bit of data. And let's send that. Okay. Oh, we need the lunch day ID in the body as well. So lunch day ID. That's going to be one as well. Okay. So that looks like that RAM. Let's check PG admin. And so now you can see we got test updating menu. So those endpoints are working. I'm going to try one more error path here. So if we tried to do a post on a lunch week that doesn't exist, let's see what happens there. Yeah. So this is our foreign key working to maintain data integrity in the database. So it won't let us insert an orphan lunch day record where the parent lunch week doesn't exist. Okay. Now let's cover an important note about security. We haven't discussed security yet, but it's important to know that our backend endpoint is completely public. So when we go to our browser, we hit this endpoint. We're getting data back without having to authenticate at all. And in postman, the tests that we just did, we're able to insert, delete and update data in this API without providing in sort of any sort of key or credentials or authentication. So this is completely public. And if you were to deploy this to a production environment, it would be wide open to the internet. So it's good to just kind of understand that. And we're going to resolve this gap later by using Auth0 and JSON Web Tokens, but it's kind of just good to understand the difference and what we've set up so far. And then one other point that we can make is we haven't introduced a concept of segmentation by customer. So lots of SAS applications are multi-tenant, which means that we could support lots of different customers inside that SAS application. And they would have their own kind of independent view of the application. And so we haven't dealt with that yet. And later on, we'll have a module on changing our architecture to make the app multi-tenant. But for now, we've got a real kind of simple architecture with no security and no segmentation by customer. And we'll address that later. OK, so that's it for this module. And we covered a lot in this module. At the beginning, we didn't have any persistence at all. And so we've covered installing Postgres. And now at the end of this module, these four lessons, we have an API that creates, reads and updates data in a Postgres database. So we're really starting to learn about the full stack, all the different layers that all work together. And so this was all back end in this lesson. And we're going to jump back to the front end in the next module. And we'll update our Svelte app to interact with all of the new endpoints that we just created. Thanks a lot. And we'll look forward to seeing you next time. [BLANK_AUDIO]