WebAPI Improvements in .NET 5 - OpenAPI, Better F5, and NSwag

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in.net 5 web api has an important quality of life upgrade in this video we'll be looking at the integration of open api into the project how it works and then why that's so important we'll also be looking briefly at nswag and how to use it to generate api clients for other applications using that open api standard now if this is the first video you watched of mine my name is tim corey and 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 have a full set of training courses on iamtimcore.com i encourage you to check out all the resources i have to offer in this video as with most videos i may create some source code if you'd like a copy of my source code just use the link in the description you might even get a special bonus just for downloading that source code so let's start looking at what's different in api in dotnet five so let's go to create a new project and we'll look for a not desktop project let's go to all project types and we'll look for a asp.net core web application hit next let's call this our demo api and let's call this our demo app we'll hit create and we're gonna select an asp.net core web api that's dotnet core and net core 5.0 so that's our new product type now if you notice on the right no authentication yes https and there's this new check box right down here it's a little really small but it says enable open api support and by default that check box is checked we're going to leave that checked that's important so hit create if you don't see that check box probably you're not on a net 5 project you probably selected.net core 3.1 now if you have worked with an api project before especially a.net core api project this will look very very similar in fact if you have taken my course that intros the five different types of asp.net core project types that's the getting started asp.net core in that course we deal with a net core 3.1 web api we build that out this will look extremely similar to that the big difference comes in startup.cs where we'll see right down here these lines are extra these lines are extra and that's it that's really the big change when it comes to the code of our api project so what what are these lines do well this is called swagger gen now if you have seen what we did in the temco retail manager series if you're not from that series what we're doing is we're building kind of a real world application to simulate what you'd come into on day one of a job so you can pick up the middle of series and it simulates you walking in the front door and say okay i'm you know i just got hired let's start working the project and in that project we've got an api that we we hooked up swagger to and swagger is it's it's an open api it's what it's called now but really it's swagger and so what swagger is is a way to kind of document your api but it's more than just a nice visual we're going to see that in a minute but let's talk about what's happening here so let's unpin this we can see the whole length we have swagger gen and it says swagger dock version one and then the title is gonna be our demo api and the version is v1 so this is saying is our our api is version one and the title of the the document for swagger is gonna be our demo api this right here and then these lines right down here that replaces all the configuration we used to have to do we had a whole configuration page we used to have for swagger it was really confusing had a lot of stuff in it if you didn't get it quite right it didn't work is kind of messy well now those three lines configure our open api also known as swagger for us so this is the configuration the generator configuration this is the user interface configuration so for example the swagger.json file it creates there's the path that it will be on and then the name of that will be our demo api version one and it keeps saying version one because with an api you really don't want to change your um your signature so you so if you have a get call that has no parameters and it gets back weather data you don't want to then all of a sudden change that to require data being passed into it first because that will break all the clients that were depending on your api and so what you do is you create a version two of your api and say well that old call still works it's a version one call of deprecated now we have version two calls and you can version your api like that so you don't break old clients we can bring new clients on with new functionality so swagger supports that it supports the idea of having multiple versions of your api in the same api so right now we're not going to get into how to version apis that's a little bit further down the rabbit trail that i want to go but at the very least i want you to see the swagger generator aspire ui that's all the configuration we have set up and then just use swagger notice that it's in the is environment for development is development this is important because if you're not comfortable having your swagger code visible for anybody i see then you only want it in development well it's already set up for that dotnet core when it was reimagined from.net framework.net core one of the things that was a big um mantra was security first secure first make sure that we lock this thing down and then you can unlock it how you want but by default if you lock down this is one of those things where it's locked down to only do this in development mode meaning only in our dev servers only when we're debugging but not in production if you want to use it in production not a problem you just move these two lines outside this if statement and that will work in production but you have to make that conscious choice i really appreciate this the standpoint of we're gonna be secure and then you can make it work at whatever level you want to now that's not saying that it's unsecure to allow this in production it may be exactly what you want in fact we're gonna see a use case with um with our end swag where we can generate clients and have them work off of this swagger.json file to identify how to build a client well that may be something you want to permit external people to do in that case you might want this to be a production ready thing as well and that's fine but right out of the box we're going to run this application now we're going to see what swagger brings to the table but we're also going to see something new and that is when i run this application it's going to launch right to swagger so when it launches notice it goes right to swagger it used to be that when you launched an api it went here or maybe it would go here but typically you go right to the root and there's nothing there we used to put something there just to have something to display but now it goes right to swagger so that we have a landing page we can work from so that's another update that came about with nat 5 and the newer versions of visual studio is when you launch the application it launches to swagger of course only if you have swagger installed but it launches a swagger that way it's you have to dig for find it it goes right to it now if you're not familiar with swagger i'll give you a brief overview and again swagger and open api are interchangeable at this point so just note that one kind of equals the other will use them interchangeably there is some nuance there but we're not going to get into that so as you can see with swagger what it's doing is documenting for us what our api looks like now right now our api only has one controller whether forecast and one action inside of that and that's the get action that's the only one we have now inside there i notice you can click on that expands and it says okay it doesn't take any parameters the response codes typically are just 200 success it doesn't document any other types of response codes and here is the schema down here for what that return would look like now down below we have schemas for weather forecast and again it shows us let's see if we can zoom in here it shows us what the schema for that returned object would be a date a temperature in c a temperature an f and a summary and again string two integers and a date time string so that's one weather forecast object the um the weather forecast get command notice the square brackets here returns an array of these objects so that's that's the whole documentation for the get but then we have this cool button over here it says try it out now we don't have any authentication in here yes that does add some wrinkles to it we're not gonna get deep into that we probably will at some point not in this video but in a future video because authentication has changed as well there's a lot of really cool new things around authentication in net it's going to take some time to dig into that and really teach it well so i'm not going to teach you in this video but just know there's no authentication here in this api but if we hit try it out it says okay there's no parameters so just execute when i execute it says okay you got a response code of 200. if you're not familiar with http response codes a 200 means okay or everything's good and then here is the response body which is that array with all of our weather forecast information so for this i'm i'm off there we go for this date it's going to be 32 degrees fahrenheit which is bracing this date will be 82 degrees fahrenheit which they call chili it's not chilly that's rather warm 111 is balmy um we need to put our our descriptions back in here because this is totally crazy but that gives us our response right inside of swagger inside this fire ui so we can play around with it or we can even download or copy it to clipboard now what has copied to clipboard do for us remember the in visual studio let's copy a clipboard and then in visual studio and let's see if i can do this while it's running we can come down here and there is a paste special paste json as classes i can do that and notice it created a root object called property one for array of classes and then class one is date temperature and c temperature and f and summary that looks a lot like our weather object or whether a forecast object and it said this is the json structure expressed in c sharp code so that copy allows us to create these objects very quickly in our c sharp code now of course it didn't pick intelligent names but that's kind of up to us so we can get rid of that that was just kind of a demo because there's better ways of doing this in fact this application already has those things built in but this is what swagger does for us swagger gives us all of this great user interface in this great ui to get all this you know these calls to try it out to execute to clear the contents and execute again and now we have different values really cool stuff here but it goes even further than that and this is where i think that open api swagger is such a big deal for putting into an api and it's something that may get missed in the mix and that is right underneath the title here we have this link swagger v1 swagger.json let's click on that and there is our json let's kind of zoom in here a little bit this is our json representation of the swagger information this is what the ui is showing us in a pretty format so why is it important to seal us because it really it's it's kind of messy right but what this does is it allows us to create clients let's do this let's um let's zoom out here and we're going to wait on this product i'm going to wait to say no i'm going to say this right now let's just save as and we're going to do is go back to our visual studio project we'll pin that again and we're going to um open i think copy full path might have done it for me but let's make sure by doing that and then i'm going to paste it right here so you have a swagger.json i'm going to put it right into the same project i'm working with that's just a placeholder for now but now we have this let's close this out and now in our solution explorer now we have aspire.json file in our project we don't actually want it in this project right now we want a different project but i want to save it for now and then create a new project so let's do that let's right click on our solution where i say add new project or at a blazer app and let's call this um blazer wasm demo wasm stands for web assembly and we'll choose blazer web assembly we are going to cover the new stuff in blazer in upcoming videos that's coming soon um we're not going to cover in this video but just know that the blazer video is coming with all the new stuff that's in blazer some really cool stuff going on there as well but let's just use blazer web assembly because remember that blazerweb assembly needs an api in order to get data so let's hit create and now we have a blazer web assembly application what i'm going to do is i'm going to drag this swagger.json over to the blazer.web assembly project and delete it from our core api okay so now in blazer web assembly if we right click and say say startup project and just run this just to see we're going to find is that it already has a simulation of the um with that forecast so fetch data we get a weather forecast 133 freezing and so on and come back here notice it doesn't change it still says 133 and freezing and the dates are from 2018 and that's because it's just pulling from a json file in the application there's not actually anything i believe it's in www root sample data weather.json so there's that whether it's pulling from that's not the best we want to actually call from an api so what we're going to do is we're going to call our our demo api instead but we're going to use nswag which is a tool that works upon swagger to auto generate for us a client this is gonna probably blow your mind a little bit we're gonna step through it we're not gonna go deep into end swag today but i do wanna show you why it's important to have open api in our api projects because of what it allows for on the client side all right so step one right click on connected services this may be something you've missed in the past maybe you haven't used it's not something you necessarily use often but there's some really cool stuff in here so add connected services this is where you add service dependencies including open api or grpc so you want to talk to grpc from blaze webassembly not a problem you would do it right here let's hit add under this middle section where it also says open api we're going to choose open api remember that open api and swagger is open api therefore we already have an open api and we're going to choose a file a url or somewhere else actually no that's sorry that's the only two places we have options though so we're going to choose a file now you can choose the url and point to an existing api if you want to but our case we have the url download or the file downloaded let's hit browse and notice we're in the blazer wasm demo folder there's our swagger.json that's from does the auto-generated swagger.json we just downloaded from our api double click it name space for the generated code we're going to leave it blank which will use the blazer web assembly or blazer razor demo name space and we'll hit finish now this is going to bring in nswag the client and api description client and he's going to use newtonsoft.json and that's about it so now we have our client in place let's hit save but it seems like nothing has changed i want you to see there's a button up here let's zoom in here there's a button at the very top that says show all files and if you look in the obj folder this gets recreated so if you ever have a problem where you think maybe it's using old code or an old build you can delete the obj and bin folder and it will recreate it the next time you build your application but in here we have swagger client double click that let's zoom out this is an auto-generated client that was built using n-swag and it's built off of our swagger.json file this is all set up to talk to our entire api let me show you how to use this notice it says swagger client is the part the class name so we can go over to our pages let's go to fetch data this is where we normally load our sample data slash weather.json file we're not going to do that instead we're going to get information from our api now our api let's go our api real quick and grab under dependence not dependencies properties the launch settings.json the ssl port for iis is gonna be 44316 and copy that and then in here in this forecast i'm going to change this actually let's go one level higher first and say swagger client notice it found it let's call it client equals new this is the new syntax here i don't have to put newswire client i can say new and then let's say get rid of string here https colon slash localhost colon that um port number i just specified or found and then we'll pass in http like so now what just did i just do well i create a new swagger client instance that swagger client is the auto-generated client for our api and i said it's passing two pieces of information first of all the base url for your api this is where you're talking to remember that this is just the client side you still have to have your api running and so where is it running well in this case it's on localhost colon 44316 we also have to pass in our http client but i pass an http where is that the very top here we have inject http client and we named it http this is the standard thing to do in blazer web assembly is it's actually using the http client factory to create instances and dispose of them properly and make sure we don't have um we don't have a problem with our connections to http we don't have any problems with um keeping things open too long or too short and those kind of things so that's kind of the the quick way is just to pass those two pieces of information and now we have this thing called client so down here we can get rid of this call for forecast and say client dot get async and say i can't find that there we go weather forecast async so it's gonna get the weather forecast asynchronously now the weather forecast async returns an eye collection of blazer wasm demo dot weather forecast not the same things we have up here so first of all it's an eye collection of blazer webassembly demo dot weather forecast forecasts we can't do a too short date string up here it comes through as a date time offset which that's a translation issue and it's something that you can tweak with nswag i just haven't done it i want to keep it as simple as possible but this is just a kind of demo what you can do with nswag so i'm saying that's the base url that's my http client instantiate this client object and then just say client.weatherforecast async that's the our git command that returns a set of weather forecasts which we then display up here now it i didn't have a changing code up here besides that get short date because of the fact that the the structure is pretty much the same thing because we they use the same demo code all over but now instead of pulling from in our blazer web assembly instead of pulling from this sample data dataweather.json we're going to pull from our api instead there is one tweak to make in program.cs the http client by default they add on this um it's the the base address of the same blaze webassembly project so it's saying hey here's a shortcut um use the base address from where we're running as the the starter place for the address well we're calling a different api so we don't want to do that so let's just not put a base address in we can pass in the address every single time so with that change let's do this right click on your solution set startup projects multiple projects we're going to choose our demo api to start move that up one and then our blazer web assembly is start without debugging so we have two projects opening the api opens first and then the blazer webassembly hit okay run this i have noticed some quirkiness with loading two products at the same time so note that can cause a little bit of issue sometimes but it should launch so there's our weather forecast and if we open this up and try it out and execute um it does execute it opens a separate window it's a little weird but um here's my blazer web assembly fetch data and it says un hanoi error has occurred aha if you hit well first of all notice that you can hit reload it'll try again still on helix and error hit f12 enter console you'll see what the error is now the error here is access to fetch at this from this origin has been blocked by coors policy no access control allow origin header is present on the requested resources this is a course issue a cross-origin resource sharing i forget so many acronyms in software development but basically what this says is you are on one url the api is and your blazerweb assembly project is on a different url and i don't have a rule in place in the api that says that's okay and so since you're not on the same url i'm gonna say no you can't talk we're gonna open that up so we're gonna allow more of that just note up here it says blade web assembly loaded with 8.89 megabytes of resources first of all that may freak you right out because it seems like a ton of resources this is in development mode not production mode it's a big difference here published applications will be significantly smaller they kind of point that out there so a lot of stuff going here honestly yes that's a big number but it's not nearly as big as what most production applications are but that's just beside the point we'll talk about that later in the blazer uh video which comes out uh in a couple more videos after this one so anywho that f12 showed us the error and so you got a coors error okay i close that down what we're going to do is we'll hit stop and we're going to go back to our api go back to startup and we'll make some modifications here and at this point it's kind of bonus coverage we're doing here to show off how to enable cores for certain websites um but i want to do this but i want to show you that yes this would work and then we'll actually even show a desktop client or a console application that's also using this this uh generated client just to show you off the different ways we can do this so let's start off with inside configure services we're gonna say services dot add cores and i'll say options no not options builder options that's the name i want to use arrow curly braces options dot add policy and the name of the policy will be i don't know um wasm policy sure doesn't matter comma let's get our cursor out of here builder arrow a lot of stuff going on here and then in here builder dot with origins this is where we specify which urls can have access to our our application well let's go and look at what blazer web assembly under properties launch settings four four three one four so we're gonna say https localhost colon 44314 that gets access but you know what if you were to launch let's go to the next line here if you were to launch with kestrel instead you'd have https localhost colon 5001 that's a standard port and let's call that good and then we're going to do is say dots with methods and we'll just say just get for now so what does that do for us let's put our semicolons all the way down what does this do for us so we're saying is i'm going to create a new policy for course you can create more policies if you want or create just one policy and that policy is that we're going to allow calls that have an origin of this url or this url but they can only make get calls so if it's a get call from those two locations cool no problem if you want to have more than that you can say post delete and so on it's up to you if you want to add actions in but that allows you to kind of dial things in cores is not security but and really in a lot of ways it's a pain in the butt but um it is what it is so that's how you would configure the policy but now we need to apply the policy let's scroll down under the configure method after routing app.use routing before authorization say app.use course and i forget our policy name is but that policy name is wasm policy so so use course and use that policy so that's all there is for course we hit run and now it should be that our site has access to that api now the api has started let's go to fetch data and now we have data notice it says warm with a temperature of of nine here we go back to this now the temperature is 46 and it's cool so it's fetching from our api every time we come to this page now so just using that generated client we were able to very very quickly talk to our api there wasn't a lot of setup there wasn't a lot of overhead now i have a love hate relationship with generated code and i am perfectly fine with you saying i never want to use nswag ever that's cool because when you generate code it's kind of like entity framework entity framework generates a database for you and you say man that's great i have to do the work that's true but when it breaks it's on you to fix it well in the same way if this generated code breaks it's on you to fix it so you've got to figure out you turn on the um view files here and go to a sweater client you gotta figure out what's going on in this file why it's not working what's going on what's happening and so on notice this file is 266 lines long for one endpoint now it won't scale at that so two end points won't make it 500 lines long but that's still a lot of lines of code you have to be able to at least know how to debug it in order to figure out what's going on you in theory could come in here and make changes but remember this is generated because it's generated it can get regenerated and overwrite your your code so you could take this code and just put it right into your code and not have it generated anymore and just make your modifications for example there can be some conversion types right like right here we have the newton-saw json property notice it's capital d in c-sharp but lowercase d for the json property really cool stuff right there and there's a lot so you can learn in here as well you can learn about how these different things work but in general if you're comfortable maintaining this file then this is a great option because it saves some work but if you're not comfortable with understanding what's going on then maybe you don't want to do that maybe you want to do the work yourself i'm not advocating that you necessarily have to use n swag i'm not even saying you should use n swag i'm saying it's an option for you to at least consider and that's one of the reasons why i think the open api is such a big deal inside of api because that allows those generators to work and those generators aren't just for c sharp you can create you can have generators for javascript for c plus plus for objective c there's a lot of different generators out there that will create clients to talk to your api based upon that open api standard really cool stuff now just kind of drive this point home let's right click on the solution and add one more project we'll do a lot quicker in this project consoleapp.net core and we'll call this our console demo and in here we're gonna do i'm not going to take out the namespace class and and method name make it a top level call i could and um i guess it's kind of a possibility that be useful but just know that that's definitely possible with a real quick side note here i've gotten some pushback on why top level calls are important people really want to see console demo program and main in their code i get that except for the fact this is a special method this special method can't really be called anywhere else so why does it have a namespace why does it have a class name why does it have a name itself it can't be called anywhere else so even though this looks like a normal method it's not a normal method so why are we treating it like a normal method so just my thoughts there getting rid of all this code and starting from the very top seems logical to me but you don't have to use it okay inside of our code in our console demo let's grab our let's um in blazer webassembly there we go let's not show those anymore and let's grab our swagger.json and drag it in the console demo which makes a copy of it so this is the the same copy we've used from our api well now we can do is under our console demo we can say add connected service add open api file that json file hit finish it adds the stuff it needs we hit close we hit save and now in here we can say slider client dot oops client equals new we need the url for our our api that would be i'm sorry https localhost and i believe it was four four three one six let's see my memory was and then for http client i'm gonna cheat here i'm gonna cheat real bad um just for a second time i'm gonna say new client in fact let's let's be more clear there i could just use new but i'm going to use new http http client because of the fact that it's not being i don't see what the new is i don't see that it's http client now i do see in my cheat here but um that's okay oh and it's saying here that new is not available for c sharp eight that's because i haven't changed right click on our console demo properties change to net core five there we go so i have now called that api and i can say i've got the connection to the api now i can say let's just say var records equals client dot and the call was with our forecast async i can save for each var r in records console right line string interpolation which is our dollar sign that allows us to put our curly brace in here and say r dot i believe it is date space or colon space r dot summary records here is saying oops i say you can't do that because it's a task not a list that's what i'm not getting intellisense down here whenever you don't get intellisense it's probably your problem not the codes problem i have to say a weight here but that raises a problem because main is not asynchronous well i can say async task ctrl dot to add the using statement for system.threading.http.tasks and now we're good to go let's run our application we have to add this to our multi-start set startup projects let's start our console app without debugging but we'll move that to the bottom of the list that way it starts after the api starts all right the api where it popped up the other screen there we go there's our our dates and balmy mild hot freezing scorching so our weather's gonna fluctuate pretty rapidly so there is in what two lines of code all right so we have yeah two lines of code i was able to set up the client and talk to it now if you want top level call there we go now notice you have to say um cons actually probably use the same up here using console demo and the reason why is you don't have a using a namespace since it's not a namespace at all you have to have the namespace of your root project if you're gonna call something else on the root so but now we've cut that down to 13 lines of code to talk to an api and get all the data out of it and display it now i did say this is a shortcut up here i want to spend a couple more seconds here just let you know this is not the way i create http clients this is a quick and dirty way but it's definitely not something you want to have in production because this could bankrupt your system of available connections to the internet you don't want to do that you want to use the http client factory which would mean setting up the well ideally dependency injection and then using the dependency injection systems for http client i go over setting up a a better console in a different video on this channel and so i'd encourage you to check that out also if you want to learn more about swagger i would encourage you to check out the timco retail manager series where we go kind of more depth and actually use it in a real world type setting now we don't generate our clients but we do use it to test our api and try different things out so those are the changes in api they seem minor just adding swagger or open api and making sure that it starts on that spider page when you hit f5 those are the big changes api besides the behind the scenes speed improvements there's a lot of performance improvements in net 5. every version of net core has major speed improvements so if nothing else just upgrading a.net core will give you better speed in your application how much depends on your application and what you're using but it will perform better so those those are two what seems to be minor tweaks but at the same time they enable us by default to create this type of system where you have auto-generated clients really cool stuff i think it's really important and i think that it's something you should at least think about implementing in your apis i also want to at least check out nswag try it out with a generated client see how it works see if you understand the code and maybe read that code as well because that will increase your knowledge around calling apis so with that i want to finish here for this video in the next video we're going to talk about something that's not necessarily new but something that i think is important to talk about in in this whole net 5 era and that's the concept of http rebel and so we'll talk about that and how to debug much more easily our apis using http rapple so in the next video but for now thanks for watching as always i am tim cory [Music] [Applause] [Music] you
Info
Channel: IAmTimCorey
Views: 87,373
Rating: 4.9383597 out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, asp.net, .net core, .net 5, webapi .net 5, webapi asp.net core, asp.net core, nswag, swagger, openapi, web api swagger c#, web api swagger, install swagger web api, swagger in web api core, swagger c# web api example
Id: nY-w9wPFEuY
Channel Id: undefined
Length: 46min 47sec (2807 seconds)
Published: Wed Nov 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.