SvelteKit API Routes & Endpoints

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on everyone my name is Hunter and welcome to a brand new spell kit video in this video we're going to be learning about endpoints or API routes in spell kit which are defined inside of the Plus server.js or dot TS file now we look at this felt kit docs here we can see that the server.js file is going to export some functions that correspond to http verbs like get post patch put and delete these functions then take in a request event argument and return a response object so essentially spell kit enables us to create an API within our spoken application that we can consume both inside the application and from other sources outside the application now we're going to take a look at how we can Implement something like this and we'll be building a little bit of an example project I'm starting out with a fresh spell kit skeleton application and we're going to start by creating a new directory within our routes called API and then we're going to create another directory inside of the API directory called posts and then we'll also create a server.js file inside of this post directory and we're going to start off with defining a get function here and it kind of seems like we're jumping right into it but I promise this wall makes sense here in just a second so we can export cons to get this is going to be a function and what this function returns is actually a response object so we can say return new response and since we're building a rest API of sorts let's go ahead and we need to convert this response body into Json and we can do so by running json.stringify and then passing some a JavaScript object here so we can just say message is hello and then this also takes in an optional init which is kind of where we can set the status and some options so let's just say status is 200 for example and then let's just test this endpoint out and I'm gonna be doing all the API testing through thunderclient which is an API client or an HTTP client I should say similar to postman except it's an extension for vs code that makes it you know super easy to test your API within the within BS code without having to go back and forth so let's create a new request it's going to be two localhost 5173 which is where my app is running right now and we'll say slash API slash posts and then we can click Send and you can see that we in fact get back that message and then we can modify the status code for example and you'll see that we do in fact get that status status code modified on our client as well so this is cool and all right but let's actually start to extract some information from this request so if we look here on the documentation it takes in a request event argument and if we click on request event we can see that we get access to all this information one of which is request so let's go ahead and pull request out and that's going to give us access to headers right so let's just say that our app our API we want to have authorization headers that need to get passed in order to access the API and if they're not passed and they're not valid then we're not going to like let them access the API we can actually pull out the authorization Header by saying cons auth header equals request.headers dot get and then we'll just say authorization right then we can console log the auth header real quick just to see what it looks like now inside of our HTTP client or thunderclient we're going to say headers we're going to go down here we're going to type in authorization we're going to pass my auth header as an example here and then we'll click Send to see it logged to the console so we do get access to this right and then I guess a little bit of an example scenario would say like if there's no off headers and this would obviously be where you would run your your checks to make sure that auth header is actually a valid token of sorts but for this example we'll just say if there's no off header or we'll say if the off header is not equal to say my auth header then we want to return a new response we'll say json.stringify the message will be invalid credentials and then our status code is going to be 401 for unauthorized now let's just test it without or with the authorization header and then we'll just change this to one two three oh it's invalid and if we just take this off all together we can see that it's still invalid right so we're not able to access that so that's kind of how you can set up some authorization into your API endpoint let's go ahead and add that back in here okay so now let's say that we have an environment variable that contains an API key and we need that API key to go out and reach out to an external API to pull some data and we don't want to expose that on our clients and we have multiple load functions that would require to make require making the same request we can just Define it in this endpoint here and then from our load functions we can just fetch this endpoint and that will return all that information for us so let's just pretend that this dummy Json posts API here it requires a an API key of sorts so inside of our file explorer here we can see that we have a EMB file defined and we just have a variable named secret API key to access this inside of our server.js file it actually is super super easy we can just say import secret API key from we'll say EnV static slash private now what we can do is we can just console log the secret API key for example and then let's just test by sending a request here we can see that we do in fact get that API key inside of our server.js file so that's how you would use environment variables and API keys inside of these requests as well and this will never be exposed on the client so that's great all right now let's go ahead and fetch this data from the dummy Json API and then return it back to the user if they have you know an auth header for example so we can say is we can say cons res equals 08 Fetch and then we'll just pass this in foreign data equals awaits res dot Json and we actually need to make this an asynchronous function now because we're running some asynchronous code and then instead of just returning this message hello we'll just return data now whenever we make a request for posts you can see here we're going to get back all the same information that we received here right pretty cool this could also be you know you going out and fetching information from a database for example you could do that here as well so let's just say that we want to also give users the ability to limit and filter posts right so if we look at the wjson API we can see that they have the ability to limit and Skip posts bypassing some query parameters and we want to extend that capability to our you know private API endpoint what we can do is we can also take in a URL here and then we can actually access those specific query parameters like this we can say const limit equals number we're going to convert it to a number first and then url.search params dot get we'll say limit and I'll show you what this is doing in just a second and then if this does not exist we want to set the default to let's just say 10. and we can also set one for a Skip and this will be set to Zero by default and we Skip and then this will be skip now we can convert this response are we going to convert this fetch request into a template strings here and we can pass in question mark skip or limit equals limit and skip equals skip right so now let's test this out inside of our thunderclient we can say question mark limits equals 10 and Skip equals 10. so we're going to skip 10 and we're gonna get 10 back so our first post should be for ID number 11 and we should only get 10 of them so let's hit send so you can see now we're getting we're starting with 11 because we skipped the first 10. and we only have a total of 10 right so that's how we can access query parameters and these don't have to be limit or skip it can be whatever you like we can just say for example we could change this to dog just to give you an example as to what you can do obviously limit and Skip are our API standards but we can just say dog and Skip right let's save this and then we'll change the limit to dog uh let's see here oops I gotta change this as well dog now let's make that request and you can see that we get the same response right so let's obviously change this back to limit here so it's not too confusing but we can access whatever query parameters you want to provide in your API you can provide them and then access them like this right so that is getting data let's talk a little bit about posting data to the endpoints right so let's say export const post equals async and we're also going to take in the request because we're going to need to get the request body so we'll say request here and then what we're going to do is we're going to pull the body out by saying const body equals await request.json that's going to convert the it's going to parse the Json out of the response body and then we'll just console log body just to show you what this is going to look like and then we'll create a new request inside of our thunderclient and we'll just duplicate this one here and we'll change it into a post request and we'll just be posting two posts and then the body will say title my first post and the body or the content let's say is going to be my amazing post right now when we send this here you will see that we're getting an error what is happening here oh Handler should return a response object so I made a mistake here of not returning response object let's return a new response json.stringify and we'll just say message success and we'll say the status code is going to be 2014 created because they just created something for example now let's make this request again sorry about that now you can see that in the console we get the information that we passed through this request so we get access to title and content so we could just say body.title body dot content we could access all those variables here as well and let's just go ahead and put our auth header check here as well and we'll actually need to get the header from the headers again and again post requests work the same way so if we don't have this authorization header set we're going to get a 401 unauthorized and if we do have it set you can see that we do in fact get that posted to the server cool sounds like actually implementing this with an application that we're developing for a Blog for example so let's go back into our file explorer here we're going to close up the API for now and then we're going to create a new directory inside of the routes we'll call it posts it'll be a Blog right and then inside of this we're going to create a plus page dot JS and then we'll also create a plus page that's felt now for the plus page.js if you're not familiar with loading data and so I could have a video on that I'll leave a card in the top right as well as a link in the video description but we're going to export a load function and this is going to return the post so this load function is actually going to take care of going out and fetching the posts from our own API that we built and then returning that back to the page.spel file so we can display them right so let's go ahead and set up some initial structure here within our page that's felt so we'll set up a script tag we know that we're going to be receiving data from the page.js file and let's just set up an H1 with the title and a p-tag with the body right now inside of our page.js what we can do is we can actually say const fetch posts we'll Define our method a function here equals async and we actually need to take in Fetch from the load function because this is going to be an internal request here we'll say const res equals 08 fetch now this is what's really cool about using this fetch here we pass it into a page.js is that we can use a relative request so we can just say for example slash API slash posts right which is slash API slash posts it's going to hit this server right it says we're making a get request by default with fetch it's going to hit this get function here right now we can say const data equals await res dot Json and then since this is going to give us back a object with posts and then an array of posts what we want to do is we actually pull out this posts here so we'll return data dot posts now what we can do is we can actually return this function by saying return posts fetch posts right now we'll have access to those posts inside of this data prop here so we can set up in each block so we say each data.posts as post move up title and body and then we'll say post dot title whoops post.title and post dot body I think that's what they're called right yep title and body over here we're getting the title embody from this API so we're going to have this array we're basically going to have an array of posts inside of data.posts right and then we're going to go for each post we're going to place the title in a H1 tag in the body and a P tag for our page right now let's click save and then we'll make sure this is saved as well and let's navigate to that URL so we can go to slash posts and we're getting a an undefined property here can I read properties of undefined reading length so data.posts that should be an array each data.posts so this gives us back this fetch method here this fetch call here gives us back okay so we didn't actually we actually don't have an auth header set on our fetch request so let's just take this out for the time being so we'll just remove the auth header check here on this one and now we can see that we do in fact get all these posts displaying here right we have that default limit of 10 set still so let's go ahead and save now we get access to all of these posts cool so let's just say that now we want to be able to click on one of these posts and bring us to the full post page right we can also Implement that within our API as well using the params so inside of API and posts we can create a new directory called post ID and then we can say A Plus server.js will go in there as well so now we have a param so now we can say export cons to get equals async and what we're actually going to pass in here again is going to be the params right so now we're going to be able to access the params the same way we would do that with a normal route in soil kit so we can console log the params really quick and just show you what that's going to look like and we'll return a new response go back into our thunderclient here we will say let's see here we'll make a request a get request to this URL now remember slash whatever comes after post is going to be that post ID param so we could say oh say we want to get Post 25 for example now if we remove this we can remove this Json content here because we're not actually passing anything we're not making a post request when you remove this body and then hit send you're going to see that we get message success right so now what we can do is we can actually go out and get this specific post information and return it on this page as well so we can just say const res equals await Fetch and we could see obviously down at the bottom that we're getting the post ID here in the console so we can say fetch and then we'll say we'll use some template strings Dummy json.com Post and then we'll pass in the params.post ID and then data and then we'll just pass data here now we make a call to Post 25 for example we're going to see that we're going to get the post with the ID 25 right which means we can also do the same thing inside of our post directory outside of the API route so we can just say for example post ID and then we'll make a plus page.js and we'll also make a plus page that's felt and then inside of the page.js we'll say export const load equals Ace equals this we'll pass in Fetch we'll say const fetch post this is actually going to take in a parameter of an ID we could say const res fetch we're just going to say slash API slash posts slash the ID right because this is going to be we're actually hitting our own API with this one then data is awaits res dot Json and we'll return data and then inside of our load function we can just return post is fetch post passing in the params or the params which we need to actually import so say params params.post ID and this may be a little bit confusing because we're using the same syntax here but this is entirely this is an entirely separate param than this param so this param is internal to our spoken application this param can be used by anything right so let's return that and then inside of our let me close out some of these first instead of our page that's felt for the individual post page we can just export let data to accept that data prop and then we'll set up another div here and we'll say H1 is going to be data.post.title and then the P tag is going to be data dot post dot body so now if we navigate to for example post slash 25 in our application we now get the 25th post here which is happening by our load function hitting our own API which then goes out and hits the dummy Json API and returns that data right so that's essentially how you can use endpoints again I'm not sure if this example was was a great one but I wanted to show how not only you can you know set this API up to be consumed by multiple different endpoints or multiple different clients but you can also consume it from your own application again really in this in this exact scenario that I outlined here you'd probably want to just use the load function page.server.js load function to handle this because we're only accessing it really in one place but just to show you an example of how you could access that same API endpoint from anywhere in your application or outside of your application right so I hope this video has been informative for you all if you found it useful I would appreciate if you would like and subscribe if you guys have any more specifics you'd like me to cover with regard to endpoints or anything related to spell kit I'd be more than happy to take into consideration we also just recently started a Discord server so feel free to join we're trying to have some you know meaningful conversations in there about swell kit and some of the best practices so feel free to hop in there ask me any questions you may have and if not I will see you guys in the next video [Music] [Music]
Info
Channel: Huntabyte
Views: 33,232
Rating: undefined out of 5
Keywords: sveltekit, sveltekit tutorial, sveltekit crash course, sveltekit +page.js, fetching data with sveltekit, external data sveltekit, sveltekit load functions, sveltekit props, sveltekit endpoints, route params, sveltekit routing, dynamic page sveltekit, sveltekit url, sveltekit form actions, sveltekit forms, svelte forms, sveltekit actions, form actions sveltekit, use:enhance, endpoints, +server.js, +server, api route svelte, sveltekit API routes, svelte routes
Id: qlmDj7q2x0c
Channel Id: undefined
Length: 18min 58sec (1138 seconds)
Published: Sun Oct 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.