REST Web Requests with Data Caching with ASP.NET Core Web API | Xamarin & .NET MAUI 101

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're gonna see how we can make easy simple crud operations with web requests from our mobile applications all using the power of c sharp so tune [Music] in [Music] hey everyone i'm james montemagno i'm back with another xamarin 101 video i'm real excited about this week's because we're talking about web requests using http client the ability to take all those awesome bits of stuff on the internet pull them down into our mobile application but also at the same time not only get data but also post data too back to a web client if you're brand new to the channel i'm glad that you're here we've been building out awesome mobile applications with xamarin.csharp.net and i have a whole xamarin 101 video series i'll put up over there in the corner but make sure of course you subscribe and ding that notification bell because i put out videos every single week right here on the channel as we guide through our learning journey together all right so today what are we going to do well we're going to take a look at how we can use http client which is built into net itself to make web requests into an asp.net core web api of course you can do with any web api it doesn't have to be asp.net core but since i'm a c-sharp net developer that's sort of the beauty is that i can build my mobile applications desktop applications and my powerful web backends and even microservices and all that good stuff now i'm not going to walk you through how to build that back end i'll show you kind of show you it's the easiest web api in the world but we do have great documentation and things like that so i'll show you what that looks like and then i'm going to pull down that data upload some data give you some of my best practices and additionally how to store and cache that data locally at the very end we'll talk about data synchronization so tune into that all right now i want to show you that we have tons of great documentation and learning pass on microsoft learn and of course onto our docs but these are self-guided learning paths anything from learning c-sharp creating web apis building mobile applications all sorts of good stuff you can browse through all the different learning paths there's all sorts of great stuff here if you were just to put in like an api in here you'll see create a web api with asp.net core and even one for swagger which is a really cool way of adding documentation with open api so i have published my asp.net core backend to the internet it's here and this is swagger and swagger is sort of like a um automatically generated browser of apis so here we have the verbs get post get a specific id put and then delete so those are like the different ones so get is obviously get post is to basically insert or add a new item here get within a specific id is going to get a single item and then put is actually a little bit different put is please update this item okay so put is to update an item and then delete is obviously to delete so here what's nice about swagger is that you can actually come in here and execute and test out the api so for example this is the api mott's coffee dot azure websites dot api coffee and if i zoom in here you'll see that it returned a single json blob back to me okay and what that does here is it just visualizes it very nicely so i added one by default right there i can also come in and i can also post so here i could actually add another one if i wanted to i could give it a new id and i could say two and then hit execute if i go back over here and hit refresh now it's going to have two items same thing if i scroll up top here and go ahead and hit execute on my get it's going to now return two of them back in a json blob so what we want to do is not only be able to test our web api client we also want to be able to put this into our mobile application so let's go ahead and first look at our web api i have a simple very very very very simple uh web api over here it's this one's built with done at five and it's simple asp.net core web api you can see here's net five right here um and what i've done is i've actually shared my coffee model with my mobile applications and my web api so it's actually kind of nice as you can share code between your web backend and your mobile applications so this coffee application is crazy simple um it's actually just built in here's the route api controller which is basically slash coffee and there's very simple gets i have a static list of coffees all it's doing is getting get a specific one you know posting adding a coffee pudding updating a coffee deleting deleting a coffee so really nothing special there it's just a blank web api canvas nothing like that i did publish this to the internet to make it easier just to kind of show this off i will talk about local debugging which is awesome and what i've done here is if it's in release i've also added swagger and https in there which is kind of nice you don't have to do that you can just only have it in debug mode development mug mode to add swagger which is that definition there so what else do we have okay well we've pulled out our coffee now we're sharing just the simple model between our web api and our mobile app but i've also created a internet coffee page an internet coffee view model and and internet coffee service so previously we had a coffee service and this was pulling from a sqlite database that we can see here and it has ad coffee it has removed coffee and it has get coffee so what i've done is i've basically duplicated that here and i have internet coffee and we're going to get coffee we're going to add coffee we're going to remove coffee okay now at the same time i've also created an internet view model and it is actually the same exact view model as my my coffee data offline cache that's stored this internet one the only difference is that when i hit add on the ui it's going to add it to our internet coffee service it's going to remove it from our internet coffee service or simply get it in the refresh so very very simple and of course i could add updates and things like that too okay so let's get started this one's really simple we're going to start in our internet coffee service here and here what i've done and i want to show this off to everybody is that i have a just base url give me the base url where my api lives so i don't have to type it over and over again and if i'm debugging locally alright this is really important android emulators don't talk on localhost but they talk on 102.2 and on ios it talks on localhost as long as you're on a mac of course now for this purpose i just published it really easily to a free tier on azure so i could go ahead and give it a go and have a base url here note though that it's really complicated to debug https locally certificates all this stuff it's really messy so what i do is i go ahead and i turn off http s for local debugging on my back end so that way i can debug it locally there is a little bit of setup that you need to do in your ios and android application to allow clear text but i'll put links down below so you can read up on that it's very easy to do just a few config files so this is my base url and for right now i normally have an interface and i have some dependency injection stuff but i'm just going to create static stuff so i'm going to create a static i'm going to create an http client okay i'm just going to say client here there we go and an http client is sort of this base class for doing http requests or rest requests off to our back end and we have all sorts of stuff in here so the first thing we're going to do is just create it and i'm just going to create it in the static constructor and say new http client now on the client itself if i zoom in here we can see that i can do client dot okay and i have get async send async post async if i go down here i also have delete async which takes in a url request get async again like i said get stream get string there's all sorts of different helper methods in here post put sent so these are things that are very similar to those verbs that i just showed you okay and you have timeouts you can really control this now if if you don't specify a base url you'd have to enter that url every single time so what you can actually do here is you can give it a base address all right you can say new uri and give it this base url so that's kind of nice so you don't have to post that that url every single time and concatenate it it's going to say this client here is for this url no matter what all right let's just start really simple okay let's just get our coffees so all i'm going to do is say var json i'm going to say await client dot and in here i have a few ways of getting data i have get async get byte array async get stream async or get string async now the get async is just generic it just gives me a message back and we can use that in most instances when we don't know what we're getting back but i know i'm going to get a string back here so i'm just going to go ahead and say get string async and my request url is api copy that's it because again remember it knows that i already have that default url that's in there so that's going to get back a string and if you remember if we open up the browser one more time here it's going to get back to this string which is an array of copies now we'll also have to deserialize this json from the internet basically and you can use json.net or newtonsoft.json to do that or any other json deserializer that's out there but we're just going to use json in here json.net so we're going to say var coffees here i'm going to say json convert dot and json convert i'm going to bring in newtonsoft.json and i can say deserialize object and this is going to be an innumerable of coffee because we know it's an innumerable coffee right that's how we know it is i'll just pass in json and then it'll return those coffees boom just like that so now we have our api our coffee and our coffee's coming back and just like that what i want to do is just debug the get first okay and then we can look at the ad and then we can look at the delete as well so remember very simple literally three two lines of code it gets the string asynchronously deserializes that object asynchronously back and that's it this is sort of the base of every application i've ever written ever for all intents i would say um that's that's sort of important to kind of know all right so here our application is launched now so i've added another item in the fly-out menu so we can now come into our internet coffee i'm going to go ahead and pull the refresh here now this is going to make that web request often to the internet there we go let me go and minimize this down and we can see that i have my coffee right here look at that i have the two items coming right in which is really really cool now if i go ahead and simply step over this we're gonna see that i have the two coffees check this out so very very simple i have the delicious coffee and then the delicious coffee number two from the second internet roaster and then just like that we have two different coffees right there at our disposal coming from the internet we just made our very first web request and we are good to go okay now that we have gone ahead and gotten the coffees let's go ahead and insert a coffee so we can insert a coffee pretty easily what we need to do is come in and make another web request let me go ahead and zoom in here so i'm going to say var response equals await client dot and here instead of doing a get we can do a post async all right now post async takes in a request url and an http content there's different types of http content stream extremes and strings and objects we can actually pass it string content and we can pass it json because we're able to do that and automatically our server will be able to deserialize that which is very nice so our api is actually going to be the same as before api slash coffee and then what we want to do here is simply pass in some content okay so what we're going to do is we're going to say var json equals and again we're going to use json convert dot and we are going to d or serialize an object sorry and pass it the coffee so this is the coffee that i created right above and again this may not be the best practices of creating a randomly generated id you should probably let your server handle that but for this instance we're going to do that and now we can do is we can say var content equals and we're going to say new string content okay and here we're going to give it some strings which is our json i'll give it encoding so we'll say encoding [Music] dot utf-8 and then what we need to do is give it a media type so let me go ahead and put this down on a new space here and this is going to be application slash json okay there we go so that's going to be the the content that we send in so var content response and what we can do here is we can say if you know not response dot is successful we can get the headers status codes successful status all that good stuff we can go ahead and do something and that's really simple and this is a little bit um a little bit more complicated because we're passing it data right we're actually sending it up there um compared to this get which is like hey give me the object send it back down now for the remove we can actually do a very similar thing um we can actually just do a you know not do a post but we're going to use another verb which will be delete so we have our post and here we're going to do for delete is say await and then client dot and if we zoom in here we can see that i have a delete async now this does return an http response for me so i can do the same exact thing i could say var response equals and then here i could say the request url in this instance we can use some string interpolation and what i'm going to do is say api slash copy slash id because again if we looked at the coffee controller it's going to tell us api slash coffee the id and that's how it's going to look it up and delete it delete it from the list so that's all we really need to do and i can do the same thing here i could say if response is not successful yada yada go to town there so let's go and test this out and add some breakpoints and actually debug it okay so what we're going to do now is we're going to go off serialize it add our new coffee but also the way of deleting it so let's go ahead and get this up and running now there we go so so far not too complicated hopefully we have simple you know rest commands that are out there and then our applications calling them with the http client so here's internet coffee let's go ahead and pull the refresh here and we should get back our two coffees coffee one coffee two and let's add one and i'll say my coffee and then that's the name and i'll say roaster james hit okay this is going to go off it actually just made the web request it was successful i can actually look at all the stuff there hit ok it's going to hit my refresh code so it's going to go off refresh the data from the database and boom there's my coffee and i can prove that it's actually in our back end because if i go here hit execute here we go internet coffee jamescoffee coming in now if i come in and i hold this down and hit delete it's going to do the same thing remember we made our delete api coffee our response was ok successful hit ok here and if we go back into our back end again now hit execute we can see that coffee is gone it's completely gone and it's gone from our application which is very very nice boom good to go so so far what have we learned well we've learned that we can use http client which is built into net just built right in there and json convert and with part of newtonsoft.json and json.net to serialize and deserialize and get our objects from the internet which is super nifty in my personal opinion now there are some other cool mechanisms like if you have a swagger definition you can automatically create a client and it'll do a bunch of stuff for you that's built into visual studio i'll link to another video that i did with my buddy glenn talking about that you can also use some other nifty apis out there like refit is a really cool one that you can go ahead and have it generate very simple apis i want to show you the basic building blocks and there's amazing.net libraries that do a bunch of really cool things now let's talk about one other thing here which is how do i cache my data right what if i'm offline you know completely offline here what do i do in that case well first you should probably try catch all of these things because if you're offline it's going to throw an exception and bad things are going to happen so you definitely want to do that for sure but you can also cache your your data locally you can put that in a sql database but i'm not about sometimes caching the data locally and storing the objects i want to cache the web requests so in this instance since we're just talking about online data i'm going to go ahead and use a library i created that is called monkey cache so monkey cache actually if you just go to browse or your nugets and type in monkey cache one word there's a bunch of different versions of it i've installed the file store which just saves different files to disk in the correct place and the cache there's also a sql lite version and a light db version so you can pick and choose what you want i like the file one it's very very simple so monkey cache is a cache it's not a database necessarily it's not meant for that but it stores your information in a cache library so if your users you know upgrade their device or the system wipes it out it clears it out but it's good for caching web requests the only setup you need to do is inside of your application startup and set the application id so this gives it a folder to put the data into you put everything into this barrel all right and that's um sort of the basis of putting items into barrels with different keys there's also a few other libraries i'll talk about later that do some similar things but monkey cache is the one that i built so i sort of like it so let's go back into our internet coffee service here and i'm just going to do obviously the web request caching for the get because here this is going to make the web request every single time so here's what i'm going to do is i'm actually going to add a little helper library not library but a little helper function here and what this does is it says get async and it's generic so you can reuse this method over and over again give me a url give me a key and give me how many minutes you want this to be valid for and if you want me to force refresh this basically ignore the cache so this is pretty cool i'm going to bring in my monkey cache library there we go and what this says it says use xamarin essentials and see if i have network access if i don't get the information from the barrel all right now if there is information in the barrel then go ahead and just deserialize that object asynchronously else go make the web request like we saw earlier add that into the barrel and then simply go ahead and return that object and if something goes wrong let me just go ahead and deserialize this here so easy peasy so this is really cool so now we can do is we can come into this get coffee and now we can say is get async i'm going to say innumerable of coffee and what this is going to do is give me a url so api coffee all right key i'm going to say get get coffee so whatever you want it to be that's the key it's going to use and we're going to simply say use the default so minutes 1 x etc etc and here now that it's just asynchronous i can return the get async and now if i have more gets in the future i can simply reuse this over and over and over again so now let's go ahead and run this and see how this works so um all built in you can reuse this get method over and over and over again um i like this generic version of it here okay so let's launch the application and what we're gonna do is we're gonna go ahead into internet coffee i'm gonna hit refresh now this will be the first time that actually gets data so we can see that the data is empty and then what we're going to do is get that information store it locally because we've gotten it from the internet there it is and then i can continue on now we've cached this web request for a minute so if i actually pull the refresh again it's not going to make that web request call we can see here that this got the cache right here from the barrel so it went and grabbed it and we're good to go now in this instance it's going to return it and just pop it right back up into our ui but what happens if let's say i close the application i put it into airplane mode and then relaunch it again well now because we have monkey cache here it's going to detect if i have internet or not with xamarin essentials and it's going to return that list directly back to me there it is i've now cached those coffees offline for as long as i need to because it doesn't check the expiration it's just always going to be there my application is good to go now it's very similar in this instance like reading it from the database but here this could be for any web request it could be you know any data that you just want to make sure your user has available to you it's one way and another tool in your toolbox all right now there are a lot of other mechanisms out there for getting data caching data back and forth some things like akavash are really good um it gives you a lot of persistent value key value store monkey caches here there's a lot of other databases that are out there into the world that you can use because the next question becomes well what about online and offline data synchronization it gets a question a lot and there's a lot of ways of accessing this right and actually making online and offline work there's a lot of services that you would need to you know register for if you didn't want to create your own in this instance we could we could have a internal id that we use locally and a you know web backend api if we store it in entity framework into a sql database we could figure out how to upserve you know and delete and you know update all of our different database copies locally and our back end totally possible most likely what you would do in that case is have some sort of hash that was unique and then you would have like a dirty flag so if you're offline you could say you know i need to update this later do some synchronization there's plenty of services out there like realm like azure mobile apps a firebase and a bunch of other ones out there that you could use and sign up for that would automatically do online offline data cache where you need it a lot of my applications just make get requests they often are pulling data from the internet and displaying it so this sort of works for me now of course your application is different so again there's a lot of different resources out there and i'll put links in the show notes below to actually check all that out anyways i hope that you found this video interesting it was a little bit longer form but i wanted to go through basic rest and http and making these web requests and of course even caching those web requests offline with monkey cash which is a really fun library and it's all open source so you can take a look down in the show notes below hope you enjoyed this xamarin 101 episode and hope that you check out all the other xamarin 101 episodes here on the channel i definitely love hearing from you and reading all of your comments so please leave some comments below more importantly if you do love this video give it a thumbs up that goes into the google algorithm of youtube goodness and recommends it to other people and don't forget of course to subscribe and ding that notification bell so you get up to date on all the latest episodes i put out anyways thanks again for watching i hope you have a good one and cheers [Music] you
Info
Channel: James Montemagno
Views: 32,000
Rating: undefined out of 5
Keywords: xamarin forms, xamarin, ios, android, uwp, data caching, monkey cache, offline data, xamarin.forms, http, asp.net core, REST, restful
Id: a37qBMt0V9w
Channel Id: undefined
Length: 26min 19sec (1579 seconds)
Published: Thu Mar 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.