Intro to Refit REST API Client for C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
calling an api can be a pain you have to use the http client correctly you need to handle return types deserialize the data and more or at least you used to have to do all of that not anymore if you use refit refit is an automatic type safe rest library for both xamarin and net and that's dotnetframework.net core and dotnet five and beyond now in this video we're gonna be setting up an api and then call it from blazerwebassembly using refit you'll be amazed at how easy it is to talk to an api now this is the first video you watched of mine my name is tim corey it's my goal to make learning c-sharp easier i provide videos twice a week here on youtube to help you grow as a developer i also a full set of training courses on iamtimcory.com i encourage you to check out all the resources that i have to offer now in this video as with most of my videos i'm going to create some source code if you'd like a copy of my source code use the link in the description all right let's go over to visual studio and get started create a new project and let's search for an api project we're going to do an asp.net core web api project first and let's call this our let's call it our um simple api like that and this is going to be our refit demo app all right we're going to hit next we use net five no authentication yes to https noaa docker yes to enable open api support that's the swagger so let's hit create basically keep all the defaults and once we do this we're it's going to create for us a really simple api that doesn't have a lot in it in fact what it has is just one weather forecast controller with one method called get and i'll get a random set of weather forecast values so what we're going to do is create a new controller we'll leave the weather forecast controller there or creating a new controller i'm going to call this it's an api controller we will controller with read write actions that just kind of scaffolds out some things for us makes it a little easier we'll hit add and we're going to call this the guests controller all right guests controller and this will be a really simple guest book for us all right so we can get rid of this comment here we're gonna leave the route as it is which is api slash in this case guests so you see this right here in the square brackets that means this section right here i'm not gonna go deeply into apis here that's not the point of this lesson but i do want to do a little bit of setup here so right click on your api project hit add new folder we'll say models and in here we're going to create a new model i'm going to call this the guest model and in here prop tab twice id prop tab twice string first name prop tab twice string last name like so so there's our our three values here for a really simple model now in here what i want to do is i want to set up a a static list of those models so private static list of guest model control dot to add the using statement we'll say guests equals new and then curry braces and in here we'll say new guest model credit race id equals one first name equals tim last name equals corey so we're just saying some temporary values here some some test data you wouldn't normally do this you wouldn't normally have a a private static list in your controller this is just going to help us when it comes to setting up our our controller just to see what things look like as if we had a database but we don't now we'll finish changing these up i know we have red squigglies here um we shouldn't there we go we need a semicolon the end so sue storm and we're gonna say uh robert smith okay so there's our three uh demo users in our list so our list is gonna start pre-populated with three users that way right off the bat when we do a get we can actually have something to get so let's do that let's change it from string to list of guest model and we'll return guests oops not list we already have i innumerable oh that looks weird all right there we go so now we have whenever you say git you're going to get back a list of our guests we're going to fill the rest these out real quick here just with again we're set up a sample api we're not setting up a real api these are real methods but we don't want to wire up a database and create a database and do all the plumbing work necessary we're just going to create a sample so in here we're going to say get by id so instead of return value it's not a string it's going to be a guest model so we're going to say guess dot where oops dot where we'll say g arrow g dot id equals id first or default and what that'll do is it'll grab the first record where the id matches and it doesn't find one it's going to turn the default value which is null next up we're going to have the post which again is going to post a guest model and this is pretty easy we'll say guess dot add value just add that to our list and then our put is going to be again a guest model and for this one the put what it's going to do is actually we're going to modify a record so we're going to say okay with this id we're going to modify an existing record with new values well instead of updating one by one we're going to do a simple thing which is guess dot remove guess dot where g arrow g dot id equals id first or default like so so we're going to move the the first ordinal but the first record where we have an id that matches this id being passed in and then we're gonna do a guess.add value and yes there's other ways of doing this they're probably better and we're repeating code that's okay this again is just for demo purposes and then finally we can actually take this right here copy it paste it down there there is our delete record which is just going to delete it and it's not going to add a new value being passed in it just deletes it entirely so that is a quick and dirty api let's launch this run it try it out and make sure you understand what it's doing all right so here's our swagger page get we can actually zoom in a little bit here you can say try it out execute and that's going to give us back a list let's zoom in here there's our list of three records now we can come down here to post let's just do one post so we'll try it out and eras say the id is four against all manual um mary jones execute okay and it says 200 which means success okay so now we can come back up here and say execute again on this we should see that now mary jones is in the list all right so that's the how to use this api but now you need to call this from another another project okay so we're gonna grab this url right here because we need to know what that number is that port number 44367 so now we have that let's right click on our solution and say add new project and this time we're going to choose a blazer web assembly project we're going to call this our we call it a simple api so this is our simple ui hit next dotnet 5 no authentication yes to https node hosted and note a progressive web application we just want a a simple working blazer web application and what i'm going to do is in my program.cs let's collapse this one down in my program.cs i'm going to at the top here i'm going to comment it out but paste in that url that's going to be the url to our api now we'll definitely come back to that but for right now let's right click on our simple ui i'm going to add a new folder called data access and then before we go on let's add our dependencies right click and say manage nuget packages type in refit and we're gonna add two packages here because we're using blazer web assembly and we want the http client factory with us so install refit the normal refit and then also install refit http client factory you could just install the client factory because that depends on refit but this way it's clear that you have both installed all right so now we have those two things installed let's go over to our data access right click where i say add new item interface and we're gonna say this name is i guessed data and make it public now here's where the magic comes in where i hate to use the word magic because it's not magic it's doing stuff behind the scenes but this is what you will need to worry about when it comes to talking to an api so we have our guest controller where we have those methods that are the the get the get with id the post put and delete well we're going to call all of those using an interface so let's start off the get get which actually we need to add a using statement up here using refit all right so get and we have to pass in a path here so what's the path well our path is slash guests so we're gonna have a base path which is our api's um you know the the url which we grabbed that here slash api and then for example in this case guests is our controller that will be the the part we add here so it's just a partial um api path so this is our guests call so we're going to say task list of guest model we don't have that yet here we're going to add in just a minute we'll say get guests so let's add the guest model so we're going to right click on the project say new folder models right click add class and this is the guest model yes i'm repeating this i could do a shared project i want to keep these projects entirely separate though so i even debated naming us this something else like a client guest model or something like that just to show you that these two projects don't talk to each other okay so the the api does not have any kind of reference to the blazer web assembly project and the blazer webassembly product does not have a reference to the api they're separate the only way they're going to talk is over this url that's it okay i'll make sure that's clear that's why i didn't share any um you know a class library project with the models so let's go back to our igas data we're going to do a control dot here to add the using statements for our models and this right here is all it takes once we wire it up that's all it's going to take to call our api i know that sounds kind of mind-blowing and it really is let's wire the rest up and then get to the good part of seeing it working so next up we have another get and this time we're going to pass in an id so this is our guest where we say passing the id we get one guest back the first default so with this one we're going to say task these are all asynchronous so task of guest model and then we're going to say get guest notice a singular int id all right so we have get guests plural get guest and pass in the id and that will be our single lookup next up we have post and this is going to be repetitive because it's going to start kind of following the same pattern over and over again guess notice the reason we have guests here and guests here is because the different methods types so this is a getter this is a post so here we're going to have task let's call it create guest and we're going to pass in in the body we're going to pass in guest model guest so it's a post which means we're going to send data to the server to the api in the body since it's a post method and we're going to send is a guest model we'll call it guest so that's for creating guests then we have a put and a put we're going to say slash guess slash id this is a little trickier one because the put what it does is it passes an id and it passes from the body it passes the guest model for value so it passes two different things one thing on the url one thing in the body so we're gonna do it this way like so and we'll say task update guest int id and then from the body or in the body we're going to pass guest model we'll say guest finally we're going to say this is a delete method again we're going to say slash guests slash id and curry braces because that's the value we're passing in where i say task delete guest int id so these interface methods right here what they're going to do is scaffold out our entire call to our rest api it's going to do all the the various bits let's go over to program.cs we're going to add a using statement up here using refit and then down here right now we have let's unpin this it goes off a screen even is we have this [Music] this uh http client factory being set up we're going to comment that out for now we don't need it but i want to keep it in there just long enough so you can see it and instead we're going to say is builder dot services dot add refit client for this is the i guessed data control dot to add our using statement so i guess that's the interface that we just created so cr and a refit client that uses that interface and we're going to say dot configure http client and we'll say c arrow function and then let's go a new line here and put our curly braces don't forget semicolon at the end we'll come back to up here where i say c dot base address equals new uri and that's going to be our uri which is this right here that's the path to our api so this configuration right here replaces this configuration right here notice that we have an add scope the new http client with a base address of the the builder.hosts environment.base address so instead of doing that we get rid of that and we do this where we say hey i got a refit client for i guest data and for the http client in there we're going to use this base address so what will happen when we compile and run our application is it's going to look for this interface and add that as a refit client what refit will do is it's going to take our http client setup and it's going to create http client factory and properly configure all the calls necessary to a rest api that we have configured here it's going to figure out all those calls where they go how they work making sure the calls are wrapped properly and so on we don't have to worry about any of that now that we've passed in our i guess data notice we're not we're not implementing i guess data that's what the refit client does we can go over to our solution explorer let's go right to the main page we're not gonna modify or create new pages let's just set this one up so on the main page we're going to call our api and load some data so let's set up a code section first and in here let's grab a list of let's see a private list private list of guest model and we'll call it data equals let's um let's start off with nothing in it and i do need to or i do want to go over here to my imports.razer add a using for the simpleui dot data access and using simple ui dot models that we can call those more easily like this and then in here that should rebuild at some point there you go we're going to have a protected override on the on initialized async we can shift tab to bring it back into line we can take this line out and we also need to mark this as async we're going to say data equals a weight and we call the i guess data so let's inject that inject i guessed data let's call this guess data so i can say guest data why is it not showing up i'm not sure it should be showing up there guest data dot there we go it shows with intellisense but it had a regular red quickly interesting um get guests that's it that's going to be our guest list so that's going to be all it takes to call our api and ask for a list of guests that's it that's all the code we need to write so the whole code for refit is setting up our refit client with an interface creating that interface and then calling that interface that's it just to show us before we create a full page let's do this um and if we're gonna say data is not null then for each and we'll say for each item in data and let's just do a simple um actually that's well let's just hm i wanna make sure i'm semantically correct i don't want to do like h3s so let's just do an unordered list and then inside there for my 4h what i will do is say um a list item that is item dot and then let's do um let's just do first name that was interesting put the dot in the wrong spot im.firstname space item dot last name like so just to show off that we have something working okay that's gonna give us a quick and dirty little whoops that's not gonna show us what we wanted to show because we're only loading the api right click on the solution set startup projects multiple startup projects start the api first so it's not at the top drag it to the top using the arrows start both of them okay now it's going to start the api and then it's going to also start our blazer webassembly project so api starts first and then our blazer webassembly project launches as well and we have an unhandled error has occurred let's find what that error is i don't wanna help welcome message who cares okay it says ah coors policy so if you can't see us here let's zoom in if you see us um the call from origin this origin has been blocked by coors policy no access control allow origin header is present on the requested resource so this is saying is you can't make a call across apis so you have a different url url you're coming from i don't know if you're authorized to talk to me so i'm going to assume you're not so what we need to do is enable course to work so let's go over to our startup.cs of our api come down here under services.add controllers where i say services dot add course and we'll create a policy arrow function and then in here don't forget to add your closing semicolon we're going to say policy dot add policy we'll call it uh open course policy this is the same policy we have in the timco retail manager where i say opt for options arrow there we go boil off my key from it and then in here we'll say opt.allow any origin the next line dot allow any header and then the next slide will say allow any method and then we make sure we close out the semicolon there as well i actually don't need these clear braces right here like so and this is still messing up um this i don't need this either there we go sorry a little a little confusing there with all the nested um different things and arrows and all the rest but this is our course policy that basically says allow any origin allow any header allow any method so if you don't have this then it means it won't talk to other apis in other locations if you don't have this and if you pass headers along with your api it might block them and if you don't have this then it will only allow i believe git and post but not put patch delete or all the rest but we're not quite done we've added this to the services but down here after let's do it after the use https redirection we're going to say app.use course and pass in our open course policy so this is where we actually use it so we create it up here down here we use it so that should allow us to make that call so hopefully that's that authorizes everything and we can make a call to our api and get a list of guests and there we go we have our list of tim corey sue storm and robert smith excellent so now we know that that's all it takes to call an api so and this is just kind of a little mind-blowing it's a really great tool for making quick and easy calls to an api without sacrificing pretty much anything this just takes away all the fluff all the the setup and all the uh ceremony around talking with api and just narrows it down to a really simple just call it that's it so now just to prove this all works i'm going to set up the rest of our methods in a really simple little uh form here so that you can see how the different methods work and make sure you understand how to call them properly so let's do this let's um get rid of of this here let's let's keep the um is not null we'll make sure that if it is null we don't show this but then we're going to have a um a div class equals row and then inside here we're going to have a div class equals call md six and then in here we have an h2 that is item which we don't have our for each loop oops let's cut this out for a minute for each var item in data there we go so now we're going to say item dot let's grab id first space item dot first name space item dot last name that'll show us all the data for a record but now i want another half the page class equals call md six if you're not familiar with the the uh classes i'm doing here this is bootstrap specifically bootstrap four and what it's doing is it's saying okay we're gonna in this row we're going to divide the page in half so there's 12 columns total so six of them will be for this size this spot and six of them are over here it's going to divide it equally and then it will resize nicely for phones and other devices so let's say button class equals btn btn-primary is fine and we'll say on click and for right now i'm going to leave that empty and we'll say add guest and yes i know you're yelling me in fact i'll get rid of it for now i don't want to yell at me i don't like to leave on me there you go so we have two more and this is going to be update guest and this will be delete guest so let's change this to um danger and warning um so we can make sure that we can differentiate the buttons and just see what each adds to it okay now let's go down here and we're going to say private async task add guest guest model guest and in here we're going to say await guest data dot create guest and then let's do a new line here and we'll say new guest model we'll say id equals data dot uh count plus one so we're gonna create a new guest model based upon the guest you pass in so yes this is again quick and dirty we're not creating a form and do the fill out stuff we're just going to take whatever row you were on we're going to pass in that guest we're going to duplicate that guest but create with a new id so the first name will be the guest dot first name and the last name will be guest dot last name basically making a copy of a guess just changing their id to a new id that'll be it okay so there is our our create guest the only thing i'll do at the end i'll grab this call right here and i will paste it down here so that once we create a guest we then refresh our list of guests so we can see that new guest show up in the list that's our add guest method so let's come up here and say on click equals and this will get a little longer so let's unpin this and we'll say at open close parents and here's why i want to pass in a value so i can't just give the method name so i'm going to say um e is fine um e arrow will say add guest item so what this does is it calls the on when on click method is clicked it's going to call this method right here add guest but it's going to pass in the item which is a specific item in our for each so we know which user was clicked so we could just let me show you that down here i could say on click equals add guest like that that would work except the fact that i can't pass in that guest model if i tried with the item like this that won't work because it's not it's not um expecting an actual method name it's expecting an event callback which is a little different so this way the event callback is the wrapping parens which creates a [Music] an action not a function in action and the action is to call this method with the um the parameter so just a little bit of trivia there for working with blazer okay let's create a couple more methods so private async task update guest guest model guest and then in here i say guest dot last name equals let's go with uh jones so we're going to rename you're going to pass in the guest whatever record you were on up here we're going to pass that in we'll change the last name of the record you passed in to jones and then we're going to say await guest data dot update guest guest id guest so we're gonna pass in that same record but now it's gonna have jones the last name and then just like before we're gonna grab that new set of data from the api again and one last one while we're here let's actually just copy and paste really this here where i say delete delete guest get rid of the updating the last name and instead of update guess we're going to delete guests we don't need to pass in the whole guest just the id for the guest we do i want to call that list again to get the new list which should be minus one guest back up here let's copy this on click method paste it a couple more times in these two this is going to be uh update guest and this is going to be delete guest but the rest is the same we're still passing the item in it's still the on click method with this e doesn't really matter okay so now we have a pretty simple but hopefully functional page to work with let's launch this and see our list of guests wait for it wait for it there we go so let's shrink it down oops that's a little too small uh there you go so now there's our list of tim corey sue storm and robert smith only has one that's interesting it looks like um i made a mistake and i didn't update robert smith's id that could be problematic so let's go ahead and delete robert smith and actually deleted tim corey because tim corey is the first one with the id of one that was found makes sense let's add a guest there's robert smith now with three and now it's updated guest now it's robert jones let's go ahead and delete robert smith don't want him and let's add a guest on sue storm's record which is now sue storm again but now the id of three that's what we've messed up the ids now but we add again there's two storm of four let's update sue storm and sue jones let's delete the third sue storm so you can kind of play around with all these things and we have a fully functional page talking to multiple different uh endpoints in our api multiple different types of calls and it's all really simple to do now before i forget let's go back over to that guest controller go back up here and modify robert to be three okay just so we we're a little cleaner there and don't have that problem again but that's all there is to refit i mean there's a lot more to it you can go in more depth but that's all that you have to do to get it working you need to have this call right here to set up our our client well kind of you do you don't have to let's do one more quick demo so you can see what's going on see how you can kind of remove dependency injection if you don't have dependency injection or how you can call a second interface if you want to add a second one to dependency injection so if you want to add a second one just basically copy and paste and change the interface if you have two of these add refit clients in your dependency injection but let's look at our api and we have this weather forecast controller we have this weather forecast model here so let's grab this the model contents come down to our models down here we're going to say new class we'll call it weather model and in here we'll paste our our model properties okay so recall this weather forecast uh api up here which just has that one get method that's it so to do that we do is create our interface so in our data access we right click add a new item interface and we're going to say this is the i weather data make it public we're going to say this is oops don't forget to add a using refit and we'll say this is a get call and in here this is just weather forecast that's the the call to the correct uh controller it's weather forecast controller so we'll say task of type list of weather model control dot to add the using statement for that model and say get weather okay so now we have a call to a second a second weather forecast or a second api our weather forecast controller now instead of adding it here in our program.cs i'm going to pretend we don't have dependency injection now we do but let's say it's a console app or a winform app where you haven't added it now you can definitely add the net core dependency injection fairly simply into all these different projects i have covered that before in some of my courses but let's say you don't want to do that you don't want to go to that depth not a problem let's come back to our index page actually let's go to our our fetch data page which i believe our fetch data page right now is going to grab let's look at it does call an api right now and it grabs the weather forecast uh model that's interesting which is right here which is the same model we just brought over so we can get rid of that model we can get rid of this call right here and we can just change or update the using statement here it's actually a model there we go so you have forecasts so now this page should mostly work let's get rid of the inject statement here let's come down here it's actually a list of weather model but we need to make a call to the api so how do we call the api when we haven't added the interface into our dependency injection well up here we need to add a using statement for refit and then down here in our code we can do is we can say let's set up a our api so var weather data equals rest service this comes from refit dot four and our interface is going to be i weather data and we pass in our api now our api the url is this url without the slash api it's a little bit different that's because um weather forecast does not use the the api just so you know it just says controller whereas guest controller says api controller that's that's the difference so there's our url for that api and that's the entire setup we can do instead of putting it in depends the injection now dependency injection is the preferred way if you're using dependency injection if you're not you can do this way and now we can do is we can say uh forecasts equals await weather data dot get weather done that's it now if we load this up we can go to the weather page and get data from our api let's wait for it it's a little slow at first because it's starting both up it's waiting for one to be done before start the next so this page works now fetch data and there is the the data from our api if we refresh this it's going to be different now they're all sweltering uh we refresh it again and now it's new data it's all coming from our api and we didn't have to go through depends injection so we can do it either way we can do it through dependency injection or we can basically instantiate our our service right in our class and then make the call now if you're gonna do this if you're gonna make one call i would say this outside the method and then reuse it but in our case it didn't really matter if we were used it or not because we're only using it once so that's how to call refit there's a lot more you could do there it can work with authentication it can work with different json clients it can do a whole lot of really cool stuff if you go to i'll link this down below reactive.ui.github.io refit so again there's that url right there reactiveui.github.io refit i guess down the description is below as well this page will walk you through setting up refit there is the interface set up there is the call for it and there is the how to use than that interface here's how to set the services up so walk you through that but then it goes through a whole bunch of other things like json content xml content forum posts redefining headers bearer tokens or bare authentication and so on so lots of cool stuff there's even support for poly uh we're gonna cover that in a future video poly is a really awesome tool you should definitely check out so uh really cool stuff here it talks about how it works where it works you can view the project on github and you can learn more about there as well and um ask any questions you have if you get stuck somewhere but lots of cool stuff in here lots of examples that walk you through the various things you might come across aliases so maybe you have group id being passed in but you want to alias as the id in this call not a problem so really cool stuff check it out i definitely encourage you to put this in your toolbox of tools to use to make your life easier and at the same time safer and more consistent you will probably see me use this now i've covered on video you'll probably see me use this in future videos just because of how easy it is and how powerful it is it's kind of like dapper in connecting to sql where it's just really easy to do really really well so with that if you have any questions leave them down in the comments below if you have any thoughts on refit leave them down the comments below as well thanks for watching as always i am tim cory [Music] [Applause] you
Info
Channel: IAmTimCorey
Views: 36,132
Rating: undefined out of 5
Keywords: c# refit, tim corey, iamtimcorey, tim corey c#, c# api, c# .net core api, visual studio 2019, c# rest api
Id: HH8drNbai8w
Channel Id: undefined
Length: 49min 17sec (2957 seconds)
Published: Mon Aug 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.