How to Easily Call APIs With Fetch and Async/Await in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey how's it going guys my name is dom and today i'm going to be showing you how to use the fetch api and a sync08 to call apis in javascript alright so the reason for today's video is because i want to show you how i typically call my apis from the front end and of course doing it in a modern way using a sync awaits alright so this right here is going to be the test api for today's video i developed it for myself or i developed it for this video and it's going to be a simple api containing a list of users and the country that they belong to so as an example right here localhost at port 3000 forward slash users then forward slash the username forward slash country is going to give you the username decodes uh country information so myself right so if i send this across here we can see we get a 200 okay and it says my country is australia my internet code or shortened code is going to be au and the capital is going to be canberra so a very simple api here which is also going to return a 404 if the username cannot be found as an example if i say something like apple.juice here sends it across we get 404 not found for that user so we're going to be demonstrating the checking of status codes and of course handling that kind of thing but this middle part here is going to be the only interactive or dynamic part of this api so putting it back to d code and of course we get that response back once again so going inside the url so going inside the browser right here is this user interface so a very simple ui built using html with an input field and a retrieve button so as an example if you pass through decode here press retrieve we of course want to show the user that this person decode is from australia okay so i'm not going to be showing you the code for the api in today's video because in many situations for yourself you either don't care about the code for the api or you actually don't have access to it so i'm treating this test api like a real api okay so going inside the text editor right here we have this field set the input field with an id of username get and the button to of course submit or you know retrieve that user's country all right now i am using an on click attribute here now you probably shouldn't do this but as an example for today's video i'm using on click all right and it's going to be calling a function here called get user country so this function is yet to be defined we're going to be doing that to of course demonstrate the api usage all right so going down inside the script tag right here we can begin by simply defining this asynchronous function called get user country so we'll say here async gets oops my mistake async get user country just like this okay with async function at the beginning of it my mistake so async asic function get user country all right we're good now this function is going to first retrieve the username from the user's input so we'll say here const username is equal to then document.getelementbyid passing through here username get then dot value now also real quick the usage of async here is going to make sure that we can now use a weight when calling the api so more on that later but this basically allows us to write a synchronous code in a nicely formatted way and it looks very similar to normal synchronous javascript all right so we have the username we can say look if there was no username provided or basically if it's an empty string we can simply return and cancel everything and we'll just say here alert please enter a username just like that i'll save this go back in the browser here i'm going to say retrieve and we get please enter a username okay if i was to say something like decode sends it again we of course do not get that error so of course we have the error handling for the user's input okay next step here is going to be to simply build up the endpoint so we can see here that this api is hosted on localhost that port 3000 forward slash users and then of course you have essentially your route or whatever it might be okay so we're going to simply copy this url right here i'm going to say const endpoint is going to be a new instance of url so a new url object here in javascript so this fight here is going to have a very similar purpose to being a simple you know plain string but the fact that it's going to be a url object is going to allow us to easily add query parameters to the url more on that later but for now we can use the back ticks neither one on your keyboard here which means now we can paste this in and we're going to replace decode with the actual username provided we'll use the dollar sign and then curly brackets to simply say here username okay now of course the back tick key is going to be javascript template strings allowing us to of course have this dollar sign and pass in that username i can now simply console.log the endpoints url object i'll save this code back in the browser i'll say decode then retrieve and we get this url object right here so we can see it's going to pass the url string which we provide and of course break it up and we've got access to this property right down here called search params so this right here is my main reason for using this url object okay so let's say your api requires you to to provide authorization details in them in the fashion of a token so you might be provided with a token in your api dashboard on whatever app you're using and they might say to provide that token as a query string in the url okay you can easily do this by simply saying endpoint dot search params dot set and we can say here set my token to be then your token goes here all right now you have to check your api documentation for whatever service or app you're using to find out what this url parameter should be called and of course get your actual token tied to your account so this right here is one of the methods which api service might require you to provide authorization information okay if i was to say console.log the endpoint but this time i'm going to say endpoint.2string it's going to take the url add in the query parameters and provide you with the full built up string i'll save this go back in the browser provide decode press retrieve and we get here this completed url we have the token appended to the url right here so we're good to go now if you were to provide any characters to this uh to the search parameters here so back right inside here they are going to be automatically url encoded so you don't need to worry about doing anything like you know you know encode uri component or anything like that it's all handled for you so a very nice way for you to build up a url and what's nice is the fetch api is going to support this object right here so as an example i'll say now const response is going to be equal to then we're going to start using the await keyword we'll say here await then pass in the point just like that my mistake guys sorry awaits then space fetch okay very important i'm going to fetch the end point right here so now because the api call is an asynchronous operation it's going to wait for the response to come back from the server side before hopping down to this code down here this right here is the beauty of using a sync await previously when using promises you have to say dot then dot then so on this right here is a lot easier to read and of course understand we can now say console.log the response i want to show you this and then show you a way to provide authorization details using headers i'll save this go back in the browser i'll say decode press retrieve then we get this response back from the server side alright so we have some very important things here we have the body which of course is your json data in this case right here and you have the status code so you can use both of these things here to of course update your ui or show messages back to the user whatever it might be all right now before jumping into this right here i want to quickly show you how to provide auth details using headers all right so we can see here in the in the network tab of the developer tools the response has gone through i might just clear it and try it again okay so we can see here we have the response sorry the request going through to the server side okay and we have things like the headers okay so i'll expand this real quick we have things like the headers which are going to be passing through so this right here is going to be your request headers right down here all of this stuff is default by the browser but you can provide an authorization header if your api service requires you to do so so it's going to be up to your service once again whether it's through the url query parameter or a header like this so i want to get back in here now and i want to say look away to fetch then provide a second argument here i'll say headers is equal to then say here authorization just like that then say your token here so authorization is also a very common way to authenticate or to authorize with an api so you're going to have to once again read your api documentation to figure out what this should be your token order or whatever it might be and of course provide it using a header if you require to of course do that i'll save this go back in the browser sends it across once again press retrieve and now we can see we have of course the authorization header with the token right there now one quick thing to mention with providing this authorization details okay so whether it's a url token or it's your token in the headers here make sure uh or you know sort of what can i say like try your best to hide your users api keys in the back end so if you're using or if you're developing personal applications for yourself where you know you don't really mind if your token might be visible to anyone else or if the details being retrieved are not too sensitive then you might not care about that data being linked but when it comes to a real application you definitely want to try your best to hide any tokens on your own server side so you might store some token in the database instead and simply file for request provide a username something like that and then your server side can actually retrieve that token instead of it being visible in the front end so it's always better to try and hide things when you can but like i said if your api is you know providing unsensitive data nothing too serious then you should be okay to provide it here but like i said be very careful with exposing tokens to the public all right anyway once you have your authorization provided we can now go ahead and check on the response so going back inside here we're going to say something like this right we're going to say look if response dot status is equal to 404 so if the user provided a username which does not exist we'll say alerts username not found something like that we can now simply return out of that i'll save this and try it out so i'll provide the apple.juicy username once again so an unknown user press retrieve and we get here username not found in the alert menu of course you'd have to provide your own api to update it and you know make that data display but we can see there we have that check perfectly in place you know if we're all good the user was found we've got the response we can now start using the data so here we're going to say const data is equal to then awaits response dot json so converting the response from what you get here is a readable stream so by default like we saw earlier the response has the body which of course is a stream so in order to convert that into actual json it's going to be an asynchronous operation so we're going to use await once again we're now going to say once the data is provided to us and we have a javascript object for that data we can simply alert that data to the user so i'll copy what i had earlier on in my testing example we can see here we're now just saying look i'm going to say the country is going to be data.country so using the template strings once again remembering that data here this data object is simply referring to this object right here in the api response so data.country then newline capital is going to be data.capital or n a so if the api returns now or undefined for the capital i'm going to say here n a then of course internet code and data dot internet code so very straightforward here i can save this and go back in the browser i can now call this api say retrieve and we get here for decode country australia capital canberra internet code au so that is how you can call apis using the fetch api in javascript and async await hope today's video helped you out if it did drop a like and subscribe and i'll see you in the next one
Info
Channel: dcode
Views: 49,008
Rating: undefined out of 5
Keywords: javascript fetch, how to make http requests with javascript, javascript http, how to call apis with javascript, how to fetch api with javascript, how to use fetch api in javascript, how to fetch with javascript, how to call api with xhr in javascript, xmlhttprequest javascript, how to call apis with ajax in javascript, how to use ajax to call apis in javascript, how to use async await in javascript, what is async await in js, what is fetch in js, what is fetch async await
Id: 1Okmw8ggD1Q
Channel Id: undefined
Length: 15min 25sec (925 seconds)
Published: Mon Mar 28 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.