ASP.NET Core Tutorial for Beginners | .NET 7

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
asp.net core is one of the most popular Frameworks for building web applications on the.net platform in this tutorial I'll show you how to build a complete race API step by step using asp.net core and the c-sharp language let's get started by taking a quick look at the topics I will cover across this tutorial you will start by learning how to use HCL net core and c-sharp to create a rest API to manage against catalog of a fictional game store in this race API you will initially implement the traditional post get put and delete operations with only a few lines of code after the initial implementation you will learn how to filter proof your API by incorporating several essential techniques like route groups input validation extension methods and data transfer objects as well as useful patterns like dependence injection Singleton and repository then you will stand up a SQL Server database in your box and you'll learn how to use the asvm network configuration system and the.net secret manager to securely connect your res API to the database and following that you will learn how to use the popular Entity framework core or in framework to easily query and modify your database data using only the c-sharp language finally you will learn how to use the asynchronous programming model to improve the API performance and get it ready to scale that will give you a solid understanding of how to get started building res apis with Asia netcore if you want to go beyond the basics please check out the link to the full course in the video description where I cover many other topics that will expand what you'll learn in this tutorial and will give you a full picture of everything needed to build a production ready rest API with.net next we'll take a look at the finished rest API in action across this course you will create the rest API for a fictional game store and in particular for the game's catalog section of that game store so if you scroll down a little bit here you're going to see that we have a bunch of endpoints to perform the typical product operations for games management so in this case it would be an endpoint for getting all games an input for getting a game by ID for creating a game for updating a game and also for deleting a game and there's also an endpoint over here to upload the image that's going to be Associated to each of the games now of course for each of these endpoints you have a full description let's say we expand the boot input here you get a full description of what this endpoint is for what are the parameters supported by that endpoint what is example request body that you can send for that endpoint and all of the expected responses that you can get from that endpoint right the same thing for all of the endpoints and if you go all the way to the end you're also going to see that we have the full list of all of the contracts or details that are supported by this race API and one thing you may notice here is that there is a mention of a version right here right B1 for one of the videos and that is because this race API actually supports multiple versions to allow for introducing new features without having to break our clients unnecessarily so if you go all the way to the top you're going to see that you can actually select up here you can select between V1 or V2 of the API right where V2 in V2 we have only implemented a couple of endpoints but they return a different video in this case and with a different payload for the clients that are supporting that new version now going back into V1 if you notice here this rest API exposes its open API specification via this swagger.json file if we click on that this is the open API specification for the rest API which allows any other kind of tool to easily start interacting with that API and in fact what I did is I just took this Json here and I brought it into my Postman tool which is a super popular tool for interacting with rest apis and nothing importing the rest API I have the capability to start interacting with it in a very easy way so for instance if I wanted to go ahead and get all the games that have been created in my database I'll click on the get all games and put over here and then I can go ahead and click on send and that's going to go ahead and retrieve the games that are stored in the race API as you can see now one thing to notice is that I'm not creating this in my local box I'm actually going ahead and creating this directly from the Azure Cloud right because across this course we want to show not just how you can create this API in your local box but how you can interact with it and deploy it all the way into a production environment in the Azure Cloud right so everything here is coming from the cloud now in this in this endpoint you can also do things like paging right so you can go ahead and just add a little parameter here to say let's say I want to do a page size of 10 right to get 10 cases both to the default 5 games and so if I hit send now I'm going to get a list of 10 games as opposed to the initial five that we had before and we also support a feature of a search right so you can do now filter and we can say okay so I want to filter I only get the racing games right opposed to all the games so I'm going to click on send and this time I only get the racing games Mario Kart 8 Delux and Forza ryzen 5 which are my racing games right so you can search either by the name of the game or by the generator of the game and if I wanted to create a brand new game I could go into the post endpoint over here to create a new game and I'm going to expand this a little bit down here so we have a payload here to create a Minecraft game so I'm going to click on send but when to notice is that it doesn't succeed right we get 401 on authorize it and that is because all of the endpoints that allow for any kind of modification of the data are protected right so they are behind the authorization and authentication features of ethernet core so you will not be able to just access that that way so in order to actually send the request what we have to do is go in to auth and we have to enable let's go ahead and enable ol2 and I have pre-configured a bunch of settings here and so what I'm going to do is just get a brand new access token over here and that is going to actually open up the page from the odd zero service which I think configured for this API and I'm going to log in as the admin okay so I'm going to login and after successful login I'm going to go ahead and receive my token as you can see here's the access token and then I'll do use token so that we now have the ability to actually go ahead and I'm going to hit send once again and again has been created as you can see that was a success okay so across this course we'll learn how to perform all of this integration to make sure that your API is fully secured and of course we could keep trying the different endpoints over here in Postman but I think the best way to really show off what your recipe I can do is by integrating it into a real and modern a client UI right so that's why this course includes a ready to run client application that I can show you right now and which is an application that you don't have to code all you have to do is use download the source code that's included with the curves and you can go ahead and just run it and it's ready to go ahead and connect to your.net Res API now notice that this application is also running fully in the cloud as you can see right here this runs in the cloud so that you can get an idea of how to run both your client and your rest API end-to-end in a production environment and of course in this application you can also see all the features that we saw in the rest API also enabled here in terms of querying right you can go ahead and do pagination as you can see you can go to page 2 page 3 and here's a brand new Minecraft game that we just created via the address API which doesn't have any image just yet and then we can go to back to page one I could use this search box to just type here let's say Final Fantasy that's going to retrieve all of the Final Fantasy games from the res API or if I wanted to just look for racing games again that's going to retrieve all of the games from the rest API that have the raising generate all right and so let me clear those those search a filters and of course one thing that we seem to be missing here is the ability to modify the scan catalog here and that is because we have not yet logged in into the application so let me go ahead and click in the login button in the top right over there so I'll click on login and that's going to once again pop up the aort0 authentication page so I'm going to log in as an admin and after doing that the client recognizes that I am an authenticated user and I have the correct role and I'm in role to be able to do these modifications and I can see now we have a bunch of new elements showing off over there and also down here and down there right for each element for each game we can go ahead and do modifications so now let's go ahead and for instance let's go ahead and create a brand new game so let's say we're going to be creating the Super Mario Bros 3 Game right which is going to be and we can select here of course that is going to be kids and family and let's scroll down and the price is going to be 19.99 on the release day it was 10 23 1988 so a while ago and so here you can also go ahead and choose a file that you want to use as the image for this game right and so here's the game catalog you're going to get also as part of the downloads for this course so you can go ahead and select one of these images I'm going to select the Super Mario Bros 31 open and this is going to go ahead and upload the image into the Azure storage service right and retrieve the actual URL back into your res API so that when you save the game you now have you see page three now you can see that we have our Super Mario Bros 3K with its nice image right there and of course just like you can create games you can update your game so for instance let's say for Minecraft we don't have an image there yet so I'm going to click on the edit button right here and I'm going to say that this is actually Minecraft uh for Nintendo switch and then we're going to say that we actually want to choose a file for it so I'm going to click choose file and then I'm going to select my Minecraft image over here click open again the image gets uploaded into the Azure storage service and then I'm going to click on Save and if you go back to page 3 you're going to see that my graph now shows its nice image and finally you can also have the ability to delete a game right so I'm going to go back to page one and if I didn't want to see any more my fortnite game over here I'm going to click on delete I'll say delete there and now the game is deleted and it is replaced by a game from the next page so now that you know what you're going to build in this course let's talk about what you need to know before starting with the course topics in order to take this course you should have some basic knowledge of c-sharp Java or a similar object-oriented language you should also know the essentials of web development and it would also help if you have some experience with relational databases however this is a beginner level course so you don't have to be an expert on any of these topics since we write every line of code from scratch and everything we do is explained in detail next we'll go over the software prerequisites that you will need in your box to get started in terms of the software prerequisites for this course all the tools you'll use are across platform so you can use any computer with Mac OS windows or Linux as a operating system you will also need to download and install the following the.net software development kit or SDK which includes everything needed to build and run the net applications Docker desktop which you will use to run your database server Postman the popular API client that you will use to interact with your rest API and pixel Studio code a lightweight but powerful source code editor that you will use to write build and debug your code you could also use any other code editors if you prefer but BS code is your best choice to follow along step by step please make sure you download and install these tools in your box using the URLs on screen before starting the coding part of the course in this lesson you will get an overview of asp.net core why you want to use it and the different types of applications that you can build with it so what is ASP and net core well in simple terms asp.net core is a popular web development framework for building web apps on the.net platform ASP stands for active server Pages which was Microsoft's first server-side scripting language and in gene for dynamic web pages and was released in December 1996. it was superseded by asp.net in January 2002 with the first version of that.net framework and several years later around 2016 it was superseded Again by Asia netcore where core mainly hints to the cross-platform capability of this web framework now it will be good to also briefly mention what is a.net platform and how it relates to ASP and netcore.net is a free cross-platform open source development platform for building many types of applications the Govern apps for Windows desktops to web applications Cloud applications mobile applications games app for internet of things and even apps designed for artificial intelligent scenarios.net is a unified platform that serves the needs of all app types to make it easy to reuse code across all of your apps now in this course you will focus only on asp.net core which stands for the web type of applications that you can create with the.net platform now how do you create HP network applications well you got to use a programming language but that language is not really.net or even asp.net core you get to choose between three languages to create your svnet core apps which are c-sharp F-sharp and Bissell basic but in this course we will be using the most popular one which is c-sharp when you install the.net software development kit or SDK you get access not just to these languages but also to a series of tools that make it very easy to get started with the platform even before choosing a code editor or IDE you also get access to a Microsoft and community supported set of libraries and packages that can quickly expand the functionalities of your app so you don't have to reinvent the wheel there are many ways to deploy ASP and net core apps to make them available to your users that go from simple xcopy deployments to fully dockerized deployments ready for the cloud your API unit core apps are cross-platform meaning that the same code that you write once can run on Mac OS Linux and windows and it's all open source on GitHub along with.net core it has thousands of contributions by hundreds of developers and companies making it one of the fastest growing and loved projects on GitHub we talked about the different kinds of applications that you can create with a.net platform but even with asp.net core there are also a few types of applications that you can create on one side you can create very rich Dynamic and interactive web uis or front-ends with the extensive UI framework included in Asia netcore but on the other side you can also create many kinds of secure and Powerful backend services that can provide data to the web UI or take care of long-running or compute intensive scenarios that don't need any user interaction now when you create web uis with HP and net core you have the choice to create either server renders or client render uis a server rendered UI dynamically generates the HTML and CSS of the pages on the server in response to browser requests so when the page arrives to the browser it is ready to display to create this type of apps you can choose either A3 Nets NBC framework which uses the model view controller pattern or the Razer Pages framework which follows a page-based model a client render UI dynamically renders the UI elements on the client directly updating the page you see in your browser as necessary this type of uis are also called single page applications or Spas since usually there's only one single page that is continuously updated as you interact with the site asp.net core includes a complete UI framework known as blazer for building this type of application with c-sharp HTML and CSS there are also several choices for building back-end services web application programming interfaces or web apis are the most common form of backend Services giving how easy it is to use them to query or send data from and to backend servers using the HTTP protocol asp.net core offers two approaches to creating apis controller based apis which use controller classes to handle API requests and minimal apis which Define endpoints with logical handlers in lambdas or methods besides web apis you can also create real-time applications via signalr to push content directly from the server to the client or erpc apps which allow for high performance remote procedure calls between clients or services or even background worker Services which can perform tasks that usually require no user input like loan running or compute intensive operations or even tasks that starvasted on some sort of external event you could also create microservices which are business aligned Loosely coupled services that small and focused teams can build and deploy independently using one or more of the available back-end service Technologies I just mentioned now in this course we will focus only on backend development and more specifically we will only cover the creation of production-ready rest apis using the minimum apis approach since it's the easiest way to get started with minimal code and configuration in the next lesson we will get our development environment ready to start creating ASP and netcode applications at this point you should have already installed all the software practices that I mentioned in previous lessons if you have not done so already please go back installable requisites so that you're ready for what's coming next now here I am I Visual Studio code and the first thing that we're going to do is to just change a few settings so that our c-shar development experience becomes much better so what I'm going to do is just go into file and then let's scroll down into preferences and then settings and here we're going to be looking for aesthetic cold place open Rays and the settings we're looking for are place open brace or new line for control blocks and place open Rays on new line for functions so if you want to tick both those settings and that's going to allow us to make sure that anytime we create either an if else or a switch or any of those control blocks so that the curly brace starts in the next line same thing for functions we want that cool erase to go to the next line so this is more of a personal preference but I find it that it makes the code much easier to read and the next setting that I want to enable is one called format on Save so if you're looking at this setting over here for model save and you want to tick on that one and this is going to allow us so that anytime we save a file uh the editor itself is going to format that code so that it just looks better right so that's going to save us a little video of keystrokes then what you want to do is go into file and then you want to look at this setting over here called auto save right there case I'm going to go ahead and click on that one and so with that one what's going to happen is that anytime you make changes to your code files those changes are going to be automatically saved into your machine without you having to save or hit Ctrl s or anything like that the code is just going to be Auto saved so I find that also very useful as I go through the changes in my machine so that's it in terms of our settings and I'm going to close this and also close to close that and the next thing that we're going to need is the a couple of extensions so if we go into the extensions Hub right here the extensions Hub click on that and the only extension that I have installed so far is this one called vs code icons and I'm going to close this because I guess which just gives some nice coloring into the a file explorer in vs code but the one that we really need is this one called C sharp and this is going to be the very first one the one created by Microsoft this one over here you want to install this one so just click on install all right and that's going to start in just a few seconds and this is going to bring in all of the C sharp productivity features enabled by the omnisart server which is an open source implementation that allows you to have really all sorts of intellisense and all sorts of nice productivity features of c-sharp in your Visual Studio code experience lastly you also want to bring in another extension called c-sharp extensions okay and that's going to be this one over here and notice that this is the one by Jaws creative right there are a bunch of versions but this is the one that you really want and you want to just click on that and click on install and this is going to add a few other context menus that are going to make it much easier to create c-sharp files inside Visual Studio code so that's it in terms of the extensions I'm going to close this and close that and the last thing I'd like to do is just to verify that.net has been properly installed into the box so what I'm going to do is just go into my terminal by going into View terminal and of course you can also do this if I close this by just doing Ctrl tilde on Windows or you can also do Ctrl J which is my favorite shortcut and in this terminal all I have to do here to verify that that has been installed is just to.net dash dash info and that's going to bring in all of the information about the version of the data you have installed and as you can see here's the version that I'm using right now is version 70203 you don't have to install specifically that version it doesn't have to be 70203 but it has to be version 7 right so you want to make sure that you're using version 7 of the.net SDK and that is because I will be using a few features that only showed showed up in.net7 right so you need that that version and also you don't want to go a version evolved like version 8 or anything like that because the predict templates that I'll be using in this course are based in the net sdk7 and I'm not sure what kind of changes are going to come in those predicting plays in future versions and that could make it so that you cannot follow what I'll be doing on screen the exact same way so make sure that you have the Net 7 SDK installed in your box so with all this ready let's move on into the next model where we're going to learn how to start creating our first.net risk API in this model you will learn the basics of race apis and how to create your first rest API using the tools included with the.net SDK by the end of this model you will have a solid understanding of the following what is a rest API how to identify resources in a res API how the different rest API HTTP methods work how to create and configure a web API project in asp.net core how to implement a basic res API with asp.net core and how to test your best API using Postman in this lesson you will learn the essentials of web apis in asp.net core how to identify resources in a rest API and how the different HTTP methods work so what is an Athea netcore web API well it turns to be that it is nothing more than a rest API implemented using asp.net core and your next obvious question is going to be what is address API to understand what the rest API is instead by thinking about all these apps that you have in your phone like your weather app Twitter or Spotify these apps use a ton of data like the latest weather information the top tweets of the last hour or the hundreds of hours in your favorite playlists however that data can't live in your phone which is what we know as a client because it will be way too much data to store in your device and you want fresh data all the time anyways so the data has to come from somewhere and that software is going to be some sort of server computer that usually lives somewhere in the internet Cloud how can these apps talk to that server in the cloud to retrieve that data well by using an API API stands for application programming interface and is how a service defines the functions it provides to clients so for instance going back to the Spotify example the Spotify cloud service could Define an API with two functions get recent songs function that receives the username as a parameter and that Returns the 10 most recent songs for the specified user there could also be a play song function that receives the song name as a parameter and that Returns the stream for that song so that a client can play it like this there could be dozens of or hundreds of other functions offered by the service that clients can use to interact with it so an API helps clients communicate what they want to the service so it can understand and fulfilled request so what is rest rest stands for representational State transfer and it defines a set of guiding principles that impose conditions on how an API should work we won't dive into each of these principles in this course but the important thing to know is that thanks to them you can build apis that are scalable flexible and independent of the technology being used in the client and in the server so going back to original question arrest API or vessel API is one that conforms to the rest architectural style now the main reason why we want to stand up a rest API is so that our clients can interact with the data that it manages but how do they actually reach that data well for this it is good to First understand the concept of a resource in a race API in a rest API a resource is an object document or thing that the API can receive from or send to clients for instance in our game store application the main resource is going to be our games that's what clients want to query and modify but in all applications like the Spotify example one of the resources could be the songs and in the Twitter example one resource could be the users and another one that tweets themselves these resources will be hosted on some domain which could be a public domain an internet location or it could be just your deadbox and they can be accessed either via the HTTP protocol or the https protocol which is a must in public environments so when you combine all of these you get what we know as and uniform research identifier or URI and that is what your clients will use to identify and reach the resources on address API there could be more parts to this URI but these are the essential elements now how do you actually interact with the rest API well just like with traditional web pages when clients want to request something from the servers they will send an HTTP request using the resource URI to the server and then the server will send back a response however in rest apis these requests and responses will look a bit different depending on the specific HTTP method used to call it the most common methods are post which creates new resources get which retrieves the representation or state of the resource put which updates an existing resource and delete which deletes the resource so these methods allow you to create read update and delete resources and therefore they are also commonly known as crowd operations there are other methods too but for the purposes of this course we'll focus on these four ones let's take a quick look at each of these methods in the context of our games for example to understand better how they work to request all games a client will send get requests to the game's endpoint and the server will respond with something like this the first part of this response is the status which is 200 okay in this case this means that the operation was a success there are many other HTTP status codes that the rest API will send back depending on the result of the operation many of them for failure scenarios the next part is the body which contains the list of games in this case notice that this body is not HTML which would be expected to render traditional web page here the format of this response is known as Json which stands for JavaScript object notation this is the de facto format for sending and receiving data in res apis because of how easy it is to read and write and is supported by all major programming languages If instead of getting all games you wanted to get a specific game you would again send a get request but this time you would append the research identifier at the end number one in this case the server will respond with the state of the game with that identifier assuming it is able to find the game to create a game the client can send a pause request once again using the game's resource UI but this time it needs to specify the desired resources state in the body of the request which in this example only includes the name of the game but could include many other properties of course the server will usually reply with a 201 created status code and if the resource identifier was not specified as part of the request body the response will usually include it to update an existing game the client sends a put request with the same resource URI as the one to get a game but this time it includes the resource State just like in the post scenario the server will completely replace the state of the game associated with the specified identifier with a new state and will typically respond only with a 204 no content status code finally to delete an existing game the client sends delete requests to the URI that identifies the game to delete and after deleting the resource the server will usually respond with a 204 no content status score so in summary your complete games rest API would look something like this and it should offer all the support that your clients expect from the modern backend let's now jump back into the code to see how to implement this rest API in asp.net core so let's see how to go ahead and create our first.net address API so here I'm back in pixel Studio code and the first thing that we're going to need is some sort of directory where we're going to be storing all of the files for the rest API so what I'm going to do first is to just get rid of this welcome screen and I'm actually going to click on this checkbox over here because we're not going to be needing this welcome string anymore close on that and then we're going to do is to open my terminal and to open the terminal what you can do is go into view terminal right that's going to open it or you can also use a shortcut like on Windows you can do control tilde or you can also do Ctrl J to open and close your terminal and now we are in the terminal I'm going to go ahead and just switch into my D drive then go to go into my project directory and here I'm going to go ahead and just create a brand new directory that I'm going to be calling game store of course you can create or use any other directory in your box this is just the one that I chose for this for this course and now that we have our game store directory created let's go ahead and open it in Visual Studio code so I'm going to go into file open folder and then we can go into my d project and then game store directory right here and then I'll just click on select folder and that's going to open Pixel Studio code in the context of the game store directory okay so now is the time to go ahead and create a project so to do that we're going to be using the.net CLI in our terminal so let me first collapse this pane for a moment and then I'll open up my terminal using Ctrl J I'll open up this a bit more and then to use it.net CLI all you have to do is just use dotnet and in this case the new word or there and then before we carry the project let me show you just a quick list of all the project types you can actually create here so I'm going to say just list and as you can see this is a full list of all of the different project types that you can create with the.net CLI and that goes from Asia net core products as you can see here we also have some Blazer projects that you can create you can create class libraries you can create a console apps and you can create really a bunch of different types of projects but the one that we're mostly interested in here is this very first one over here Asia net core empty a application a short name web because that's the one that's going to provide us with a very clean slate to start a start very small with this web API and we will start building up on top of that over and over across this course all right so let's use that template so for that let me just clean my screen and I'm going to say dot net new web and they will use the dash n argument to specify the name for the project so the name is going to be game store dot API right so I'll hit enter and then the.net SDK is going to go ahead and provision or create the project files for a for us so if I now go let me just restore my terminal over here go to Explorer and if we expand on the left side you're going to see that we have a bunch of new files it just created so let's take a quick look at each of these created files so that we get a better idea of what each file is for so let me just close my terminal and let's open up game store.api.cs proc so this file Here is known as the project file so you always have a break file and this is the file that's going to describe what type of project this is so in this case as you can see here this is going to be a web type of project which makes sense because this is a web API okay and then another important setting here is the target framework which in this case it is a net seven zero okay so this target framework defines which are going to be the set of apis from the.net SDK that are going to be available for your project or for your application right so since we didn't specify a specific version when we created project it just defaulted to the version of the SDK that we're using which is.net7 I'm not going to go over the other the other contents of this file right now but just know that they're going to be another important thing here is going to be the project dependencies that we're going to bring in later on but we'll take a look at those when the time comes now the next file that we're going to look at is program Cs and this file is known as the entry point of the application now usually when you open up a C sharp file in Visual Studio code you're going to get this prompt over here and what you want to do is just click on this adjust button over there just click on JS because that's going to go ahead and generate a brand new DOT DS code filter over there which we're going to be talking about in a moment but it's very important to enable a nice a building and debugging experience Visa Visual Studio code now also notice that as we open this program.cs file the omnisharp server it was started and you can tell it because of this little fire Arc icon that you can see over there okay that means that the only charge server started and like I said before Omni sharp is the component of the c-sharp extension that enables all of the nice c-sharp features in telesense and a bunch of productivity features of c-sharp inside the visual studio code experience so you want to make sure that you always have omnichar up and running in your in your c-sharp projects now if for any reason this vs code folder did not get generated when you open the C sharp it's CS file over here you can always generate it manually by just going to your command plate so you can go into view command plate and then what you want to do is just look for this option called dotnet generate assets for build and debug so you click on that one and then in this case of course it's going to ask me to replace what I have but in your case you can just go ahead and generate the funds for you okay so that's another way to get these things up and running so I'm just going to hit cancel here now what is going on with this program.cs file we're just a few a few important things the first thing is that we're creating this optic Hill does is a web application Builder object right with this very first line and this object is going to use it to define or to register a bunch of services or to configure a few things that are that are essential for your application right now we don't have any Services ready to configure so that's fine but later on you're going to see how we're going to be using it extensively to configure and to set up a bunch of services for the application now the next line here uses that Builder object to build a what we know as the web application and which is this app object over here so that object that up object over there is one that you're going to be using for defining the application pipeline uh we're going to Define multiple things like for instance the endpoints are going to be available in your race API as you can see by default we got one one endpoint Define it right here right which is listening is going to be I get a type of endpoint so it responds to the get a operation and it is listening it's going to be mapping into the root of the application and then this Lambda here defines what's going to be the response when somebody invokes that and that endpoint and we'll see this in action in the next lesson but for now just know that this is a very simple way of defining your initial endpoint there and then the last line app that run just goes ahead and starts the execution or runs the application in the host in the Caster holes in your box right so that it can start serving requests a couple of other files that we have available here are absence.json and app development.json and these files are normally used to define a set of configurations that you don't want to hard code in your code files right so that way you can have different sets of configurations that can have different values depending on the environment where you're executing your application right for instance absence the Json is usually the one that's going to be available for the production application but you can also have access to development and Json that's going to set specific values for your development environment and you can see Hardware defining logging here for the development environment but we'll talk more about logging in a future model another important file here is going to be inside properties launch settings.json and this one defines a what we know what we know as profiles right that Define a bunch of different settings that are going to be available for your application only where you're running in your development environment or in your the box for instance this first section over here on their profiles this section Here is known as the HTTP profile and it's going to be the default profile that's going to be activated if you don't specify a specific profile and this one is going to define a few things but the important most important one is going to be the application URL right here so this is the URL that you can use in your box to access the rest API now that port number over there 5115 got automatically or randomly generated for me as I created the project so you're not going to get that same port usually you'll likely get another Port but regardless this is going to be the location of your application for HTTP purposes now if you do want to use https in your box you can also go ahead and use this other profile over here the https profile right so there are arguments in the.net you can use to start using that profile there and as you can see that defines an https URL that you can use to start using https instead of HTTP now in this course we'll be mostly using a HTTP there are also some other settings for IIs but we're not going to be using also IX Express or is in this course at all now we also saw that that we got this BS code fault generated on the left side and so this this folder has two files the first file is named Dasa Json and this one defines how you're going to be building your project using the built-in tools of a visual studio code and then we also have the launch.json file which defines how is that Visual Studio code can start and initiate a debugging session of your application uh within Visual Studio code and so now that we know what all of these files are for uh in the next lesson we are going to see how to build and run and also debug the application within visa to the code let's see now how you can go ahead and build run and debug your application inside visual tool code so to build the application what you can do is the following let me go ahead and open the terminal I'll choose Ctrl J so this opens my terminal and I'm going to switch into my game store.api directory okay because that's where the files actually live now from here all you have to do to build it the project is just type.net build like that and that will go ahead and build the project and produce the output dll as you can see right here here is the game store.api.dll generated which are going to find under bin on the domain directory you're going to find your dll right there okay so that represents the compiled version of your application now in order to actually run the application what you can do is the following so let me click this you can go ahead and say dot net run okay hit enter and that's going to spin up and start hosting the application locally in your box and you can see that you also get your your whole support right here this is a whole support that you can use in your box to access the application okay so what happens if we just navigate over there so let me show you this I'm going to just copy that URL and I go into my browser now over here I'll just paste that hit enter and as you can see we are getting our hello world displayed in this a very very empty web page and this makes sense because if we go back into the code you're going to remember that in program CS what we have is just one endpoint over here that when when you go into the root of the application it responds with hello world right so that's what we have right now but of course we're going to be expanding this significantly to Define our API later on so that's kind of one way to do build and run of application now another way that you can actually build application and let me close this for a moment is by using integrated Visa Studio code experience since Visual Studio code generated this launch.json and data Json files right what you can do is is this you can go into your menu bar in this case uh it'll show Three Dots here because it's a bit smaller but you want to look for the terminal menu in your bar and then just go into run build task or Ctrl shift p so you click on that and that's going to go ahead and build your project directly using the visual studio menu now because we can do this using the integrated that integrated build menu it also means that we can just do a control shift b as I just did and then build directly and all of that is enabled because of the task.json entry that you have defined over here using data Json you have this this build test defined over here and because of that you can do well what I just did right so like I said Ctrl TV we'll go ahead and build your project now if you wanted to debug your application using Visa Studio code and use breakpoints and stuff what you can do is just call let's go into program.cs for a moment and let's put a breakpoint let's say over here okay and let's see if we can heal it now in order to start a debug session what you want to do is go into this debug view over here the debug view so you click on that and that's going to show you this pane over here and run on the Block where in this drop down you're going to see the different launch configurations that are defined in your Logitech settings a lot of Json file so let's click on the netcore launch web and then what you can do I'll just collapse this for a moment and I'll click on the start debugging Bullock over there and we're going to see is that the debug session actually starts we hit the breakpoint right here and you can even inspect the variables if you wanted to and then of course you can step over and do the useful things you can see the yeah the content of all the variables and then you can just click on play so that this continues executing and as you can see this opened a browser window right with again with our hello world displayed right there just as we saw before so that's how you can debug your application inside Visual Studio code and like I said and I'm going to stop this this is enabled again because of the launch.json file that was defined when that was Auto generated a pipel studio code now one thing that I'd like to change here is this one setting over here and this is because this is setting that enables opening the browser anytime you start debugging right so if I just do like like I just did right with the debug section here or even with F5 I can just hit F5 right and what's going to happen is that it's going to start application and it's going to hit breakpoint I'm going to remove this breakpoint for a moment hit play and it's going to open yet another browser right so as you can see this is going to get a little bit polluted with too many browser windows for our web API and the thing is that you don't really use the browser to do any sort of testing of your web apis so this is really not needed so what I'm going to do is just go back to this to your code I'll stop this close that and then go back to launcher Json and what I'm going to do is just remove this section here that says server reduction right because if you just remove this the browser is no longer going to open anytime or every time you start a debugging session so I'll hit F5 once again F5 this is indeed going to start the debugging session as it did but it's not going to open a browser anymore right I find that super convenient because otherwise yeah like I said you have end up with so many browser windows most of the testing of the API is going to be happening in the postman application which we're going to take a load pretty soon so now that we know how to build run a debugger application let's go into the next lesson where we're going to learn how to define the entities that are going to be needed by our res API it's time to define the class that is going to represent the resources that our res API is going to manage so for that what we're going to do is just right click at the gamestop.api directory so you just right click there we're going to say new folder and then we're going to be typing entities so here's what we're going to be defining our game entities right so the game is what defines the resources that are going to be managed by our game store API let's just go ahead and right click on entities and then new c-sharp class and the name of the class like I said is going to be game now one thing that you can notice here is that the c-sharp extensions extension that I'm using vs code is actually defining the namespace as a block sculpting space right as you can see here because of the curly braces that is here so the class is inside the namespace and that is okay but I think these days a better way to do this is by using another thing called block scoping spaces which saves a little bit of space on screen so if you just step over the anywhere in the namespace name over here and you click on this light bulb we're going to see is that you can select this option that says convert to files Opening space so if you just click on that you're going to hit that now the class is at the very very left right and then the namespace has has this semicolon on the end right so it's kind of the same thing but now we're saving a little bit of horizontal horizontal space which I think is a is a Big saver a small Improvement but a big Saver in terms of horizontal space and just like we did that let's also go ahead and clean up a little bit decent spaces at the top so what I'm going to do is once again you can just put your cursor anywhere in these namespaces here click on the light bulb and then you can select remove on a society usings so I'll be doing this exercise of using file company spaces and just cleaning up the namespaces over there yourself we have a cleaner code overall so now let's go ahead and Define the actual properties of our game class and the first property is going to be the ID so let's define and you can just type prop and then tap that's going to define a property just like that and then the type name the type is going to be int that makes sense and then the name is going to be just ID right so that defines our ID property let's go to the next one this is going to be the name the name of the game so again just type prop Tab and then this is going to of type string and then it's going to be name now one thing that you can notice here is that we have a small squiggle here with a warning right that what it's saying is that uh we have defined a property of a string type but we have not set any value for that property right so what the compiler wants us to do here is to actually Define some value for that string property or to find that the property is going to be no longer right so you could do something like this write some value if you wanted to like that and that's going to satisfy the constraint or you could do something like string.empty there right or if you wanted to keep it nullable because you're saying well it doesn't have to have a name then you could just add this question mark over here right and that is going to turn it into another one right so the the point here is that the compiler is trying to make sure that we don't end in a situation where we Define a property that could be no level but we have not declared that it could be new level and later on we run into issues because of not defining these properties now the thing about the game the name is that we don't want it to renewable we do want it to be a required a parameter right it has to have a value and these days luckily what we can do is just to define a keyword and that allows you to specify that yes that a value has to be a specified for name but we don't have to specify it right here in the definition uh you just have to say that this property is required just like this required that means that whoever creates an instance of this game a class has to specify a value for name either in the Constructor or as part of the property initialization when the variable the variable has been declared and yeah it's a very handy feature and we'll be using this require a keyword quite a quite a bit across this course so now that we have a required we have the name let's go ahead and Define prop string this is going to be our genre right the game generate and this should also be required so let's do required the next one is going to be the price so this is going to be of type decimal I think it's a good type for a for prices for for money so let's just name it price and the next one is going to be is the release date so whenever the game got actually released so let's do prop it's going to be daytime the name is going to be release date and lastly we're going to be adding a property here for the URL of the image that is associated to this game write the picture of the game so let's do prop and this is going to be string and let's name it imesh URI and then this should also be required so let's do required just like the others and so with that in place we now have our game entity ready and what we want to do now is to Define some initial list of games that are rest API which we're just going to start building in the next lesson that the rest API can start using right away right on this for now this is going to be at least in memory and in memory list of games and later on we're going to transition into a natural database right so but because right now the focus is on creating the API itself let's just use a very simple list of games so we have something to work with so let's go into program.cs and what we're going to do and let me collapse this for a moment what we're going to do is just to go to the very top and here we're going to be defining a list of games so this is going to be list of game just game and then since we are introducing a type that lives now in a different name space right so remember that game lives in game store.ap.neties what we want to do is to introduce the name space into program.cis and to do that what you can do is just step into or click into the the game word over here and you're going to see this light bulb over here what we can do what you can do with that is show code actions right so you click on that that's going to show a series of options that you can use to automatically make changes to your code so in this case we're interested in the using gamestop.api that entities as you see here so I'm going to click on that and as you can see that went ahead and right away added my using for gamestop.api.net and then just so you know another way to do this and let me just do Ctrl C here another way to do this is just by while you're in the world that has the equivalent races you can just do at least on Windows you can do control Dot and that's going to again just pop off the dialog and then you can click the option that makes sense so like I said in your case is using installer API that entities and then we have our namespace right there so I'll be using control dot all over the place across this course I find that that's the easiest way to do this so with that in place let's go ahead and say games that's going to be the name of our list and it's going to be new and then let's define our list right away so for our list let's define our first game here it's going to be new game right and now let's define the values for the different properties let's also close uh these curly braces just like that so first thing is going to be the ID okay so let's just start with a simple number ID is going to be one then the name for the name I'm just going to pick one of my favorite games of all time Street Fighter 2. and then for the General is going to be in this case firing and then for the price I'm going to say 19.99. now the thing about the this number here 1999 is that it could map two different data types right not just decimal not a price is decimal but since 1999 code map to different types the compiler gets a little bit confused here so what you can do is just actually follow the guidance that you can see in the warning here it says use an m to create a leader of this type right so you want to be explicit here saying that yes I do want to define a decimal and not just any other random type so just by placing the M right here you're clearly stating that this is a decimal so that makes the compiler happy and uh let's go ahead and say release date is going to be new daytime all right so the daytime for this one is going to be 1991 2-1 and lastly we want to specify the image URI right now what image here I want to use here where you could use really any image right it doesn't matter really too much at this point but later on when we get all the way to trying to show the games in Decline you may want to have something that just doesn't render a broken image or a random thing because of that what I like to do is just use this a very nice service that's called placehold.co which provides you with a kind of a placeholder of an image of any size so for instance I can do the following https placehold.co slash 100 and what that's going to do is to generate a simple placeholder of 100 by 100 pixels uh whatever you try to display the URL so in in fact let me show you that so I'm going to copy this so let me just copy that and I'm going to go into my browser very quickly here and I'm going to paste it and then I'll hit enter we're going to see as you can see right here he said super simple a placeholder image for an image of type 100 by 100 right and just like that if you wanted to you could go ahead and do another size right 200 or you could do 300 as you need but I think 100 is good enough right so all it does is just provide us with someplace holder for the images and like I said that we're going to see later on in the client so please hold that code slash hundred uh you don't have to use it you could use any other URL but I just found found it very handy so just like we did that let's go ahead and Define just a couple of more games so that we have some data to work with in in later lessons so let me just copy this over here and so this second game is going to be scroll down a bit id2 and then I'll just put another of my favorite games here Final Fantasy 14 and then this is going to be role playing and the price yeah this is more expensive 59.99 release date is a bit more recent 2010 9 30 and then for placeholder I mean for the image array is going to be the same thing right there's there's no need to change that and then let's add a one last game here okay let me scroll down again so this is going to be ID number three the name of the game is going to be FIFA 23 very nice game and then the type is the generation Sports the price is third expensive 69.99 and the date time is uh much more recent so 2022 9 and 27 and for image here I will just keep the same thing and so with that in place now we have our game entity and we have our initial set of games which like I said we're just going to do in memory for now and later on it's going to be an actual is actually going to be coming from our database but for now this is going to be great for us to move to the next lesson where we're going to go ahead and Implement our first API endpoint to retrieve the full list of existing games let's now go ahead and Define the first endpoint for our res API and this is going to be the endpoint that's going to retrieve the full list of games here we're back in our parent.ts file over here and as you remember we do have our in-memory list of games Define it right there and we're going to do is to just go ahead and collapse this just to save a little space on screen and what we can do now is to just pretty much follow the lead of this initial get endpoint that has been defined here I'm going to be reusing it to return our list of games now like I mentioned before there are a a bunch of metals like this one here map get that you can use to map different patterns into handlers that can take action whenever that pattern is invoked in a rest API so just like map get if you do control spacebar you're going to see that there are a bunch of other options like map post map put mod patch and map a delete and others right so let's go ahead and Define our gate and the first parameter in here like I said is the pattern so this is the pattern that has to be matched as a call from the client so that the Handler can get activated so in this case it's going to be just a pad and the path that we're going to be using for our games rest API is going to be just games notice that I'm going to be using plural here right so games I'm not just game because that is the correct way to define a restful API so this is going to be defining the resources that are going to be managed by the API right and this is going to be game so all of our calls are going to be starting with games not just game but games and what we have the pattern we want to define the Handler so this Handler can take a few shapes but it's really in this case it's just going to be a simple Lambda expression that's going to be defining what we're going to return so in our case what we want to return is just this list of games that we have over there so what we can do is just replace this with games and just by doing that you have already defined your very first endpoint for your race API now let's see how to how this works so I'm going to do Ctrl J to open my terminal over here okay I'm going to be closing that and cleaning up this and I'm just going to switch into kingstore.api which is our actual directory and that's just going to type.net run okay so this starts the API and once again it gives us the the location of the API in this case it's localhost 51 15. so I'm just going to copy that and I'll paste that in my browser for now so let me just go into my browser over here so here's the the localhost and and the port but remember that we need to Define here the full route into the res API endpoint right so if you remember you remember the MPI endpoint is actually under slash games so I'm going to copy that because that's the part of the input we want to hit and then back into the browser I'll just paste that over here and then I'll hit enter and as you can see we are getting now a representation a Json representation of the resources that the API is returning right there you can see the list of games right so the three games are showing up right there and that pretty much defines the result of our rest API invocation now of course looking at the rest API responses like this is not going to be very useful as you can tell and there are much better ways to do this so in the next lesson we're going to be learning how to use the postman tool in order to properly query and work with RBS apis let's see how we can use the postman application to start working with our res API now the first screen that you're going to see usually when you start Postman is this one over here which is asking you to either create a free account or to sign in into your personal account now if you wanted to you could also go ahead and just click on this link over here to skip and go into the app directly but I found that the experience is a little bit better when you actually have an account so I would encourage you to go ahead and create creative account if you don't have one already in my case I already have one so I'm just going to click on sign in over here and that's going to take me into this a tab over here I'm going to just select my account here and then I click open and that's going to bring back the postman application over here as you can see I am now into the postman UI now in Postman the best the the main way that you're going to be tracking all of the things that you're doing Postman if you're using by deck what they call as workspaces so workspace is the is the one thing that's going to keep track of a bunch of things that are kind of related so for that what I'm going to do is just go into workspaces over here at the top just go into workspaces and then I'll click on create workspace and I'm going to create a workspace for the word that we're going to be doing across this course so you could put any name here I'm just going to put a name here named building.net res apis right because that's the name of the course and then I'll just click on this option here personal okay that should be good enough and then I'll click on create workspace and now we're here we can go ahead and start creating a requests right that's the main thing that you're going to be creating in Postman so I'm going to just close this overview section here and I'm going to click in this plus button right there that's the one that you can use to start creating requests so click on that and let's open up opening up this request over here now to save space I'm going to collapse this is the left section like this so that we can see better what's going on now for some reason it looks like the Zoom is too much in this screen so let me just go over here I'll do View and I'll do view zoom out so yeah now I can see much better now on this tab what you want to do is first select the type of operation that you want to invoke into the rest API as you can see in this drop down there are many many different operations that you can use but in our case we're going to be starting with the get operation so I'm going to just click on get and then on the text box on the right side you want to enter the URL to the endpoint that you're going to invoke so let's remember what's going to be the the first the host and portal we're going to invoke so let's go back into Visual Studio code over here and then you can always find that by going into properties launch things.json and in this case it's going to be in the HTTP profile that application URL is going to be right here okay so I'm just going to copy this localhost 51 5 okay I'll copy that and paste it in the text box and then remember that we have to specify the actor route into the game's endpoint so once again let's go back to vs code let's go into program that's Cs and remember that that's what we have in your map get the endpoint is cycling in slash gains so I'm going to copy that copy that and then I'll just paste that over here okay now let's also make sure that we our res API is actually running right so I'm going to go back into vs code Ctrl J to open my terminal I'll clean this and then I'll just dot net run okay so that starts the server and now I can go back into Postman and I'll just go ahead and click on this set button over here so click on that and that's going to send the request into the server so I'll click on that and as you can see down here we got our results right so we have our three games and this time things look way better right so it looks like proper indented Json right that we can understand that we can explore very nicely and we can work with that later on you will see as we move into the course there are many many utilities inside Postman that are going to be super valuable and it makes way more sense to use work over here as opposed to working directly in the browser or somewhere else so now that we know how to use Postman let's move to the next lesson we're going to learn how to create another get endpoint but this time to retrieve Again by ID let's go ahead and Define the endpoint to retrieve one game by its ID so here we're back in our program.cs file and then right here just after our previous map get call we're going to be defining a new call to retrieve this game by ID so let's just say app dot map get okay and in this case the the pattern is going to be very similar so it's going to start with games as expected but in this case we have to add one more thing which is going to be the ID so the restful way to specify this is just by adding the ID at the end of the route and then in the Handler section we're going to be defining how is how we're going to handle such a request now the hunter is going to also are going to be similar to the previous one but in this case we have to do more things right so we have to actually find that game before we can return it back into the client so for that the first thing that we're going to be needing is the parameter the ID parameter so for that you can just go ahead and Define a parameter just like this by opening and closing parenthesis like that and then we're going to be defining our int ID okay now this ID variable name over here has to match the pattern that has been defined on the left side right here so it says ID it has to also rename it ID as the parameter that we're going to be defining in the Handler now here we're going to be defining an arrow function on the right side that's going to say that we're going to returning the games but then we're going to be executing the find function and that's going to expect us to provide some predicate to to match the actual game that we want to return so here we're going to say okay so we want to find the game where game dot ID equals the ID that has been received as the parameter okay then I'll just close semicolon like that and that is the way that you can Define your get by ID and so let's go ahead and try this out and see how it works so let's go ahead and do Ctrl J I'm going to go ahead and do dot net run in the game store API directory to start our server and so let's go back into Postman and what I'm going to do is just to copy this URL that I have here in my previous get request and I'm going to spin up a brand new tab over here again with the get operation on the left side I'll paste this but this time I'm going to go ahead and add slash and the ID of one of our games so if you go back into our previous list we know that we have IDs one two and three right so I'm going to go with IDE number one so I'll just put one on the bar here and then I click on send and as you can see that allowed us to return the specific game that we wanted to find also notice that we are getting the expected 200 result over here 200 okay which means that the request was successful now one thing to consider here is what happens if somebody requests a game with an ID that does not actually exist right what would we do in that case so let's see what happens right now so in this case I'm going to ask for again with an ID of let's say four which does not exist so I'll click on send and then what happens well we are getting a very strange null response over here and for some reason we are still getting a 200 okay over here so this is completely wrong right that's not what should be happening if we are not able to find the game so to make this restful the right way what we have to do is to figure out a way to return um not found result here in this case Okay so let's go back into visa to the code and I'm going to do Ctrl C to stop my server and what we want to do is to expand this uh this Handler here a little bit more so that we can handle the case where the game does not exist so I'm going to open curly braces over there and then close curly faces over here just like this perhaps okay and then what we can do now is to actually capture the return of these games.fine call so I'm going to say so game which is going to be the game is equals to games.find and then I'm just going to close the semicolon over there and then we are getting these these curly braces here this little Point here because fine is is returning a new level result right so we should fix this by saying not just game but game with question mark which turns game into a nullable value right so we could get a null here so we have to handle that case properly so now we're going to say taking advantage of that new level thingy and I'm going to scroll down a little bit here is the following so we're going to say that if game is null we are going to go ahead and return one specific result and the red one for this one is going to be results dot not found so that means we are not able to find that resource that you have requested and otherwise if you are able to find it we keep going and we're going to say return results dot OK and in the parameter we can specify the actual gain the event return which is the so now we're handling both cases right they're not found and the successful case so if we execute the API once again I'm going to dot net run this again and I'm going to go back into Postman this time I'm going to ask for the game number four once again and let's see what happens accent and then as expected we are now getting a status 404 not found which is correct and if we go back and try to find an existing game let's say game number two we should still be getting r200 a successful status like that and we are getting of course the game on the left side okay so that's how you should be handling those cases of the a game that cannot be found so with this in place in the next lesson we're going to see how we can create a request to actually create a game in our res API let's now create the endpoint that's going to be in charge of creating games in a race API so for that we're going to be scrolling down a little bit just after get over here we're going to be finding our brand new endpoint and so it's going to be in a similar way so up dot but in this case is going to be a map post right so post is Right verb or operation that you want to use in order to create resources in the rest API now once again the the pattern or the path is going to be very similar right it's going to be just games and then for the for the request delegate or the Handler what you want to do is to specify here uh of course I mean what's going to be the logic to create this game but the parameter they want to receive here is going to be the actual game right so for that we're going to be adding just these parenthesis here and we're going to be defining our game game like that and then we Define a number function here where we're going to be defining what to do about that right I'm not going to be closing this with semicolon I'm also going to be closing this to have more space on the screen so how should we go ahead and proceed we create the game so the entire game payload is coming and in the game the optic over here but what's not going to come is the ID of the game so that will have to calculate here just like as if a database would calculate that Daddy so in our case we're going to keep it very simple for now and we're just going to say that game.id is going to be games.max and that's going to be we're going to try to get the maximum ID that we have so far and we're just going to increment it by one so we're going to say Max from the list of current games we're going to say game game dot ID so give me the Max and then just add one right super simple and after that we're going to be adding that game into our Games Collection so we're going to say games dot at the game all right let me scroll down a little bit more so we can see better and lastly we could go ahead and just say uh midterm and we could do a few things here we could do results dot okay that would be one way to do this but really they read the the right way to do this is to return a created result so that you return back the created object and the location of that object inside your vest API so to do that what you want to do is the following instead of saying results that okay we're going to be returning results that created at Route and so the first parameter here is going to be the name of the endpoint that can be used to locate a resource right so that endpoint for us is going to be this one over here remember this is the endpoint that we can use to actually get one resource by ID however we have not provided a name for this endpoint just yet so we need to do that so we're going to do is just expand this a little bit right the mapcat we're going to say dot with name and here we want to specify a name for our endpoint and the name is going to be just let's say get game all right now close these so that's how you can provide a name for one of your endpoints now since we're going to be using that name in the other endpoint luckily we don't want to use hardcore this over here but we actually want to have some sort of a variable for this so I'm just going to copy this get game name over there and I'm going to go close to the very top over there and I'm just going to define a constant to Define to Define this name here so it's going to be constring let's name it get game endpoint name that's going to be equals to get K all right and then I'm going to copy that and then use it right here and now we have that available we can scroll down once again into our map post and for the first parameter of created at route we're going to say that the route is going to be the one identified by get game endpoint name and the second parameter defines the route values remember that that route has to receive the ID right so it specifies an ID that has to receive it here so we have to provide that ID and the way to do that over here is by just saying uh creating kind of an anonymous type so you can just say new and here we're going to just Define an ID which is going to be coming from game.id they did that we just generated all right and for the last argument we can provide the actual entire object that just got created into the race API so that's going to be just game and closing semicolon so by doing this we're going to be creating a location header in the response after we are have created the game into the rest API so let's see how that actually works so I'm going to open up my terminal so Ctrl J all to.net run okay and then let's go back into Postman and this time we're going to be creating a post request so let me just copy our endpoint over here so I'll copy that I'll click on the plus and then let's switch this operation into post and I'll paste the URL and then this time we have to Define an actual body right because it's going to be a pause request so what you want to do is just go into this body section over here just go into body and in body you want to select Raw and in the right side over here you want to select not text but you want to select Json because we're going to be creating a Json body now let me scroll down this here and here's where we can specify the Json representation of one new game now do not type everything by hand what I'm going to do is actually just copy the representation of one of the other games the one that we retrieved in the previous lessons and copy that and I'll paste that over here now like I said we're not going to be providing the ID as part of the post request that's going to be calculated directly by the API so we're going to be removing this ID 11 over here and then we're going to be filling in for the all of the other elements right so let's go ahead and create our Minecraft game over there and then the general is going to be kids and family and then for the price it's going to be a bit cheaper let's say 19.99 and then the release date is going to be 2011 it's going to be 11 and 18 and then I don't think we need to specify a time for the release date so we're just going to remove the piece and then for the material we just keep the same thing so with that in place and I'm going to expand this a little bit let's go ahead and send a request and see what we get so click on send and as you can see and let me expand this a bit as you can see we are getting our expected 201 created status code so that means that that was a success the item was created in the API we are also getting here a brand new ID for our created game and of course we have all of the other the the rest of the payload of the game but one very interesting thing is that we do have that header created for the location of our brand new resource so if you go down into the console so the console is going to be down here the console so this is always keeping track of what's going on with your request calls so you just click on that one you're going to see this and then you're going to see at this point I have one request for our get call and then I also have one for our post call so I'm going to go ahead and expand this and if we go and look at the response headers uh down here you're going to see that we have our location header right so that's a result of our use of the created add route method right so it calculated the correct location of the resource that just got created so if we just copy that for instance you can just now copy that you can go back into your get by ID and point over there and I'm going to close the console for now so I'll paste that over here I'll click Send and now if we expand this as you can see we just got our a Minecraft game using that that endpoint that was provided by the postcode so that's a nice way to notify the client what is the location of the item that they just requested the creation for so yeah that's how you implement a post endpoint for a race API internet and in the next lesson we'll see how to define an endpoint to perform updates to our existing resources let's now see how to define a put endpoint in our res API so that we can update existing games all right so we're back into our program.cs file and we're going to scroll down all the way to the end just after the pause endpoint over there we're going to be defining one a one more endpoint of course so same idea we're going to say up that but in this case it's going to be map put right and so the the pattern here is going to be similar to the others so games but in this case for a put operation you have to specify what is going to be the ID of the resource that has to be updated so for that we're going to say just like this ID just like we did we they gave it by ID API and then for the parameter I'm going to receive in the in the second section uh we want to specify two things the first thing is going to be that very same ID this ID that's over here has to be specified as a parameter so I'll Define int ID and then the second parameter is going to be that updated game right so we're going to say game updated game all right and so just as before we'll Define our R function just like this all right and now comes the logic to a to find that game that has to be updated right so the very first section of this is going to be very very similar to the section that we did for the gate by ID endpoint so I'm going to actually copy that section over here so it's going to be this section here from get by ID so I'll just copy that because it's the same idea so scroll down here and I'll paste that right there okay so we will go ahead and run our Games Collection we're going to try to find the game and if we cannot find it we're going to say well the game is new so we're going to be returning not found and otherwise we will proceed into the actual update of the game now we're going to just to keep things very clear we're going to be renaming this game variable into existing game and this way you can do by just typing and I'll do it again just type F2 or up in on top of the variable so F2 and then you can just say the new name for the variable so existing game and that's a nice way to rename variables across your code all right so now we just have to start updating all the fields so we're going to say existing game name equals updated game dot name and then existing game dot General equals updated game dot generate existinggame dot price equals dedicated price and then existing game that release date release date and finally existinggame dot image URI is updated game dot imagery and then the the correct result to return here from a put request is usually return results dot no content right you can also return an OK result but the multilational thing to return here is is usually just no content now one thing that I want to clarify here is is this this one here right so why are we returning not found uh or could we do something else here now there there is a line of thinking here that for a put endpoint in a rest API what you really want to do is always create the resource if you cannot find it right so that would mean that in this case if you cannot find the game we just go ahead and create it right that way the put endpoint is kind of iron potent so it always returns at the same thing right so it doesn't matter if it exists or not we always end up with the resource created now the reason we're well we're not going to be doing that and instead we're just going to be returning a result not found is because in our future implementation when we introduce a database specifically as SQL Server database it is going to be the database the one that's going to be providing the IDS for the graded resources so in that case if we received an ID over here for the put endpoint and then we cannot find the element and we let SQL Server just go ahead and create the the ID for a brand new a element likely that generated ID is not going to match the ID that the user provided right so if user provides ID 123 which does not exist and then we go ahead and say hey SQL Server generate an ID SQL Server is going to generate some 456 Aid that is not going to match what the user requested and that's just not going to make any sense right so because of that a restriction from a SQL Server uh which is going to be the one generated those IDs we will go we're going to go with this other way of implementing a put a endpoint where if the game does not exist we're just going to return not found right but like I said there's that other line of thinking so just keep that in mind as we move forward with this implementation and so with this in place we should be able to go ahead and try it out so I'll open up my terminal once again so Ctrl J and I'll do net run and then I'll go back into Postman and this time I'm going to be creating a brand new request which is going to be with the put verb over there and then the actual URL is going to be like I said very similar to the one for the get by ID so I'm going to be copying it from our second tab 4K by ID I'll paste that over here and now let's make sure we we use a first again that actually exist right so if we go back into the get by ID I I think that we can go back into ID number two here so I'll send that let's actually go back into ID number one uh yeah ID number one is the street fighter 2. so let's work with this one here so for the port we're going to be using ID number one and then you have to go into the body once again select row select text and select Json we want to do a Json input over here and then let's go ahead and just paste the same pretty much the same value as in the get by ID tab we'll paste that over here and we're going to make a few changes over here first we're not going to be providing the idea as part of the body because that's coming as part of the URL to remove that and then for the name it's not going to be Street Fighter 2 let's say this is going to be a strict Fighter 2 turbo and then let's say that the price well it is on sale so it's going to be just 9.99 and then release date is going to stay the same but we're going to be removing the the time portion of it and then the rest stays just the same okay so let's go ahead and click on send and as we can see we are getting the expected two or four no content result right there so which means that this was a success and if we go back into our get by ID endpoint and we request this element once again click send you can see that now we're getting Street Fighter to Turbo right there and the price has also changed so the update was successful and then just to make sure that it implementation the implementation is correct let's go back into put and let's try to update an element that does not exist so again let's say number four does not exist I'm going to go ahead and click on send and then as expected we are getting a 404 not found because the element does not exist in the API so now that we have our endpoint for updating games let's go ahead and Implement our final endpoint which is one that is going to allow us to delete games from the API let's now go ahead and Implement our last endpoint for this API which is going to be the delete endpoint right so here we're back in our program.cs file and let's just scroll down all the way to the end and we're going to be defining our brand new a map delete method so app.map delete and the router what you want to receive here is once again gains and then the ID of the 11 to delete so ID just like that and then as the parameter you want to receive here again that ID as an integer in ID and then we'll Define again our our own function to Define what is going to be the logic for that deletion so once again the logic here is going to be very very similar to the previous some of the previous ones so what I'm going to do is just copy the logic that we have for the put operation so I'll copy that put operation right there I'll paste that down into our delete method and all we're going to do is just remove this section over here okay and then I'm going to remove this and then what we're going to do is just say that if existing game is not null right so in this case we were able to find the game so in that case we're going to say just games dot remove and that's going to be existing game all right and let me actually rename that variable existing game should not be needed here so I'll do F2 unless you just rename this into okay so the idea is that we go ahead we try to find the game right and if we are able to find it we remove it from our list of games right so it's removed from the race API if we are not able to find it it really doesn't matter because this is a delete operation we want to do is always return the same the same result or have the same behavior regardless of if you are able to find the game or not right so it doesn't really matter if we find the game or not we always return just no content which means that it was a success right and in all cases the game should just not exist after the invocation into this delete endpoint so let's go ahead and test this endpoint so I'll do Ctrl J let's dot net run and let's go back into Postman and first I'm going to copy one of the games that we could go ahead and well let me just copy the route so we know the route so copy that and then I'm going to open up a brand new tab with which is going to be for the delete verb over here and I'll paste it right over there and let's choose just one game for deletion let's say we're going to be dealing game two okay let's see what what is game two so let's go back into the first step and let's get uh let's get the list of games once again game two is Final Fantasy 14 right so this can two should be deleted after we made the invocation so let's go back into delete and we're going to be deleting game two and yeah that should be all you need we don't need about in this case all we have to do now is just click on send okay and we are getting the expected result as you can see here we are getting a 204 no content so that means that it should have been a success so if we go back again into our list of games and hit send we can see that there is no more uh Final Fantasy 14 game all right with a D2 there's nothing there right so the game has been removed so that was a success and just verify that things are working properly we're also going to try to delete a game that does not exist right so number let's say number four and I like I said before regardless of what we what game we specify here the result should always be the same right so I'll click on send and as you can see we once again got the 204 no content right and so that game four does not exist and indirect existed really so that is the end of this model and now we have a complete rest API right it has all of the expected or traditional endpoints and it is fully functioning at least for it are in memory list for now so with this in place let's finish this model over here and let's move into the next model where we're going to be looking at a few techniques to improve the way that you organize your race API code and we're also going to be looking at a validations of the inputs that we're going to be receiving in your res API in this model you will learn a few techniques to improve the way you organize your rest API code and also to properly validate data received by the API by the end of this model you will have a solid understanding of the following how to use route groups to organize your API endpoints how to validate the API parameters and how to use extension methods to better code organization let's see how we can start organizing our code a little bit better and so here we're back in our product.cs class and one thing now you may have noticed is that we have been using the very same root a path for our endpoints over and over again right so we have a formatcat we have flash games also for the other gate we have slash games and then for post we also have slash games same thing for put same thing for delete and for all of the inputs right and so luckily there is a feature that we can use here so we don't have to specify this thing over and over again and that is called rad groups so with rock groups you can pretty much group a series of endpoints that share something something common right so that you can apply things to that to the group together as opposed to endpoint by endpoints so let's see how to use that so what I'm going to do is just go just under our app declaration I'm going to do this following so I'm going to say bar group equals app dot map group okay and in this declaration of the map group you can go ahead and declare the prefix of your endpoints right so in this case as we know the prefix is slash games so I'm just going to copy slash games over there right and that defines our ground group and now that we have defined the group we can go ahead and just use it for each of the endpoints right so now we can say instead of app that map get we can say group that map get and then instead of specifying slash games for the pattern for the endpoint what you can do is just either leave it empty because it's not needed right because it comes from the group directly or what is more common you would just put a slash like that and that will be good enough for that endpoint right and the same way that you can do that you can do the same thing for every other endpoint right so let's do this for the other market and in this case we will only specify slash ID that's all that's needed right and then coming down into our map post over here again we'll say group and then we'll and then for put again we'll do group and then just slash ID and lastly for our delete method over here we'll see again group and then slash ID and so you're going to see how this feature is actually going to become very handy moving on because we will be doing a bunch of things at the group level as opposed to the input level it's a nice way to group multiple endpoints together now let's verify very quickly that things are working just as expected so I'm going to go ahead and open my terminal I'll just do.net round here and then let's go back into Postman and let's try just a couple of requests to verify that things are working so here I am in the get all endpoint tab here so I'll just click on send and see what we get and so yeah as expected we are getting our three games just fine no issues with this and then let's go into our box endpoint over here where we're going to be creating this brand new game right so I'll go ahead and click Send and as you can see the game was created successfully without any issues so as you can see there is no change in Behavior really but now our code is uh organize it in a much a nicer way and like I said we're going to be using this map group for a few other things down the road so now we have this in place in the next lesson we'll see how to add server-side validation to our API one of the things that you should always consider when building a rest API is how you're going to perform the validation of the input parameters and why is that important well for instance here I am in the impulseman in the post request right that we created a few lessons ago and let's see what happens if I for any reason provide an empty name right so instead of writing the actual name it's just an empty string over here so let's see what happens when I go ahead and click on send so notice down here I am indeed getting a created result which is already a strange right so the item should not have been created because it didn't have a valid name and also I am getting well that empty name right there so this kind of thing should not happen and furthermore I can do also other strange things like for instance the price I mean the price should not be that like perhaps more than 100 for a game but I could go ahead and totally introduce a price of something like that right I could do that and I could hit send and now we have that huge price for our game which is it's not making much sense so we have to do something to validate those inputs before they can make their way into race API so let's see what we can do about that so let me go back into our API over here I'm not going to stop my server close my terminal and the first thing that we're going to do is just go back to Explorer and go into our game entity over here so what we're going to do is use this feature called Data annotations to annotate each of the properties that should have some sort of validation and let's start with the name because we said that the name should not allow an empty string right it should be required so for that we're going to just add one attribute here which is named required okay and this attribute requires an ordering space so I'm going to do control dot so that we can use system.componentmodel.data annotation so let's select that one right there and starting now it is not possible to introduce an empty string for the name that's going to be automatically validated and rejected if that comes in and not only that we can also make it so that the length of the string is also limited right so we can say string length and let's say that we put a value of 50 here so this means that from here on the strings for the name cannot be longer than 50 characters right so that's a way to control also the length and just like we can do that let's go ahead and do the same thing for the other a a few of the other attributes so I'm just going to copy that and for the general I'm going to go ahead and say that is also required but in this case perhaps 20 characters is good enough we should not have generous bigger than that for General now let's move on to the price now the case of the price is going to be that what we really want is to make sure that prices are not either negative and also we should not get a price more than a hundred dollars because that's that's really I would say the limit for the price of a video game and usually they don't cost more than 70 bucks perhaps but let's say in this case we're going to add the range the range data annotation and so we're going to say that it goes from 1 and to 100 okay so with that any price I comes in it has to be in that range if any other value is not going to be allowed and lastly let me scroll down a bit more we're going to do something about the perhaps the release date we'll just keep it there but for image array we're going to say that to start with it should be a valid URL right so to make sure that it is a valid URL we're going to be using the URL data annotation so it has to be a well-formed URL and also we are going to be also using the string length attribute to make sure that these URLs should not be perhaps more than 100 characters that should be good enough and with that we have introduced all of these basic data notations that I'm going to make sure that we have valid values for all of our properties now in order to use these data annotations we have to do a little bit more because just adding the notations is not going to enforce them in our endpoints so in the next lesson we'll see how to use what is known as a nougat package to import existing functionality to enforce our data annotations in this lesson you'll learn about nougat and the multiple benefits of using nougat packages in your software development workflow so what is nougat well in simple terms nougat is the Microsoft supported mechanism for sharing code in.net it is essential tool that allows developers to create share and consume useful code let's see why this is useful with a quick example here we have John who has been working in his brand new web API project the project currently produces one assembly my api.dll which contains all the code for John's API however this API is missing some essential validation logic which John could certainly go ahead and Implement from scratch but fortunately Jane who does some open source work on her spare time has a re-reading all the validation logic that John is missing and produce an assembly out of it cool validations.dll Jane talk this assembly could be useful to others so she created a nougat package which contains the assembly and then polish it to nougat.org the poly cloud service where anyone can share packages with other developers John got news about this package and decided to install it in his web API project and thanks to this he was able to quickly add all the music validation functionality as opposed to having to write it from scratch so using nougat packages brings in several benefits to other developers they allow developers to encapsulate reusable code and libraries into easily consumable packages they simplify the process of managing dependencies in a project since nougat automatically resolves and install any required dependencies developers can avoid the need to write and maintain certain functionalities from scratch is that they can leverage existing packages that have already been tested and optimized by the package authors and the community nougat has a vast ecosystem of packages available covering a wider range of programming languages Frameworks and tools finally nougat allows package authors to release multiple versions of the packages which enables developers to choose a profit version based on their product requirements in the next lesson you will install your first nougat package to enable the missing input validation in your res API like I mentioned before in order to enforce the data annotations that we added a couple of lessons ago we have to do a little bit more because just adding annotations is not going to enforce the validations in our endpoints to do that we have to use this feature called endpoint filters which is something that we could definitely write manually an input filter for this case but fortunately somebody else already wrote the logic to enforce the endpoint filter that we need here and that person created a nougat package to share that logic and if you ever want to look for a nugget package what you can do is just go into this page over here which is nougat.org right here and this is probably the biggest library of free nugget package available and there are hundreds and hundreds and hundreds and nugget packages for all sorts of purposes now the one with package that we want to use in our project right now is this one here called minimal apis that extensions right and just looking for that the the one that we are looking for right now is this very first one minimal apis that Extensions by Damien Edwards so I'm going to click on that one that's going to take us to the page that describes pretty much what this package is for and how exactly you are going to install it and use it in your project right and not only that you can also see all of the versions of the of this package available because there can be multiple versions each version bringing in either bug fixes or perhaps new features right so at the time that I'm recording this the last version is version 0.10.1 right and so in order to use a nugget package you can see we have the command line that you can we can use to import and use the nuget package so I'm just going to go ahead and copy that so I'll copy that I'll go back into my project over here and now what we can do is just do Ctrl J to open our terminal here and I'm just going to paste what I just copied from there right we're going to install in this package I'll hit enter and with that the Nugget package has been imported into our project and just to confirm that what we can do is just go back into our Explorer into gamestop.api.cs product project file and you're going to see that now we have that brand new nougat package reference set in here so on here on we can use any of the classes or our types introduce it in that nougat package now because of that what we can do is the following so let's go into program.cs over here and since we are using the endpoint groups feature what we can do is just import these validations for all of our endpoints in just in one shot so we're going to go into this line here where we Define the group and we're just going to just add a DOT at the second line here we'll say dot with parameter validation right which is a function that is offered by that nugget package that we just introduced right so just by doing this there's going to be an endpoint filter that checks for all the data notations in our entities so anytime somebody tries to post a request into our endpoints with invalid data those are going to be rejected so let's see how that works I'm going to do Ctrl J and I'm going to just run a project right there and let's go back into Postman okay over here and we're going to be trying out the same invalid requests that we tried before right which has the empty string and this it has the valid price right so I'm just going to go ahead and click on send and this time as you can see we are getting a couple of validation right so first we have a nice title here that says that one or more validation errors occurred so that's great then we also got a status code 400 which is the correct status code when we have a validation errors right and not only that we have one specific validation error for each of the errors that a that are happening in our API right now right so we have that for the name we have the name field is required right there and for the price we have that the price must be between 1 and 100. and so this is a well-formed error that was all created automatically just because we're using data annotations and the minimal apis that extensions nougat package so that's fantastic so now we can go ahead and actually fix this so let's go back and put a proper name here Minecraft and then for the price well let's put again something reasonable like 1999 for instance and then if you just click Send now this time is going to succeed as you can see now it is all good and there are no more any validation errors so yeah so that's a very simple way to add server side validation to your project and in the next lesson we're going to see how to use another feature called extension methods to further organize our code much better one thing that might be bothering you at this point is how much code we have so far in our brand.cs file so if you remember we have the code for defining our list of games our memory list of games as you can see there we have our Builder object our app object our map group and then we have the definition of all of our inputs right so they get endpoints and then we have the post endpoint put endpoint delete endpoint all of this code right and so I think this is just too much code for a file that is meant to be just the entry point of the application so because of that we are going to be refactoring all of the code here that has to do specifically with the endpoints into a brand new class that is going to be in charge of defining these endpoints and we're going to be using what we know as extension methods to make this a very easy so first thing we're going to do is just to create a brand new directory under game store.api so right click new folder and let's call this folder just endpoints and inside endpoints we're going to be defining a brand new class so new c-sharp class and let's name it games endpoints and so just like we have been doing so far let's go ahead and clean up this uh these files are converting to file scope namespace just like that and let's clean up these additional namespaces from the top now since this class is meant for essential methods and all extension methods should always be static we're going to make this class also static there's not going to be instance methods over here and now let's go ahead and Define our extension method by stating cooling static like I said allocation methods are static and then the return type is going to be route group Builder the name of the method is going to be map games endpoints and then the parameter here is going to be the type that we're going to extend right the title where we're going to add an additional method without having to modify the type itself so the type is going to be I endpoint row Builder and then the name of the parameters is going to be routes now since we do want to extend I am on Route Builder what you want to do is to specify this keyword here so that enables us to actually extend the method by adding a our brand new method now why is that we want to extend I am on the World Builder well if you go back into our product.cs class over here brand.cs and if we scroll down notice that if we go into the definition of let's say market right so mapcat I'm going to right click and do go to definition you want to notice that this method here recycle the extension method on top of I am on the right Builder right here you see it is extending I am control Builder and if we go back again into problem Cs and we also look at map group for instance I'm going to do F12 to also do a definition this one also extends IM control Builder right so pretty much what we're going to do is to do yet one more extension method and on top of that of that type to refactor all of the stuff that we're going to be doing over here right so it is the right type for us to extend right so I am a web Builder and so what I'm going to do now is just to bring in all of this code right starting with a in a product.cs file with the Declaration of group all the way to the end until the definition of our delete method right map Elite I'm just going to go ahead and copy that and I'll paste that over here there okay so this is so far our extension method and now at this point the the object that we are using to invoke all of the map methods is no longer named app but is named routes right so I'm going to use copyrights put that over here right so routes.map group and then let's also bring in the right type for game right so I'm going to select game here dual control Dot and then I'm going to select game store.api that entities right so we have that definition okay and then we're also missing of course the list of games and the definition of forget game endpoint name so let's go back to problema CS let's go all the way to the top and then let's select both the const over here and the full list of games let's select all of that over here yep so let's go ahead and copy that into get gains endpoints so let's define this just outside of methods just under the class definition I'll paste it over there over here so let's line up this a little bit better and of course since we're going to be using this gains variable inside of a static class we want to Define this variable as a static itself so it's going to be static list of game games right okay so we have our cones there we have the list of games and then we have map games endpoints right so most of the code is looking good now and the only thing missing here I think is just a return type right so we said that we're going to be returning uh route group Builder and that is because that is a type that our group object is made of right so our group object as you can see it is a route group Builder so what we want to do is just a return group in case we want to making continuous calls into group from our product CS class right so we're just going to go ahead and return group and so yeah that's pretty much the definition of our map games endpoints extension method right and so that's what we have in our class right now and what we can do now is just go back into brand.cs and we can start getting rid of stuff so now we can delete this const and the list of games I'm going to delete that okay those are deleted and then we can go ahead and remove most of the code here so I'm going to remove all of the map extension calls over here okay except for the group and then what we're going to do instead of defining the group here is just say removing this app that map games endpoints and of course we will have to import another name space here so I'm going to do control Dot and then we'll have to select using gamestop.api.inpoints like that right and then we can go ahead and clean up this because we don't need the entity's namespace anymore so now our program.cs class or file as you can see is just made of eight lines that make much more much more sense all we do is just secure the Builder declare the app Define the endpoints and we're done right and all the logic for the definition of the endpoints is actually now refactored into this class test with which only purpose is to Define and manage all of these endpoints as you can see and so yeah just let's make sure that these things are still working just fine so I'm going to do.net around here to verify that things are working properly and now let's go back into Postman and let's test a couple of those emblems right so let's go this is going to be our get all games endpoint so let's go ahead and hit send and as you can see we are still getting our piece of game just fine go to post we can go ahead and we have a body here of course yeah we have a body hit send and it is working I suspect uh all good so yeah extension measures are a very handy feature uh to as you can see or a nice call better and yeah that's going to be the end of this model and in the next lesson or in the next model we're going to introduce a few design patterns that will help us future proof our API for any future changes in this model you will improve your best API with a few popular design patterns and best practices to ensure your code is ready to adapt to Future changing requirements by the end of this model you will have a solid understanding of the following how to use the repository pattern for better data manipulation how to use a dependency injection pattern to write more maintainable code which are the different service lifetimes available in Asia net core and how to use data transfer objects to Define clear contracts between client and server in this lesson you'll learn about the repository pattern and why you should use it in your applications to understand why you may want to use a repository let's say that today we have the application logic of our service talking directly to our SQL Server database however a few months or years from now our application has become incredibly popular and the constraints of a relational database are not allowing it to scale so it's time to move to a nosql database like Cosmos DB perhaps sadly giving away things have been set up we would likely need to rewrite a good chunk of our application logic in order to talk to the new database which is not just going to take a while but also is very error prone since box in duplication logic can easily surface as it gets adapted to the new data access code instead of these we can take advantage of the repository pattern but what is repository a repository is an obstruction that encapsulates the logic for accessing and manipulating data its main purpose is to abstract away the details of the underlying data access technology from the rest of the application going back to an example we will now introduce a repository between our application logic and the database this repository is the only one that knows how to talk initially to our SQL Server database and is the only one that our application logic will interface with then if we ever get the requirement to move to another database the only thing that we would need to change is our repository but application logic stays the same so the repository pattern is important because it the copies application logic from the data layer and minimizes duplicate data's logic across our service let's now see how to apply the repository pattern into our res API before we introduce the repository pattern into our code base I'll just have to mention that there is an Associated pattern called unit of work that we will not be using here because it's mostly related to having to perform transactions across multiple entities or multiple tables in your data storage but we will not use in transactions across this course so we don't really need to go into the units of word pattern so we're going to be implementing a simple version of the repository pattern here that you'll be good enough for what we need to do so the first thing that we're going to do here is to introduce a brand new directory just under game startup API we're going to right click and say new folder and this is going to be named repositories and inside repositories we're going to be well let's right click let's do new c-sharp class and the name of this class is going to be since this is going to be kind of an in-memory repository of games let's name it King mem es Repository so let's do a little bit of cleanup here let's step over here in the name of the namespace control dot convert to file scope namespace and then also on the usings to remove only that usings so what should we bring in into this class so let's go back into our endpoints class games endpoints and so here's where we have declared so far our list of games so we're going to first thing to do is just to bring in that list of games into our repository class I'm going to select the entire definition of our games just like that okay and let's go ahead and cut it we're going to go ahead and cut this and let's put it into our in main game Repository right there and then let's go ahead and select the game word over here control Dot so that we can use kingstore.api.npt same space just like that and then this should also be lightly Avid only because it's not going to be modified anywhere else in the class so I'll do control Dot and then add a read-only modifier and then we can start defining the repository methods right so let me collapse this for a moment and let's start scrolling down here just under the definition of our games there so the first method we're going to be defining is the one to retrieve all of the games so this is going to be public and then the return type is going to be one of the most genetic type that you can return here just so that the client can easily manage the list that we're going to be returning so that type is going to be I a numberable right which basically represents a list of objects right that can be that can be read in a sequential manner the name of metal is going to be get all all right and then what should we do in this method well at this point all we have to do is just return games okay so that's going to return the entire list of games to whoever invokes this made the next method here is going to be the method to return just one game by 18. so in this case we're going to implement public game get and then the parameter is going to be that ID just like that and so what logic should we have here so if we look at games endpoints so let's go back to game same points and what we can do is just copy the logic that we have in our map get endpoint over here uh just copy not all the logic but just a logic to retreat the game you see we use a fine method to get the appropriate game so I'm going to copy that into in-mem gains endpoint and we're going to say return games that find and then whichever game is found via the ID parameter right via the land expression over there now this method might return an all right so it's a notable return so because of that we're going to qualify the game a return type with the question mark making it so that this is a also method that can return a nullable object so if we cannot find the game for any reason we're going to be returning a new value okay so let's scroll down a little bit more and now we're going to be defining the method to create a game in the repository so let's define this as public void create and game okay so we receive the game as a parameter and then we want to do is a couple of things so unless actually go back into games endpoint to see what we were doing in the post and point over here so yeah it's pretty much the same idea so we have to calculate the max number of the ID that we have so far incrementing one and then we just add the game to our list of games so let me just copy this logic over here I'm going to copy that into a repository okay so again that ID it just gets the ID plus one and then we add it to the list of games so moving on let's go into our update method so normally can void update and here we were again we're going to be receiving our a updated game right updated updated game no no this is the game with already with all of the properties updated right which is going to be done by the game's endpoints and so all we have to do now is just to set this updated game into our list of games so what we want to do now is to somehow find the index of this of the game to update in a list of games and then let's just go ahead and update that again in that index so let's do this bar index equals games dot find index and for which game well we're game dot ID equals updated game dot ID right so that's going to give us the index of the game in a list of games and then we can just go ahead and say games sub index equals updated game right so that's all we have to do for our in memory repository for the update method and lastly let's go ahead and do the implementation for our delete method so it's going to be public void delete and then all we have to receive receive here is the ID of the game hint ID and then the logic to find it is going to be very similar so let's go ahead and copy the line from update just like that next time that we don't have a deleted game here or we only have the ID so let's just say ID okay and after that what we can do is just say games dot remove at and then they found index and one last thing to do if we go back all the way to the Declaration of our class over here is to make a small change to our games list over here because this list does not need to be static anymore right now it's going to be part of our in-man game compository so it should follow the life cycle of this class itself are supposed to be a static object so we're going to be removing the static declaration here and in fact let's just add private here so declare that clearly clear that this is going to be a private variable in our class all right so no more static for games and with that let's go back into our games endpoint.cs file and see how we can start using our repository over there so let's go back over here so let's go all the way up now here and let's uh let's remove a bit of these spaces we don't need those and what we're going to do is use at the start of our map games endpoints class and sorry method we're going to be defining our repository instance right so we're going to be defining in mem games Repository repository okay and then likely we want to do control dot here to introduce gamestor.api that repositories okay and then equals new okay keep in mind that this our code base is constantly changing right so I'm going to instantiating the repository just like this for now later on we're going to learn another technique to bring in the repository in a much much more flexible and testable way and so now that we have repository in place there we can start taking advantage of it right so now for the map kit all the one the first endpoint here what we can do now is just say repository dot get all and then keep scrolling down if we go into our map get by ID over here what we can do is the following all we have to do is just say repository dot get and then we pass in the ID and since we are here one small update that we can do also here is to just refactor this this bunch of lines I think we can do this actually in just one line so we can do is just say return game is not no okay so if it is not no we say results that okay with the game right and otherwise we say results that not found right this is multiplication and with that we don't have to add all of these extra lines now let's go with our post method over here and what we can do now instead of these two lines we can just say repository dot create and we have now our game right there and after that we just return as usual then let's move on into our put method down here and here we can use a double study in a couple of places so first to find the game we can now say repository dot get with ID and then all the way to the end just before returning we have to actually update the game inside the repository so we have to say now repository dot update existing game right so that's going to update the game in our list of games so let's move on into our last method our delete method over here where once again we're going to be finding our game using repository dot get with ID and then to remove it we are going to say instead of this we're going to say repository dot delete with that ID so as you can see we have now introduced the repository into our map cam games endpoints API here extension method and the main benefit is that now we don't have the list of games living in our endpoints anymore the list of games the memories of games exactly leaving now directly in our in-mem games repository right so we have decoupled the management of the data from our endpoints themselves right that's going to be super useful moving on and so well let's just go ahead and verify that things are working properly once again.net run we'll do a very quick test here just make sure that let's go back to post plan and let's go ahead and do Ascent to get all the games yeah that's working properly right and then for a post let's go ahead and send and that's also working properly so yeah things are working just fine and in the next lesson we'll learn about another very very important design pattern known as dependency injection in this lesson you will learn about the dependency injection design pattern and the multiple benefits it brings into your applications to understand what the penis injection is let's start by looking at two classes my service and my logger my service uses the log disk method of my logger to log messages to a file anytime my service performs an important operation since my service uses some of the functionalities of my logger like the log disk method we say that my logger is a dependency of my service now in order for my service to start using my logger it creates an instance of my logger in its Constructor and after that it can start calling the logdis method at first glance it doesn't look like this presents any problems but consider what happens when the authors of my logger decide to slightly modify it so that a new my file writer object needs to be passed on its Constructor because that's where the output file is now defined the record changes look simple to implement but they reveal a few important problems my service is tightly coupled to my logger in such a way that anytime my locker changes there's a need to also change my service as it happened here when the Constructor started requiring a my file writer instance my service needs to know how to construct and configure the my logo dependency like is the case here with the my file writer object which needs to be configured with an appropriate file to send the output logs this makes it hard to test my service since unit tests won't be able to mock or stop my logger and output.log file will always be created which would slow down tests and disassuming that the tests have access to a place to write files to fortunately there's a better way to do this using what is known as dependency injection let's go back to my service and it's my logger dependency my service still uses the lock disk method but this time my logger is not explicitly constructed by my service instead my locker is passed in as a Constructor parameter my logger is injected into the my service Constructor this way my service doesn't need to know how to construct or configure the logger it just receives it and can start using it right away but if my service doesn't construct the logger who does it well acornet core provides the iservice provider which is what is known as a service container your application can register my logger and any other dependencies with iservice provider during startup which is typically done in your program.cs file then later when a new HTTP request arrives and your web app needs an instance of my service the service container will notice its dependencies and it will go ahead and resolve construct and inject those dependencies into a new instance of my service via is Constructor this enables multiple benefits for your application to start with my service won't be affected by changes to its dependencies it doesn't matter how many times the Constructor of my logger changes there is no need to change my service moreover my service won't be created instances of my logger so it doesn't need to know how to construct or configure it if your application uses minimal apis dependencies can also be injected as parameters to your minimal API endpoints finally the practice injection opens the door to using dependency inversion but what is the Benzene version the dependency version principle states that code should depend on attractions as opposed to concrete implementations let's bring again our my service class and it's my logger dependency currently my service depends directly on my logger which allows it to write logs to enable file but let's say that now we're moving to the cloud and we need to start sending logs to some sort of cloud service for this we would like my service to start using a new Cloud lower class we could modify my service to receive and use a cloud logger instance instead of my logger instance however what we can do instead is modify my service so that it depends on a new ilogger interface which provides all the required login functionality then we can have both my logger and Cloud logger implement this new interface with this we are decoupling my service from the logar dependency allowing it to use my logger Cloud logger and any future logger implementations without ever having to modify my service the only thing that the different loggers need to do is to implement the interface that my service depends on in terms of the code this is how you would now inject the logger into my service so the main benefit of using the dependency inversion principle is that dependencies can be swapped out without having to modify the class that uses them but also it is now much easier to test my service since the lower dependency can be easily mocked or stopped and finally your code is now cleaner easier to modify and easier to reuse now before we start using the pens injection inner code there is one more important concept to understand which is the service lifetime in this lesson you will learn about the different service lifetimes available in asp.net core we now know the basics of dependency injection in asplnet core we know that OnStar app your application will register the dependencies like my logger here and later when an HTTP request arrives I service provider will resolve construct and inject an instance of my logger into a new instance of your class my service in this example what is not clear is what happens when a new request arrives should I service provider create a brand new mylogger instance for the new request or should it reuse the same instance what if another service that also has dependency on my logger needs to be created in response to a new request save my local instance or new mail logar instance the answer to this lies in the service lifetime which you configure when you register my logger with I service provider there are three available service lifetimes so let's take a look at each of them let's say that my logger is a very lightweight and stainless service so it's okay to create a new instance every single time any class needs it in that case you will register my logger with the add transient method when the first HTTP request arrives the iservice provider as usual will resolve construct and inject a new instance of my logger into my service however when a new HTTP request arrives I service provider will construct and inject a brand new instance of my logger which has nothing to do with the first instance furthermore if there's any other service that participates in any of these HTTP requests and also has a dependency on my logger it will also receive a brand new instance of it so transient lifetime services are created each time they are requested from iservice provider what if my logger is a class that keeps track of some sort of state that needs to be shared across multiple classes that participate in an HTTP request in that case you will register my logger with the ads code method here when an HTTP request arrives the iservice provider will again resolve construct and inject an instance of my logger into my service but if there's any other service that participates in the same HTTP request and that also has a dependency on my logger it will receive the exact same instance of this dependency however if a new HTTP request arrives the service container will create and inject a brand new instance of my login instead totally related to the previous instance so the scope lifetime services are created once per HTTP request and reused within that request finally let's say that my logger is not cheap to instantiate and it keeps track of a state that should be shared with all classes that requested during the entire lifetime of your application then you will register my lover with the at Singleton method as usual with an HTTP request arrives the iservice provider will resolve construct and inject any instance of my logger into my service and if there is any other service that participates in that same HTTP request and that also has a dependency on my logger it will receive the exact same instance of this dependency but furthermore if a new HTTP request arrives the service container will once again provide the same instance of my logger to any of the classes that requested and it will keep doing so until the application is shut down so single to Lifetime services are created the first time they are requested and reused across application lifetime now that you understand dependency injection in asp.net core and the different service lifetimes let's get back to the code and see how we can use these Concepts to register the repository instance needed to interact with the data let's see how we can use the dependency injection design pattern in our.net res API so if you remember if you go back into endpoints games endpoints.cs and you remember that we are creating currently the instance over repository right here at the start of the map games endpoints method right so what we want to do now is to switch this so that instead of this we're going to be injecting one instance of repository into each of the endpoints that actually needed that way we're going to be avoiding the coupling that we have today between our games endpoints class and the concrete in-mem games repository instance so the first thing to do is to go back into repositories and Inman game repository however what we want to do here is to First extract the interface of this class so that later on we can inject that interface into the game's endpoints class right so that that way that class doesn't need to know really exactly which concrete instance is being created and so to accept the interface what you can do I mean you can create it manually but there's also a good way to do this automatically if you just click on the Inman gain repository type over here you can use this lipo over here and just select the option that says extract interface the very first one there go there and that's going to go ahead and generate the interface for you okay and not only that now our class is actually implementing that interface as you can see and now that we have the interface we will also rename that interface because that name is not making much sense right it should be a little bit more generic so I'm going to just tap F2 in my keyboard here so that we can do a proper refactoring of this interface so this let's just rename this one into i games compository right so it's more generic hit enter and notice that now we have the brand new name over here and also we have that brand new name as the the one that is implemented by in-mem games Repository and with that in place the next thing that we want to do is to move this interface out into its own file just for better code organization so I'm going to click on the light bulb over here and then you can select the extract interface sorry the move type 2 I can repository option over here there and by doing that as you can see the file has been moved or created over there in I gains repository right and it's out of our in main gate closet class go back into eigen repository you're going to this use the same interface but it has been moved into a new file and with that in place we are ready to start taking advantage of this new interface in our game's endpoints file so let's go back into games and points and I'm going to collapse this so that we can see a bit better and the first thing to do here is to stop declaring of course the repository like this we're not going to have that public anymore so that goes away and then what you want to do is to like I said inject the the interface into each of our endpoints and to do that all you have to do really is just go into the parameter that's defined for each of our endpoints and declare the type so you're going to say I games repository repository like that and just by doing that whenever a request comes in that matches this endpoint the service container is going to find out which is the class that implements ik repository and we're going to be doing the registration in a second uh and it's going to instantiate in memory repository and it's going to provide that instance or inject that instance right here so that the endpoint can start using it like it is doing right now and we can do the same thing with each of the other endpoints so let's go ahead and let me just just copy this and then let's enter this as the first parameter in the next endpoint they get by ID just like that and let's do the same thing for the other endpoint so let's go to my post we put it over here and by the way the order it doesn't matter the order of parameters you can do it in any order I'll just prefer to do this as a first parameter for now so let's go for map put and then finally let's go for map delete and so yeah with that there's no more coupling between games endpoints and our repository uh repository class everything has been done via dependence injection so notice that games endpoints now it doesn't really know which a specific type is being used as a repository it only knows that there is an interface and it will work with that interface right so somebody else have to figure out what is the actual compute instance so that's what we have to do now so now we have to do the actual registration of the concrete instances going to map to eigen's repository so let's go back into our Explorer and into program.cs let's collaps this and in order to register your instance of the repository what you want to do is take advantage of your Builder object right so what you can do is just say Builder that services and services here is the entire services collection that of the services that have been registered into all Builder instance right so this is the collection where you can add your services into so to add a service what you have to do is just do Dot and then you're going to find a bunch of methods here to represent the different ways that you can register the service so you can do for instance a transient right you wanted to do a transient service or you could do a scoped for the scope service or you can do add Singleton also now the type of registration that we want to do here is at Singleton but before we do that let's actually take a look at adscoped and let's see what would happen if we use it as code as opposed to a Singleton so let's do adscoped and what you want to do now is just to switch into uh exactly to declare the interface first so in this type parameter let's do I games Repository all right and to use that we'll have to step into there and do control dot so that we can use gamestop.api that repository is this very first one over here okay so we're using that namespace now and then you specify the concrete type that you want to get activated whenever somebody asks for that interface so in that case in our case it's going to be in mem gains repository so with that we have registered our service with the service container and now let's see how this works in action right let's see what happens so let's do Ctrl J I'm going to do.net run and now let's go back into Postman over here and we're going to try our first request which is the one that gets all the games right so I'm going to go ahead and click on send and as expected this is working fine right so we are getting our three initial set of games from the in-memory repository and now let's go ahead and create a brand new game in our post request over here which is going to be our Minecraft game right just like we did before I'll click on send and our Minecraft game has been created however let's see what happens if we now retrieve that full list of games right so expectation is that it should have our Minecraft game over there so let's go back here and let's go ahead and click on send once again and notice this there is no more any I mean the Minecraft game is just not showing up here there is no Minecraft game we only have uh one two and three the three initial games right no matter how many times we create uh the Minecraft games or click on send and it was a success right it says here that it didn't got created but you go back into get all click on send and the game is just not there so what is happening there well if you go back into into our API the reason why this is happening is because we are using the scoped service lifetime this means that anytime we receive a new request in any of our endpoints a brand new instance of Inman githubs. is going to be created right so in games endpoints over here when initial request comes for for bucket then we get one instance of repository over here and then whenever we do the post call right we had another instance a completely different instance and furthermore when we do get once again we get another instance of repository over here and let's see if we can see this more uh more explicitly by using breakpoint so let's go back to in main case repository and I'm going to put a breakpoint over here right where is which is where we are pretty much creating our against list so this time I'm going to do F5 okay to start debugging and so I'll go back to postman and I'm going to do the initial send over here I notice we have our breakpoint over here right the game's in test is going to be created in members repository so we hit play and so that retrieves the list of games and now we go back into post and we're going to go ahead and create a new game right so click on send and notice that we're cool we're back in BS code and once again the list is going to be recreated because this is a new instance because this is a new request because we are using the iscope service Lifetime right so a new instance gets created and of course that's not going to have a our brand new game and in fact if we go back to get all we click on send and then once again a brand new instance is getting created and so that is that is what happened here's us that's what this is not working and so because of this what we want to do is just go back to vs code I'm going to stop this close that and then let's go back to program.cs what we want to do now just while we're using the inmate repository is to switch from adscope to add Singleton so that's going to make sure that we only get one instance of the repository for the entire lifetime of the application right this is likely not what you want to do when you start moving into database access but for now so that we can actually play nicely with this API we want to stick to in-mem and put Singleton but later on we can switch to something else right and just for our curiosity's sake let's see what happens now that we have a Singleton right so let's do F5 now all right let's go back to postman and then once again let's retrieve the full list of games click Send and as expected we hit the breakpoint over here where we are declaring the games array or the game list click play Let's go back to postman and here we have the full list of games and then let's go back to post and this time let's go ahead once again and create a brand new game click Send and notice that no breakpoint got hit right so there's no breakpoint go back to vs code the break one has nothing hit right it's not there and then if you go back to get get all games click Send again there's no breakpoint because the instance is being reused right there's no need to create it again and now we do have our fourth game right there so only one instance is created because it is a Singleton and so one more thing to consider here is the following so if you just stop this for now uh is the fact that since in program we are using a Singleton now and since this is just one instance for the entire API you might run into concurrency issues if we if you decided to just keep moving forward with the in-mem approach all the way to a production application right because we are using that exact same array in meme game repository this array is being used for all of the methods that that we have here including the method for creation and the method for update right so if there are multiple requests coming in and for some reason multiple of these methods on the repository are being accessed at the very same time you may have concurrency issues right between the differing elements that are being updated or created in the array so because of that this is not going to be the best option this simple list here is not going to be the best option for you if you wanted to use this in a production application so you want to switch into something perhaps like a concurrent dictionary or something like that that is actually thread safe but this one here is Notre safe but it's going to be good enough for our purposes until we arrive into the new repository that is going to be based on that database and so that's it for this lesson and in the next lesson we will learn about another good practice which is the use of data transfer objects or dtos and we'll see why they are essential for exchanging data between your res API and your clients in this lesson you will learn about data transfer objects and why they are essential for exchanging data between your rest API and your clients so what is a data transfer object well a data traffic object or dto is an object that carries data between processes or applications it encapsulates data in a simple and standardized format that can be easily transmitted across different layers of an application or across different applications and in the context of a rest API a dto can be considered a contract between the client and the server since it represents a shared agreement between the client and server about how data will be transferred and used but why exactly do you want to use DDOS in your rest API to understand this let's look at a simple request to a rest API where the client is requesting the data for one of the games the API receives the request and then asks for the game data from the Repository the repository finds and Returns the data in the form of an entity and the rest API is simply forwards that exact entity back to decline in the form of a Json object it doesn't seem like there is any problem with this but consider what could happen if suddenly requirements change and we are asked to rename the price property to retail price and not only that we will also start storing a secret code next to each game which is for internal use only so you should never leave the vacant however since we are returning the entities as is we are now sending both retail price and secret code in our response to the client which will not just break the client since it was expecting price and not read the price but opens the door for the client to read and show a secret that was not meant for it because of this the rest API should never return the entities that came from the repository to clients but instead it should translate entities into dtos that conform to the agreement between client and server which in this case means we always return ID name and price to clients and nothing else so the video acts as a contract that defines expectations and requirements for how data will be exchanged between client and server and you should make sure you always honor this contract on all Communications with your clients let's now see how to start using dtos in a res API let's now see how to use data transfer objects or dtos in rdn address API now for this we will be using the record types feature of c-sharp because they allow you to create immutable classes primarily designed to hold data and these matches our dto requirements since the data that comes from them should be immutable meaning that once a dto is created its values should not be changed so what we're going to do now is go ahead into our game store.api directory on the root and let's just right click and click and create a new not C sharp file but instead it's just a standard new file and this is going to be named DTS dot CS right so in this one file we're going to be declaring all of the details that are needed by our res API now one thing that we have to remember here is to also add the corresponding mainspace so let's go ahead and add namespace gamestore.api and let's add here videos alright so that all of our details are in that namespace now to declare these etios let's go ahead and also open our entities class right here because the details are going to reuse most of the properties of the game entity so let's go ahead and use that and let me go ahead and collapse this and let's see if I can put the game on the right side so I'll do split right so we can see better and now we can see the entity on the right side and the details on the left side precise I'll scroll a little bit to the right okay so the first video that we're going to declare is the one that's going to be used for retrieving data from the API right for the get endpoints so we will declare public record game dto and I'm going to open and close and just send it to the next line so that we can see whether all the parameters now for a record type all you have to do to declare the properties is just declare them in line inside of these a parenthesis right so in this case let's go ahead and start with our ID so let's declare int ID then we go with the name okay then we go with the general and let's keep keep scrolling down then we have our decimal price and date time release date and finally we have our string image URI okay so that is our game video and notice how it is much easier to declare than it is to declare an entire class so double will use to retrieve data and then we have to declare a couple of more videos for creation and update of our resources so let's scroll down a little bit and let's go ahead and declare our next record type so it's going to be public record create game dto okay so same idea and to create a game we don't need an ID as we know so far so we will start with our name so string name and in fact I'm going to actually copy most of the properties from game video here to save time so very similar properties but here we have to remember that we also want to account for the validation of all of those properties right so we want to bring in all of the data these data annotations that we were using in the entity we want to transfer them now into the dto so our create ndto for the name we want to say that yes it is required right and also and also let's do control dot here so that we can use an import system that component model that data annotations and then this is also string length and we said it is going to be 50 for the name next one General same idea but the string length is going to be 20. write and so scroll down and then we have folder price we know that we want to use the range data annotations so let's put that over here for the price and then we have release date we don't have anything specific and for the image URI we want to specify that it has to be a URL and it also has to have the string length for a handle so I'm just going to copy that over here next we're going to be defining the the detail the last CTO in it's going to be for updating resources right and as you're going to see this is pretty much going to be the same thing as a great game video but you always want to keep it separate because eventually it is it is fairly likely that the contract for creation and update is going to change right so right now our requirements are very simple so we're not going to notice any difference but eventually things could change so that's what I'm going to keep them separate so instead of creating detail this is going to be update game video so what we want to do now is to Define also an extension method so that we can easily map from a game entity into a dto and we're going to see how that's going to be very useful when we start using details in the endpoints and so to do that let's go back to Explorer and under the entities directory let's just right click and let's create a brand new C sharp class which we're going to name entity extensions okay entity extensions let me close this for a moment and on this one uh well let's just fix the next phase first convert to fast coupling space and also remove unnecessary usings okay remember that all extension methods will leave a will be static so they should live in a static class so let's do this static and then the method we're going to Define here is public static game dto and then we have to do a control dot to use gamestor.api.dos and then as dto and then since it is an extension method we have to Define what exactly is that we are going to be extending so we're going to say these games we're going to be extending the game entity right with a brand new method that's named as CTO and then the name of the parameter is just going to be in a game okay so with this in place we want to go ahead and do the proper mapping so let me just actually transfer details on the right side so we can see better okay so here what we want to do here is just create a brand new instance of the dto based on the values of the game so we're going to say return new game dto right and then for the parameters the first one uh is going to be the IDE so we get the ID from game.id and then we go for game dot name and then game.generate game dot price game dot release date and game that image URI so now we have a very handy extension method that we can use anytime we need to convert a game entity into a dto and so a quick note on this I know that we could be using also here Auto mapper or many other of these mapping Frameworks that are available today and that's totally fine so feel free to use that if that works best for you but in this case things are super simple right now and in general case I have found that you don't really need to introduce another framework for something as simple as doing a conversion as we're doing here it's an extension method is very straightforward it's very easy to reason about but easy to create and so this is the preferred approach that I have these days as opposed to using any other mapping framework but it's just a personal preference of course so now let's see how we can use the details in our endpoints so let's go ahead and open up our Explorer and let's go into endpoints games endpoints over here all right and perhaps I'm going to just move everything into our main tab now okay and we're going to be focusing on games endpoints so what we're going to do now is let's start using them right so for the first endpoint the one that gets all day all day games let's do this so let's send this repository kit all to the next line what we're going to do is that after we get all of the games the the entities we're going to be using link with the select operator here so that we transform each game into game dot as dto okay that means that for each of the games that come from get all we're going to transform the entity into the corresponding dto object right so that way we're not returning entities anymore back to the client but only details same idea for mapcat by ID instead of returning the game over here we're going to say game dot as video now let's keep going down into our post method here and the thing here is that now we have to look into the parameters we're receiving so now we don't want to receive the game entity anymore we want to receive the corresponding dto so let's rename this into create game dto and let's just name it game dto right and for this we have to do control dot so we can start using game store.api.dtos right to start using that and now we have to figure out how to actually create the entity because now we don't have the entity we cannot just send it over directly to repository we have to create it on the Fly so let's open up one more line here and we're going to do the same thing the the following thing so game game equals new and here we can go ahead and Define all of the properties for our entity so we'll say that name equals gamedto.name and then genre gamedito.genre and we'll just keep going with this of course until we complete all of the properties okay in detail that price state release date and finally image URI equals video image URI and with that in place the rest should be the same so now we have we are creating the entity directly inside the endpoint and we send that a new entity inside our repository and we return the generated ID so let's see what we need to do now for the put endpoint over here so just like with the other endpoint we are not receiving the game directly here we have to receive the update game video okay and perhaps will rename we will name updated game into updated game video let me do F2 here so updated game video okay and here let's see so we are retrieving the existing game from the repository as an entity and then all we have to do is really use the same logic so existing game name the Enterprise release your right we just take the values from the dto as expected and then we just send back that existing game into the update API or repository so that it can get updated and then for our last endpoint in terms of that we don't have to do anything special here because there's no detail involved right so there's not nothing other than the ID to be received here and there's nothing to be returned so we are pretty much done there and so with this in place we can go ahead and test this out and see if it keeps working so again the behavior should be exactly the same at this point because we we have no difference between the edits and details so far but this could change in the future of course so I'll do Ctrl J and then I'm going to go into my terminal over here I'll do.net run and then I'll go into Postman and I'll try out my get all endpoint here I'll click on send and as expected we are getting the values just like before same idea but of course now the properties are all coming from the dto the game video and if we try out our post endpoints so over here where we have our body of course for the Minecraft game we'll click on send and we can verify that yeah it was created successfully uh we can see that it now shows up in our get list of games right there and we could even verify that the validations are working properly so let me just clean up the name of Minecraft over there see what happens if I try to do ascent and as expected we are getting a bad request because the name field is required so yeah everything is working as expected Now using our details so that's the end of this model and in the next model we will start looking at how to use something very important which is the net configuration system two things like for instance accessing our SQL Server in this model you will stand up a SQL Server instance interbox and you will learn how to connect your rest API to it via the.net configuration system by the end of this model you will have a solid understanding of the following how to send up a SQL Server instance using Docker how to use the.net configuration system to read application settings in a web API and how to use the.net secret manager to securely store application secrets in this lesson you will get a quick introduction to Docker and you will learn how to use it to stand up infrastructure Services nearby address API like SQL Server so what is Docker Docker is a platform that provides the ability to package and run an application in a Loosely isolated environment called a container here's how it works here's a web API which as we know needs a database to store and query for games the piece of software that knows how to stand up and operate these database in our case is SQL Server that piece of software along with only software requisites has already been packaged in what we call a Docker image and this image is publicly available in a place called dockerhub we want to download and run this image in our box and to do that we use the docker engine which comes with Docker desktop one of the pieces you installed at the start of this course all Docker images are guaranteed to run anywhere the docker engine is available to download this image toolbox we use the docker pull command and to run it we use the docker run command once the image is run or executed it becomes what is known as a Docker container a SQL Server container in this case this is a fully working SQL Server ready to respond to the request of our web API the web API will create a database via the SQL Server Docker container and it will start interacting with it via Entity framework core which we'll cover soon notice that even when this container manages the game's database the database itself does not live inside the container but outside of it to ensure it is not deleted once a container is destroyed let's now go back to our development environment and stand up our SQL Server Docker container in this course I'll be using Docker to host the local SQL Server instance that my recipe I will use to connect to but in your case if you already have a running SQL Server instance that's either installing your box or that is available somewhere else in your network feel free to use that and just skip this lesson and move to the next one where we'll learn how to connect to that SQL Server distance for now here I'm going to show you how to stand up SQL server using docker so here I am in the docker hot page which you can get into by going to hotthedocker.com and here is where you're going to find hundreds and hundreds and hundreds of public available Docker images for many pieces of software one of them is SQL server and here what we want to do now is to find that SQL Server image to see how exactly we're going to be using it so to do that I'm just going to go into my search box over here and I'm going to type Microsoft Ms SQL server and L just hit enter and usually it should be the very first entry here so notice that this is Microsoft SQL Server ubuntu-based images and this is by Microsoft so there are going to be a few other ones but this is the one that I'm that I'm interested in okay so this is the one officially Polished by Microsoft so I'll click on the on that one and this page is going to show us a bunch of information about this image including how exactly where we're going to be pulling it down into our box and running it right and so let's scroll down a bit and as you can see here we have kind of a command line example of how you can go ahead and run the image in your box so what I like to do is to use this as a starting point for the actual command line that we're going to be running in our box to execute the docker image so now let's go back into vs code over here and what we're going to do is to actually create a readme file for our repository here for our rest API so that we can write down those commands to execute the SQL Server Docker image just so that we keep them handy in case that we want to restart the docker container later on so just at the root of gamestore.api I'm going to right click and I'll say new file and this file is just going to be with me dot MD okay so let's just put some title here so it's going to be the game store API and now let's go ahead and open up a section in this readme file to declare those commands for running the docker image so I'm going to do a subtitle here is starting SQL Server okay and I'll be running mostly these in Powershell so that's why I'm going to just put this as a Powershell section Powershell you could do the same thing in other common lines and here's we're going to go ahead and bring in that a command so going back into the page I'm just going to go ahead and copy this so I'll select this entire section here copy okay and we'll paste that let me collapse this for a moment so we can see better now we're going to be a changing this command line a little bit so that it works much better for us so what does this mean actually so here we're using the docker run Command right which means go ahead and run the image right which by the way is going to first pull down the image into your box and then it's going to go ahead and run it right so it will do those two things and then what he's doing is finding a set of environment variables right for things like accept Eula right what you want to say just yes there's no need for prompts for us so that's the first environment variable which is specified with Dash e and then there's another Dash e for the password that you're going to be using for the sa user now for the password I would not like to have our password just hardcoded here at all because it's not really a good security practice to introduce passwords in our code base at all right so that's a big No-No once again so what I want to do is instead of this let's Define a variable here that I'm going to just name as a password all right and I'm going to say this equals and here is where we're going to be placing that password I'm just going to say for now is a password here okay and later on when we put this into the command line that is where we're going to be defining that variable and that's the variable that we're going to be using so here in MSS SQL sa password we're going to replace this with as a password next parameter with Dash B is the port so this is the port that we will expose in our host machine the actual box will be working so that we can talk to the SQL Server instance that is running inside the container right you cannot just talk to it just like that you need to open kind of a window so that you can actually start talking to the container that's running inside so by default that container is going to be running inside using Port 1433 so we will expose on the outside so in our host machine we will expose Port 1433 so that we can talk to that Port it doesn't have to be the same port you could use any other port on the outside here but by convention you have to get in simple we'll just use that that's import the next parameter here Dash D is used to run in detached mode that means that once we run the image we will not just keep looking at the logs of that image as they come out it will just return to our command line uh using we'll just see a little a quid string and then our our terminal is going to be free to use right so and that's usually what you want to do you don't want to be looking at all the electron SQL Server all the time and then lastly what you see here is just the name of the repository and attack of the image that we're using which as you can see is going to be a micro SQL server and we will be using version 2022 and the latest version of 2022. now there are a couple of other things that we want to do in this command line and the first one is to Define what is known as a volume a data volume we want to do this to make sure that the data the data files for the SQL Server database that we're going to be creating are stored outside of the docker container and not inside that's important because otherwise when you stop or destroy that Docker container those data files will be gone with the destroy container and you usually don't want that you want that data to persist between instances of the docker container right so for that what it is just you create a volume and you say where you want to start your volume a store the volume inside your host machine so for that we're going to do is just let's say just after our Dash p for the port we'll say Dash V right and we will just give it a some random name to our SQL Server volume let's just name it SQL SQL volume and then we'll do colon and after column we will point to the location inside the docker image or the container where SQL Server by default stores those data files and that location at least in for the SQL server Linux image is going to be under VAR opt slash Ms SQL okay perhaps I'll put this in the next line for a few moments so you can see it better so this is how it should read so the data files are going to be stored in SQL volume which is a logical name for the space in your host machine where those files will live an evil map to the internal VAR opt mssql location inside the docker container and I'll just do Ctrl C so that it yeah it is a complete line the next thing I'm going to do is to specify just after Dash D I'll add a couple of other arguments actually just one more argument which is dash dash RM so this stands for remove that means that anytime our Docker container is stopped it will be automatically removed now this is optional but if you don't do this anytime you stop the container either because you stop it manually or because you restart the machine it's going to be a little bit more Troublesome to restart a container because it just stays there in a stopped state right so I find that it's better to just go ahead and remove it and the next time you need it you just restart it with the same command line that we are running right now and lastly let's add one more argument for the name so otherwise you will get some random name for your container so you usually want to have some meaningful name so it's easy to identify so the name is just going to be Ms SQL and so with that we're pretty much ready to stand up oursql server Docker container so what I'm going to do is just open my terminal and the first thing that I'd like to do is to double check make sure that Docker is actually running in my box for that I'm just going to do Docker dash dash version and as you can see we are getting a version back and then just to double check I'll do Docker PS which is usually the command that you use to list all of the docker containers that are running in your box so at this point both commands are replied successfully and so this means that Docker is running properly remember that Docker will not usually how to start when you start your your machine at least not on windows so make sure that Docker desktop is running in your box and go ahead and start it right now if it is not running currently in your box so with that verified what we can do now is just to well first first thing is going to be to set up our sa password so I'll just paste it here and I'm just going to come up with some random password so I'll do this one right so I'll hit enter and now we have our essay password variable notice that this is the way that you define a variable in Powershell if you're using something else that's not Powershell you may need to do this in a slightly different way and so now just copy this other line I'll paste it over here and that's going to be using that password and I'll hit enter okay and so as you can see uh the the docker CLI is not able to find the image in my box so what it's doing right now it is downloading all of the layers that compose that Docker image from Docker Hub into my box and after it downloads all of them it is going to go ahead and run the image in the box and we can verify this by doing the following you can now do again Docker PS and you're going to see that now we have our SQL Server Docker image running and you can even see the name W specify for that okay image over here so this is our Docker image it is SQL Server is up and running in the Box now the next time that you run your Docker image is actually going to be much faster because it has already been downloaded for you so for instance if I now do Docker stock Ms SQL right so that stops the docker image and actually removes it from my box and then if I do the same command again to run the docker image notice that it is done right it is done because all the layers are already in your box it is cache so it is much faster right so that's one of the great benefits of using Docker so now we should have a SQL Server running in the box so what we likely want to do now is to just connect to it and verify that exactly up and a live inner box so for that what I'm going to do is using the SQL Server extension for vs code which you can use to easily connect with MBS code to SQL Server so I will go ahead and open my command palette via Ctrl shift p right now and I'm going to toggle my activity bar which so far I've been just hiding so I'll click on view toggle activity bar visibility and then I'm going to go into my extensions view over there I'll just click on that one and here I'm going to be looking for SQL Server so it should be the very first one here each is the one created by Microsoft so this extension over here okay I'll collapses this is the one you want to install and so yeah I'll just go ahead and click on install that's that should take just a few seconds all right so it is ready and so notice that hey we now have a brand new icon on the left side over here and that's how you can access all the SQL Server tooling okay so I'm going to click on that one okay and that's going to initialize extension for us right now just take a second and so yes a little bit of a warning here and we're not going to look too much into that one so I'll just close that and then I'll close this and then perhaps let's also close this and that and the terminal so now we can do is to add a connection to our SQL Server so for that you can just click on this button here that says add connection and for the host name since since the SQL Server instance is running in a local machine in a local host uh inside Docker you can just specify here localhost all right again if this would be another instance that you have running in your box or in a network you will specify that host over here so I'll hit enter and then we are prompted to introduce the database name but we don't have database right now so we will just hit enter to move on to the next step and then authentication type we want to use SQL login right now and the username is going to be our sa user hit enter and for the password we will use that same password that we specified in the command line a moment ago right so I'll just type it here enter to go to save the password yes why not and then this is an optional setting do you want to specify a display name I don't really care so I'll just hit enter okay now here's a warning here about a SQL server and encryption and the thing is that by default encryption will enable two connections to SQL server but the thing is that we have not set up a proper certificate right a fully flash certificate for our SQL Server instance and that is fine because this is a local instance SQL Server right so it doesn't really matter too much and we can let SQL Server use a self-signed certificate to run our SQL Server databases right and so in order to do that to use SSI certificate what you can do is just enable the trust server certificate setting that's probably not to do this here so that SQL Server is Happy by using that self-signing certificate right I will not complain about that okay so this is fine for the local development environment it will not be good for a production environment but we'll talk about Production Way later in the course so let's go ahead and click on enable trust server certificate click on that and uncycle server a connection has been created as you can see on the left side so now if we just expand this a little bit databases we're going to see that we do have our system databases up and running right there and so this means that we have successfully provisioned our SQL Server so that's it for this lesson and in the next lesson we'll learn how to connect to our SQL Server instance using the.net configuration system at this point we need to figure out a way to connect our.net race API to SQL server and as you may know the way that you do that is by defining a connection string and the connection string includes all of the parameters needed to connect to a database now we could go ahead and Define the connection string directly in param CS here we can just Define it here however that's usually not a good idea because the connection parameters are usually going to change across different environments right like from your box into a test environment or in the product environment those parameters are going to change and so that's going to mean that you're going to be doing a bunch of things in your code here to accommodate for different environments right and that's not really a good idea the best thing that you can do in this case is actually to use the.net configuration system and there are multiple ways to use a configuration system in.net but one of the basic ways to do that is by using this files Here app settings.json and app settings that development that Json which is the developer version of the same file right and like I mentioned before this is the file where you can define a series of configuration settings with different values that you can later on read from your code files and later when you move to a different environment you can find other ways to provide those same configuration values into your code without having to change your code now to define a connection string using appsize.json actually a well-known section that you can use here that ties very well to the conversion system apis that we're going to see in a second so in this case what I'm going to do is use the final section here that's going to rename connection strings and notice that exactly over here as per intellisense so I'm going to click on that one and it has to be named connection strings right so that we can use it the way that we're going to be using it in a moment so make sure that you name it exactly like this and here what you want to do is to Define two things the first thing is going to be the name of your connection string right and you could use any name here but since this is going to be for the database context that we're going to be defining later on with Entity framework and this is for the game store application here we're just going to name this game store context and then on the right side we're going to be defining the actual connection string so let me just collapse this and then how do you find this connection string well the first thing I want to Define here is the server name so in my case the server is going to be just localhost just make sure to use your actual server here depending on what SQL Server instance you're using and then the database is going to be named game store right because that's our what our application is all about and we don't have that database just yet but that's going to be the native we're going to be using and then the user ID is going to be sa the standard system administrator of SQL server and then the password is going to be well I'm not going to be typing it here so I'm just going to leave a placeholder for now password goes here and I'm doing this because I'm going to show you another technique in the next set of lessons where you're not going to be needing to worry about this password anymore so for now let's just do that and then lastly you want to specify one more parameter that is that is called trust server certificate equals true and you want to identify this parameter because of what I mentioned in the previous lesson which is the fact that a SQL Server will be using encryption it has been enabled for encryption but use encryption you have to use a certificate and we don't have a properly prepared or fully production rate certificate ready for us at this point because we're just running a SQL Server as a local thing right for local development environment so in this case we're going to be we're going to let SQL Server use the self-signed server certificate that it comes with right and it will not complain about it because we're going to be saying trust server certificate equals true right so that makes SQL Server happy it will all work but certainly this is not what you want to do in a production environment and we will see layering the course how we use a different connection string for approduction based database so that's how you define your connection string and I'll just scroll down a moment so you can see it better this is how it looks like all right so that's your connection string and then well how do we read this connection string so let's go back into Explorer and into program.cs and collapses to read the connection string all you have to do and I'm just going to go here and you can go ahead and use the Builder object so Builder that and there there's going to be a configuration property here so the configuration property you can use to read all of the configuration information that has been provided by the configuration system in this case by upsell is the Json so here what you can do is say get connection string and just reiterate in order for this method to work for you you have to make sure that you use it connection strings over here right double make sure that get connection installing can find the connection string and then you want to specify the actual name of the connection strings so for that we're going to be using Game Store context so I'm just going to copy that game store contact is the name of our connection string and now we have a way to read the connection string now of course we want to set that into some into some variable so that we can see what we actually read so I'm going to say VAR con string equals to the result of that and I'm going to go ahead and place a breakpoint right here in line there and so so we can see what is the value of construct and so now I'm just going to go ahead and hit F5 to start debugging my application and we should hit that breakpoint right away when application starts so let's see it is starting now and as you can see we hit the breakpoint and as you can see if I just hover over the constraint variable over here you're going to see the full value of the connection string right here in the pop-up so we were able to read the configuration from app settings to Json and that way our code our c-sharp code is not really aware of what exact value we're using it just comes from configuration that's going to be super super useful as we move on with our application so let's just stop this for now okay and uh what we want to do now is to learn actually another technique to read configuration because like I said we don't want to be specifying our password right here in upside.json that's kind of a bad practice so let's move on to the next lesson where we're going to learn about the.net secret manager which is a much better much better option to store secrets that you can use in your application locally in this lesson you will learn about the net configuration system and how to use.net secret manager to start your application Secrets during local development let's talk about Secrets management as you know at this point we have a fully functional web API for a game store and we also have the SQL Server database that will store our games catalog now somehow we need to get our web API to talk to the database which of course will involve the use of a connection string with all the relevant details we have seen that we can use the app settings.json file to store this connection string however doing this is not a good idea because it will involve storing user credentials in this file and this presents serious security concerns for instance imagine what would happen if you have entered the site to push your source code including this file to a remote code repository if that repository gets compromised or if someone else with access to the repo pulls your code into his or her box and that box gets compromised your connection string might suddenly land in the hands of unauthorized people which now will have full access to your database and if that happens to be your production database you can be in serious trouble that is why you should never store any sort of credentials or secrets in your app says.json file so if you can't use this file where can you store the connection string well you got to realize that the app settings.json file is what is known as a configuration source and just like that one there are several other configuration sources supported internet applications like command line arguments environment variables and even cloud-based configuration sources like Azure keyboard and the great thing about this is that the aspl net core runtime takes care of combining information from all available computation sources into a single configuration object that implements the eye configuration interface this configuration object is easily accessible to your web API in such a way that it doesn't really need to know where the configuration data actually comes from Furthermore your download SDK installation includes what is known as the secret manager which acts as one more configuration source that is specifically designed to store secrets that developers can use in their local boxes for local development and testing you can add your connection string to secret manager and it will take care of storing this and any other secrets in your local machines user profile directory which lives outside of your code repository that way you will never risk leaking your secrets as part of your code changes and your web API will still be able to read them as any other piece of configuration let's now see how to use the secret manager to store our SQL server connection string let's see how to store and read our connection string from the.net Secret manager so the first thing that you want to do in order to use secret manager is to initialize it so what you want to do is just go to your terminal over here and then all you have to do is just use this command line here.net user secrets in it and then by the way I'm in the game store.api directory right the directory of your project file so just hit enter there and that's going to go ahead and set the secrets a user Secrets ID for your project so if you go now into gamestore.api you're going to see that this secret ID that is right now in the terminal is now also defined here as a user Secrets ID in your project file so that's the first step so that sets kind of an entry into the secret manager for your secrets for this specific project and with that in place what we have to do is to go ahead and set the secret into the secret menu and for that we want to use the command line but before doing that let's go back into our written file and we're going to also just like we did with SQL Server we're going to be adding the the command line that we want to use to well actually set a secret in secret menu just in case that you want to set it later on okay so let's go ahead and collapses and I'm going to open another section here that's going to be setting the connection string to secret manager right and again this is a publisher section just like we did before we're going to be capturing the password into a variable so I'm going to repeat that line that we had in the SQL Server section over here okay so that's going to be your essay password and now comes the command line to actually set the secret and let me scroll down a bit here and so we're going to do is use this.net user secrets set then we open our double quotes and then what is the actual setting that or secret that we want to set well for this we want to remember what we said before in Explorer in app settings.json remember that we have said that the connection string lives under connection strings and then game store context so we want to do is follow that same hierarchy of settings as we set up our secret that way the net configuration system is going to know how to properly grab that setting and use it exactly how we've been using it so far in the code our hierarchy starts with connection strings right so I'm going to copy connection strings and put it over here as a first piece of the name of the secret and then I'll do colon and then I'll go to the next level which is game store context right so I copy against our context over here and I place it right there okay and then I'll close double double quotes right and that is going to define the name of the secret itself now we need to go for the value okay so double quotes and so the value well the value is going to be really the connection is three that we've been using so far right so I'm going to go to absence.json and I'll copy the entire thing right so I'll copy everything here copy over here paste there we go there now we have our connection string but of course now we don't want to be using this placeholder instead of that we want to do SA password and now that we did that we can go ahead and run these commands in the terminal so I'm just going to go ahead and open my terminal over here and I'm going to scroll down a little bit over there right there and so first thing Define the actual essay password and remember that this is again this is the essay password that we defined it before for SQL server for cc administrator user so make sure you type the query password here so I'm going to type mine all right and now that we have that in place we can go ahead and run our Command to set the secret so copy that paste that here hit enter and the secret has been successfully saved into the Secret store and so to confirm that the secret is actually there what you can do is the following so you can do a.net user secrets list and this should provide you the full list of all of the secrets that you have so far configured for your current project and so now that that is in place let's go back into app science.json and well guess what we can go ahead and fully remove this connection string section it is no longer needed right which is great and then if you go back into our pearl.cs file over here we don't really need to do make any changes because now the connection string with the exact same key is should be coming from the secret manager and into our connect stream variable over here so I'll keep that breakpoint and I'm going to do F5 to go ahead and do a debugging session and let's confirm that we can actually read the value from Secret manager so the organization starts and now let's explore our connect stream variable over here and as you can see we are now getting our full connection string right there now coming from the secret manager so it is stored securely outside of the code Repository and we are able to use it right away this is how I didn't have to make any changes here and this is the key about the internet configuration system because later on we will be changing the place where we're going to be reading this this connection string from and so the fact that it is already configured this way is going to save us so much time in the future alright so I'll just stop this and so that's going to be the end of this model and in the next model we will learn about Entity framework core which is going to be the RN framework that we're going to be using to actually start interacting with our SQL Server database in this model you will use the Entity framework core orm framework to start querying and modifying your database records using only c-sharp by the end of this model you will have a solid understanding of the following what is Entity framework core how to implement an Entity framework DB context how to generate and apply database migrations how to implement an Entity framework repository and how to use the asynchronous programming model to get improved performance in this lesson you will learn about the object relational mapping technique and how Entity framework core can help you write code that interacts with your database without having to learn a new language at this point we want to add database support to a web API so that all our data is persisted beyond the lifetime of the application so whenever a request to create a game is received in a web API we want to create that game in the database and when the client requests a list of games we want to query that list from the database however there's a problem the database does not speak the same language as your asp.net core web API your web API is coded in c-sharp but as equal server database only understands the transact SQL language that means that to fulfill the request through three games your c-sharp code needs to translate the web API request into a carefully crafted physical query and then send that query to SQL Server SQL Server executes a query and then your c-sharp code has to read back and result in rows and translate them into a corresponding web API response this presents a few problems as a C sharp developer you now need to learn a completely new language this equal in order to craft the required queries and you need to learn it well to ensure that you get good performance out of it you need to write a lot of additional data access code whose only purpose is to translate things from c-sharp to T SQL and vice versa and of course deal with inspected errors talking about errors this approach is error prone since it's very easy to make mistakes when mapping things from one side to the other and you need to manually keep your c-sharp models in sync with the corresponding database tables which can be quite challenging this is where of the relational mapping techniques or orm can make a big difference but what is orm well going back to our Spotify example imagine your application has been created using an object-oriented Paradigm and therefore it includes objects to present songs artists and playlists and if you're working with a relational database server like SQL Server there's a good chance that your database will have corresponding tables for each of those objects now instead of having to write custom code to map these objects to tables each time you need to send or receive data to or from the database you can set up a map between them so that your program can keep working with objects while another component an opt-in relational mapper takes care of transforming objects to tables and vice versa so in essence of the relational mapping is a technique for converting data between unrelational database and an object-oriented program and as you can imagine it brings many benefits to application developers and fortunately HCL net core includes a great RM framework called Entity framework core so what is it in the framework core it is a lightweight extensible open source and cross-platform optic relational mapper for.net Entity framework core will sit between your web API and your SQL Server database besides mapping your dotnet objects to SQL Server tables it will translate your c-sharp data access code into transaxical statements that the database server can understand and it will also translate any resulting data from the database into objects that your web API can easily manage using Entity framework core in your dotted applications brings in multiple benefits there's no need for you to learn a new language you can perform all data access tasks using your familiar c-sharp language the actual data access code that you need to write is minimal since Entity framework takes care of most of it in fact you can use language integrated query or link to perform most of your database queries there's tooling available to keep your c-sharp models in sync with your database tables so you don't need to do this manually anymore and the framework can keep track of the changes made to your c-sharp object instances at runtime so it knows what changes to send to the database when it's time to persist the data also Entity framework core supports multiple database providers so you can use your same c-sharp models with additional relational databases if needed let's now see how to use Entity framework core to add SQL server support to our game store web API let's see how to add Entity framework core support into r.net res API and the first thing that we're going to need is a brand new nougat package that will bring in the single server provider for Entity framework into our code base so let's go ahead and open our terminal here and let's go ahead and while being in the gamestore.api directory let's dotnet add package I'm going to collapse this for a moment so we can see better the package that we want to add is Microsoft dot Entity framework core dot SQL Server so I'll hit enter and just like this package there are other packages for other providers like sqlite or postgresql but in this case we're using the one for SQL Server so that is done right and what you should see in your project file at this point is that you have this brand new product reference or package reference this one over here SQL Server and so with that in place let's go back into our Explorer and we want to do now is to define a brand new directory to enter or to specify all of the classes related to Entity framework so I'm going to actually right click in the game store.api directory new folder an output a folder named data and in this data folder we're going to be creating one class that is known as the data context or DB context so new c-sharp class and let's name this one game store context and so I'll close this and then let me arrange this by doing Ctrl dot convert the files called namespace and then control that over here to remove unnecessary usings and this class in order to for it to become a DB context it just has to inherit from the DB context class like that I'll do Ctrl Dot and we want to use Microsoft that Entity framework core enter and now our class is a property context now the context instance represents a session with the database and can be used to query and save instances of your entities also this DB context is kind of a combination of the unit of work and repository patterns and so a quick note here so you may be wondering well if the DB context can act as a repository why do we have already a repository defined for our application right so remember we already have our uh I can possibility interface and our in-mem games compository and of course we're going to have an Entity framework version of the repository later on so why do we do we do this well the thing is that we don't want to tie our games endpoints a class over here to add a specific implementation of a data access technology right so we could later on just inject gangster game store context directly here right as opposed to our eigen Repository but that would mean that our endpoints are coupled now into Entity framework directly and if later on we want to move to something else let's say we want to move to a nosql database because it is I don't know it is more performant or we need to scale really massively your application we would not be able to do that without having to make a bunch of changes all over the place in our game's endpoints but since we do have our own repository interface that we Define that we control we are not subject to that right so it doesn't matter what kind of changes we make later on into our data repositories that's never going to make a have any impact into our game's endpoint here because we're using our own interface so that's the reason why we keep all Entity framework stuff directly inside our game store contacts here and we'll see later on how we introduce our own energy framework Repository now for this game store contact Intense or class what you want to do is to define a Constructor so I'm going to do c2r and so and this is a standard stuff for Entity framework what you want to do is to Define just one parameter here that is known as DB context options and for the type argument of the contest options you want to specify your R2L gamestore context such as game store context like that and then the name of this is going to be just options okay and we will go ahead and say those options send those options into our Base Class into DB context we just send the options okay so that's going to allow this again sort context class to grab all the details on how to connect to the database including the connection string and so the next thing that we're going to need here and let's just just leave that to the side scroll down a bit is a property that defines our game's entities in the database right so for that we're going to be declaring the following property so it's going to be prop DB set and then this is going to be off type game because game is the entity that we will be managing here and then the name of this property is just going to be games and so let's head into our game declaration here I'll do control dot so we can start using gamestop.api.nt first enter there and then of course we're getting a warning here right because we have defined a property here that is not nullable but we have not defined it any default value for this property right so we have not defined a default value either in Constructor or as a default value for the property so we need to define something here and what you can use here is actually a data implementation in the property by just doing Arrow function here like a little arrow and then you will Define this as a set of game right and so that is going to Define the initial DV set instance for our games property of the context and that's what we're going to be using for querying the data of our database so with that we have our initial basic implementation of our game store context which we're going to be modifying in in a moment uh in another lesson but for now this is good enough what we want to do now is to actually register this game store context with our service container just like we did with the repository so for that let's go ahead and do a contour shift e to go to our Explorer let's go into param Cs and remember that we have already defined a how to capture that collection string so that's great so that's exactly what we're going to use to define our or to register our game store context so for that we're going to be doing the following so Builder that services okay the same collection of services that we used before for the Singleton but this time we're going to be using it to Define that at SQL Server so this article server extension method here is is one that is going to allow us to register the game store context with the connection string for SQL Server right so I'm going to specify as a type argument here game store context all right and for that we'll have to do control Dot and we want to use gamestop.api.data this one over here and then we will pass in the con string as the one parameter over there now keep in mind that this article server method here is nothing more than doing something that like app scoped but in this case instead of we specifying that we want to use adscoped we are letting the the creators of the Entity framework a SQL Server package to provide us with this extension method as SQL server and inside that method they will do the ads called a call and they will construct those options that we saw here you see these TV contest options right so they will construct our game store context instance with those options using the connection string that we have specified here right it's just a little bit of synthetic sugar but it's super useful because now we only have to make this one call and the rest will be configured for us and so with that we're pretty much done with this lesson and in the next lesson we will learn how to use database migrations to define the mapping between our daily context and our SQL Server tables it's time to Define our first database migration which in Entity framework core terms all it means is that we have to Define how we're going to go from one state of the database into another state of the database potentially going from nothing into having our actual game stable going from the entities that we have defined it already in rdb context and the migration is also going to Define how we can we can go back from the current state into the previous state if we ever need to now to define a migration the first thing I'm going to need is a a tool from The Entity framework team right that we're going to be using for performance diagonal migration so to do that let's go back into our terminal so I'm going to do Ctrl J here to open my terminal and the tool that you're going to need is name so well you want to do this dotnet to install that's how you install.net Tools in your box and this tool is going to be installed globally so that you can use it in any of your projects right so we're going to say Global and then the tool name is.net EF so I'll hit enter and that's going to install the tool globally into my machine so that's the first thing the second thing that you're going to need is a brand new nougat package that is going to enable Entity framework to actually escafld the migrations that we're going to need because we're not going to be creating them manually they're going to be generated by by the tool so let me clean this and what you want to do is the following .net add package and let me click left this so we can see better the name of the package is Microsoft dot Entity framework core Dot design right so I'll hit enter and that will install the package and you have to confirm you want to go into the install.api.cs proc and now you should see that you have this brand new package over here this package reference is what confirms that the package has been added into your project so with all this in place we are ready to generate our first migration so I'm going to open my terminal here and I'm going to closely clear this and to generate an initial migration what you want to do is the following dot net EF migrations add and then we want to provide some name for this migration let me not to equalize this the name for this migration and you can put any name here but this is the very first one that we're going to generate so let's just name it initial create and then you want to specify awareness that you want to generate the files right in our case what I like to do is just to generate those files inside our data directory over here on the left side and so because of that I'm going to say foreign is going to be data and inside data let's create a directory called migrations so I'll go ahead and hit enter and what this is going to do is going to go ahead and build your project and then it is going to be using your database context to Define how exactly we're going to go from nothing to an actual games database in the SQL Server now as you can see on the Explorer here we do have now our migrations folder and we do have our initial migration and we're going to take a look at this at this warning in a second I will go back to that but for now let's see what got generated so as you can see the main thing that got generated here will not go into all these files but the main one is this one here which line is going to have another a timestamp here depending on when you're running this migration but the main thing is that it is name it initial create right and if we can see here if we go down we're going to see that this is a class name initial create extends from migration right and it will have uh two methods right the first one is going to be the up method this one over here up which means that this is a method that's going to be used to go from the current state of the database into the new estate and for that new state it is saying here that it is going to go ahead and create a table whose name is going to be games and then it is going to have the following Fields it's going to have an ID field which happens to be that it's going to be a SQL Server identity meaning that it is going to be Auto incremented anytime we insert a rows into the database right which is what we want and it is also it is of type it is areas of type int and it is not going to be nullable right so it has to have a value okay and just like that we keep we can keep going with the other properties like we have the name here which is a type string right but in SQL Server it's going to translate into invert chart of 50 because we defined it that the name property can only have up to 50 characters remember that we did that in the data annotations of the entity the game entity here remember that name has this Con this constraint string LED 50. because of that in our migration he decided that inverter was going to be 50. so that is why it is important to clearly Define what's going to be the length of your entities in the properties okay so maxlan 50 and again it is global false and then same idea we generate and then with price uh in this case it decided or defaulted to a decimal of 18 comma 2 right so Precision 18 and scale 2 and of course this means that we could have up to 18 digits in this in this decimal where two of them can be part of I mean can go after the dot right so as part of the actual decimal numbers and then yeah that's going to be a new level false and then release date it translates into daytime 2 and then lastly image array is an inverter of 100 right also another false and it defines also the constraint right so it's going to be a primary key right of PK names on the ID and this is just by convention right so he decided by convention he decided that since we have an ID field that is going to be the primary key and also that's why by conventional decided that it will go I'll go ahead and how to increment that one field because it is name it ID right it's just one convention and yeah that is the a up method and then in the down method what you can see is that you're going to revert that so if you ever have to go back into the previous state the down method will kick in and it's going to go ahead and of course just go ahead and drop the table because that's that's a what's going to take us to the previous state so yeah that's going to be our initial migration uh but we did see that there is a warning here right uh what does this warning say well it says no store type 1 65 for decimal property price on edit type game this will cause values to be selected truncated and so yeah what this really means is that a for our price right so notice this here for price it automatically decided to just go with decimal 18 a comma 2 right but it doesn't really know if 18 with a scale 2 is going to be enough or it's going to be what we expect when we send our decimal values for the prices into the database so it is warning us saying hey I don't know if this is going to work for you so I'm warning you you might as well use ss5 this very clearly what exact value you want in SQL Server type you want to SQL Server right for your price so that is the one that we're seeing here and so in the next lesson we're going to see how to do the right thing so that we don't have to deal with this warning anymore we ended the previous lesson with this warning that we have on screen here that is related to the fact that we have not specified which exact precision and scale we want to use for our price column in SQL Server so in this lesson we're going to see how to use what we know as an entity type configuration to clearly tell SQL Server what precision and scale we want to use here so what we want to do now is let's just close this terminal and let's go back into our Explorer and I'm going to also close this and the migration folder and what we want to do is to create a brand new folder just under data so under data new folder and let's name this folder configurations and in our new configurations folder we're going to be creating a brand new class that we're going to be calling so let's use right click new c-sharp class the name is going to be game configuration let me collapse this for a moment and once again let's go ahead and convert to fast Colony space and remove only set usage now in order to make this gain configuration class an actual entity type configuration we have to implement one interface that is named I entity type configuration and then for that one we'll have to do control Dot and we want to use Entity framework Microsoft Entity framework core so hit enter so we use the writing space and then you have to define a type parameter here which is going to be the type of the entity that has the column or columns that you want to configure so in this case is game just game and then for that one we'll have to do control dot once again and we can use gamestop.api. entities and with that in place what we want to do now is to implement this interface and for that you can once again go into these curly braces and you can either use the light bulb or you can do control dot as I'm doing now and select the first option that says Implement interface okay so Implement interface that's going to scaffold this one method here is the only method we have to implement in order to satisfy the interface and in this method what we're going to do and let me scroll down a bit here we're going to do is choose one simple thing we're going to Define exactly what's going to be the Precision of our price column so for that what we can do is the following so we're going to say Builder dot property and in this property we're going to be defining kind of an expression so in this expression we're going to say game and then Arrow function here game dot price and for that price we're going to go into the next line and we're going to say that has Precision okay and here's where we can specify both the Precision and the scale that we actually need for our price column now in our case and like we said I mean the default is 18 with two decimal places for scale but that's way too much we know that our prices should not exceed like a hundred dollars right as per our restrictions so let's go ahead and say well Precision is going to be 5 and scale is going to be 2. meaning that we should be able to get up to a number that is a perhaps 999 and then with 99 as decimals right which is still too much but it should be good enough let's just leave a little bit of room just in case right so this should be good enough and now we have our game configuration defined we have to tell the context the DB context how to use this configuration so for that let's go to Explorer let's go to game store context over here and what we're going to do is just to overwrite a one method from the base class from the base DV context class that is going to allow us to apply our configuration so let's go down here and let's say protected override void and this is going to be on model creating okay and the parameter is going to be model builder model builder okay so we will be overriding that method and what we're going to do here is just to use one and single method to apply every single configuration that we have defined in our project that implements the right interface right remember the gain configuration implements I entity type configuration so this method we're going to be using is just going to be looking for every single class implementary interface and it's going to be applied into rdb context so model builder dot apply configurations from assembly and what assembly is going to be well it's going to be our executing assembly so assembly and then for that one we'll have to do control Dot and then we will use the very first option using system.reflection okay assembly dot get executing assembly right so that will give us the current executing assembly of the line that where we are right now which is just a single assembly for our web API and so what this is going to do like I said is that whenever the model is getting created as part of the migration the context is going to tell the migrations tooling that we have to apply that configuration that we have defined so let's now go back into our Explorer and what we're going to do is just to delete our migrations folder the migration folder that we have over here where I'm just going to go ahead and delete it because we're going to be regenerating it completely right so I'm just going to say move to recycle bin okay so it is gone and now we can go back into our uh terminal and I'll do CLS and then we can go ahead and do the same command that we did before right so if you remember.net EF migrations add initial create and the uploadir and that will go ahead and regenerate the migration for us so I'll hit enter and I'm going to go ahead and build it and then as you can see there is no more any warnings here so it's all clean right and if we look at the migration folder we have a brand new initial create over here let's collapse this and that and let's see if everything worked properly notice this over here so this one over here notice that now it is not defaulting to 18 comma 2 it is now 5 comma 2 which is the exact precision and scale that we want and it's also defined over here position and scale so now SQL Server knows exactly what type we want to use for decimal and now it does doesn't complain anymore and now that we have this ready let's move on into the next lesson where we're going to see how to actually apply this database migration into our SQL Server instance with our database migration ready it is now time to apply this migration into our SQL Server instance and doing that is actually very very straightforward so let's go back into Visual Studio code here and I'm going to go ahead and open my terminal and again I am in the directory of game store.api I'm going to do is just run the following command .net EF database update and actually going to go ahead and close this so we can see better okay so by executing this command we are going to run those those statements in the migration into our SQL Server database so I'm going to go ahead and hit enter and the break is compiled and just after that as you can see Entity framework tooling we'll go ahead and translate what has been defined in our migrations into proper SQL sermon commands so as you can see let's take a quick look over here we have our create databases statement right there that's where the database is being created so let's keep going down let's see what else is interesting here here we can see the creation of our table the well the migrations table right we're going to take a look at that migrations table in a second but this is the table that keeps track of the migration history okay we'll take a look in a moment on that one then let's keep going down and here you can see you can see that the actual migration is being applied right here right so that's our migration and of course that results in our table getting created in the Nets next login line over here right there and finally as the very last line there is a new record being inserted into our migration history which corresponds to the migration that just got executed right so that you can keep track of it and but of course if all of this is succeeded that means that we should have our table in and even our in the framework migration history table ready so let's go back into our SQL Server Explorer and for that I'm going to show up once again my activity bar right there and I'm going to go over here okay this one here is for the SQL Server Explorer and what I'm going to do now is to just go ahead and right click on databases and I'm going to refresh and as you can see now we not not just have the city databases we also have our game store database here I'm going to collapse this and under tables we're going to see that we have two tables the first table is going to be our EF migrations history as you can see right here and here's all the columns and if we right click on this one and we'll select top thousand right we're going to see on the right side it's a bit hard to see so let me see if I can close this one there it is you can see that we have our very first migration right here and with the version of Entity framework and so this is going to get populated with every single subsequent migration that you that you create so that engine framework can keep track of what's going on with your migrations in your database and the other one is going to be our games table which is here on the left side as you can see it has all the suspected columns but of course right now it doesn't have really any data because we have not inserted any data into that table just yet right we'll look into that in a future lesson now for now this works just fine but in the next lesson we're going to see how to apply migrations directly and automatically on application startup in the previous lesson I showed you how to apply migrations using the Entity framework tools but now I'd like to show you how to do this in a different way so how can we apply migrations automatically on application startup and that can be very handy to simplify your application deployment later on because you will not need to be applying over and over again each of these migrations as you make changes into your entities so let's see how we can do this let's go into our product.cs file over here I'm going to collapse this for a moment and here we're going to do the following just under or the Declaration of our app right so let's go here under line 11 over here we're going to be adding the following several lines so first we're going to be creating a scope because everything that has to do with our game store ADB context has to happen in the context of a scope so we'll do using Power Scope equals app.services Dot create scope that creates a Services scope that we can then use to start resolving services that we're going to need and the one series that we need here is our DB context so what we do now is the following bar DB context equals scope.service provider which is the one class that you can use to retrieve services from the service container from iservice provider you can use this class over here this is property and then you can do get required service and then you specify for what's for what type the type is going to be game store context okay and now that you have the instance of the delete contexter you can do the following you can just say TV context dot database dot migrate and in order to use my grade you will have to do control dot here so that you can use Microsoft entity framework.core so this my great meter here is going to go ahead and automatically apply any of the missing migrations in your database including the initial migration tool go ahead and create a database so this line over here has the same effect as using the Entity framework tools to apply the migration as we did in the previous lesson now we could leave things like this but I think that a better way to do this is to actually create an a specific class to take care of this of this code that way we don't pollute our program Class A once again so let's do the following let's go into our Explorer and into our data directory and we're going to just right click and add a new C sharp class that we're going to be naming data extensions right so here we're going to be creating a brand new extension method that can go ahead and perform the database migration so I'm going to go ahead and clean this out to compare the files called namespace and remove necessary usings and this is going to be a static class because it is for for an extension method and now let's go ahead and Define our method so the method is going to be public static void initialize DB and then the thing that we're going to be extending is I service provider okay and if the name is going to be your service provider and like I said I service provider is the one thing that represents the service container and it is from there that you can go ahead and always resolve those services that have been registered during application startup and so here we can go ahead now and introduce those lines that we created over here and so first I'm going to grab an instance of that scope and I'm going to do it in the following way so I'm going today I'm going to say using bar scope equals service provider dot create scope right create scope and yeah this this little squiggles here what they're saying is that there is even a better way to to Define this and so to Define this kind of a using context and so yeah let's go ahead and do that so I'm going to do control Dot and then we're going to go for use simple use install statement I'll click on that as you can see now that we can do this in just one line right so there's no need for curly braces that makes sense and then now we're going to go ahead and go back into program and actually copy these lines right those lines over here okay for the same effect and of course we have to do a control dot here to use microsoft.eddy framework core and with that our extension method is ready thanks to that we can now go back into prom.cs and what we can do is just say instead of all of these lines over here we can just say app dot services dot initialize DB right so now we are extending the service provider instant that is defined it over here that's the idea of extension methods so with that done let's go ahead and try out this new logic and see if we can actually run the migrations as the application starts up so to Define that this actually works what we're going to do is to go back into our SQL Server Explorer over here and let's connect into our instance over here and what we're going to do is just drop the game store database right which is fine because we don't have anything meaningful there for now and so we're going to drop it and then we're going to run application and see if the database gets recreated so I'm going to right click on localhost over here I'll do new query and to adjust the database all you have to do is just say drop database game store in this case Okay so drop database game store I'm going to click on this button over here that's going to go ahead and run the script so I'll click on that and the database should have been removed by now so I'll click close that I'll close this and if I refresh databases here the game store database is now gone right so it's not longer there and with that in place we can go back into our terminal so do Ctrl J to open my terminal and I'm just going to go ahead and dotnet dot that rod and I'm going to collapse T so we can see whether it locks so dot net run hit enter and as you can see as the application is started it went ahead and executed all of those SQL Server commands that before were executed When We Run The Entity framework tool right so all of these executed including the creation of the database it happened right there and the insertion of the of the value into the brand new EF migration history table right and after that the application actually started executing right so it looks like it worked just fine and I'm going to stop my server for now I'll just go back into the SQL Server Explorer and then I'll right click on databases refresh as you can see the game store database is back the tables are there we have the EF migration history we have the the games table everything is right there and so now that we have our database ready uh we're going to move on into the next lesson where we're going to implement a brand new repository that will be able to use our DB context to start interacting with our brand new database it's time to implement our brand new repository which is going to make use of our new game store Divi context to be able to both query and also make changes into our brand new game store database so let's go now into our repositories directory over here whereas as of right now we only have our IES repository interface and our in-mem games repository so we're going to do is to create a brand new class so let's just right click over here new C sharp class and this one we're going to be naming Entity Framework games repo Satori right because this is a repository that's going to be pretty much dedicated to work with Entity framework objects right so now let's collapse this and let's fix things a little bit first company space and we will necessary uses now as we know for this class to be an active repository it has to implement our igames repository interface so we'll go ahead and do that I games repository right there and then I'll just do control dot here and I'm going to select the first option to implement the interface so that gives us the initial code for the repository now I'm just going to order these methods a little bit so that they follow a similar pattern as we did with the other repository so I'm going to have yeah create go after our get and then we have update and at the end we're going to have delete all right delete so yeah so we have delete at the end update create get by ID and then get all and so the next thing we have to do in this repository is to Define our DB contest instance and so for that we're going to declare private read only because nobody should change this instance after construction and then game store context and for that we will have to do control Dot and then we're going to be using gingstore.api.data namespace and then the name is going to be just DB context and now what we want to do is to inject an instance of Gamestar context via our Constructor and so for that I'm just going to click here on the context and I'll do again control Dot and I'm going to select the very last option over here that says generate Constructor Entity framework against repository with game store context as a parameter so I'll click on that one and that went ahead and generated this brand new Constructor that receives the 3D context as injected depends injection and it assigns that that parameter into the local DB context variable that we have there and now that we have that it is time to start implementing all of our methods right so let's start with Geto so how do we get all of our entities using Rd context so that's very straightforward all you have to do is the following you will do return DP context dot games because that's our games collection and then you can do to least okay double go ahead and return the full list of games back into the color now one thing that we want to do here as a small optimization is to make sure that Entity framework is not trying to keep track of changes to these returned entities right because that's kind of a built-in feature of the data framework it will go ahead and do additional logic to start keeping track of any changes that the caller makes to the games entities however for the case of at all we don't really need that because all we're going to do as we know is just return those entities back into the client so there's not going to be any modifications and so we can speed up things for this query by just asking Entity framework to not do any sort of tracking right so to do that all we have to do is just say that as no tracking just like that and for that we're going to do control Dot and then using Microsoft Entity framework core just like that and with that like I said there is not going to be any sort of tracking on this list of entities and that's going to speed up the retrieval of those entities so we can send them back quicker into the client all right so let's keep going into our get by ID implementation here which is going to be the following so return maybe context that games dot find and for the find method we're going to pass in the ID and that's all it is then let's go for our create method over here and to implement create all that we have to do is to add that instance into our collection of games so what we're going to do is just delete context dot games dot add and then we're going to set our game entity right there and lastly we have to invoke the save changes method of the DB context so that the changes are actually sent back into the database so the context dot save changes okay keep in mind that this line here all it is doing is asking Entity framework to keep track of the fact that there is a new entity that is being tracked by Entity framework in the context but that line is not adding or inserting the row into SQL Server only when you invoke this line here then the changes are all sent back into the database and then let's go into our update method over here so for update is going to be a very straightforward tool so TV context dot update and then we send over the updated game and again the context dot save changes and then lastly let's go for our delete method over here and to implement a delete there are a couple of ways to perform the solution but the way that I like to do it these days is by using a nice feature which is known as batch delete this is going to allow us to perform the delete without having to first load the entity into memory just so that we can later delete with this other feature we can go ahead and delete it right away and so in order to do that what you want to do is the following the context that games that where this is going to be our selector so this is how we're going to select which entities are going to be deleted so we're going to say game where game dot ID matches the ID that we got as a parameter and once what we have selected which entities we want to delete we're going to say just dot execute delete okay like I said this is kind of a batch delete behavior and that allows you to First select which entities to delete which is just the one that has the ID that was passed in and then it goes close ahead and deletes everything that matches that criteria and so yeah that completes implementation of our brand new Entity framework repository and in the next lesson we'll see how to use our new Entity framework repository to see our application start querying and storing data in SQL server for the first time let's see how to take advantage of our brand new Entity framework repository in our.net res API so if we go back into our product.cs file over here we're going to remember that in line 7 over here is where we currently register the in-mem case repository as the one that implements our igance repository interface and so the beauty of dependency injection is that now in order to use the brand new repository all we have to do is use switch in mem gains repository into Entity framework games Repository and just by doing that the entire application is going to start using this brand new repository and our games endpoints don't really have to know that we're making this change those should just keep working as is now one other important change that we have to make here is to switch this registration from at Singleton into add scoped so no longer seeing intern but just scope just like this and this is because keep in mind that the game store context is registered as a scope service and that's what ad SQL Server is going to do inside this is going to register against your contacts as a scope service and that is just because of the way that the game store context has been designed it is designed to really just work for a small amount of time right during the duration of your request you should not keep this game store contest just leaving and hanging around for the entirety of the application so you do need a new instance of this guy for every single new request and since our games are context demands to be iscope service and if we kept the Entity Framework repository as a Singleton service it is not going to be possible to just inject gangster context into the Entity framework as repository right which is going to be a Singleton and that's because you cannot just inject a scope service into a single service right the Singleton is expected to live for the entireters application while the scope service requires a scope and there's not going to be any scope in a Singleton if you wanted to you can make that work uh by doing just something similar that to what we did in the initialize TV method over here so if we go into F12 in initialize DB remember that here's where we created a scope right here using the service provider we created a scope and Via that's called we were able to take advantage of our gamestore context because it is hoped it has to use a scope and you could do that if you wanted to in The Entity framework again repository but that's not really very usual that's not what you want to do you might as well just keep the exact same service lifetime for both the context and your gains Repository now we could keep things like this and just go with that but I'm not liking how much code we're writing right now just for the purposes of registering this repository and the context and so to keep things this file a kind of a clean we're going to be writing a brand new extension method that takes care of everything related to registering the Repository so let's go back into our data extensions file over here and we're going to do is just scroll down and we're going to be creating a brand new method that we're going to be calling public static I service collection that's going what we're going to be returning and then the name is ADD repositories now this is going to be receiving two parameters the first one is the type that we're extending so this is going to be I service collection and services it's going to be the name and then the second parameter is going to be our eye configuration instance okay remember that configuration is the object that you can use to retrieve any of the or the values that you have configured anywhere in the.net configuration system either app says.json or net secret manager or anywhere else so let's go ahead and open and close curly braces and let's scroll down a bit and what we do want to do now is to bring in those lines let's start with these two lines over here which are the ones that we use to register our game store contacts so I'm just going to copy that and paste those over here and in this case instead of using the Builder we're going to be using the configuration object that we just received as parameter like this and then for the actual registration we're going to be using directly the services parameter that we also got as a parameter order so that's that and then what we want to do is to also bring in our ads called call that we have over here so I'm going to be copying this and we can change that into our add SQL Server call just like that and then for this we may want to introduce other namespaces so I'll do a control dot so we can use game store.api.repositories and Entity framework games repository and after doing that what we're going to do is just return the services instance okay so by returning Services we allow any other of our colors to just make other calls into uh that use that services collection so with that in place if we go back into program we can now go ahead and do the following instead of having these three lines we can just say Builder dot Services dot add repositories and then we will pass in just Builder dot configuration and that's all it is okay so keep things clean and we can actually clean up these namespaces spaces and that's all of our product CS file at this point and with that in place we can go ahead and try out our net address API with our SQL server support for the very first time so I'll do Ctrl J here okay and so we're just going to do the net run so that's going to start and it is going to try to apply migrations if needed but of course there are no more migrations needed as you can see right here okay the database is already up to date so no more migrations so we are ready to start using the database so let's go back into our Postman over here and let's see first let's see if we can actually get any gains by just querying the the database right now so I'm going to use my get all endpoint over here I'll click on send and as expected there is well there are no gains right now right this is completely empty and what we can do now is to actually go ahead and create a game right so let's go back into our post tab over here where we already have scaffolded the code to create our Minecraft game and let me actually put here Minecraft which is where it should be okay and this should go ahead and create a micro screen so let's go ahead and click on send and as you can see it was a success so we got our 201 created status code and we got our payload right there and so this means that if we go back to our get all click on send we have our very first game now coming from the database and yeah so since that is working we could also verify that updates are working fine so let's go into our put over here uh where what this what is this is doing right now is just updating game number one uh but perhaps yeah it would not make sense to update Minecraft into Street Fighter 2 turbo so let's go back into post and let me just grab this body over here I'm going to replace it there and all we're going to do is just modify the name let's say that this is Minecraft for Windows and the price is going to be cheaper let's do 9.99 so let's go ahead and send our put call and yeah it was a 204 success so I'll go ahead and get all of our games and that's working just fine I can also get game number one over here by get by ID hit send it is getting the one game so that worked just fine and lastly yeah we could go ahead and also delete the game but before we do that let's let's actually create a just another one right just so that we have two items and then we end up we just one added an item at the very end so let's create one more Minecraft game over there so now we have two Minecraft games right so get get all we have two Minecraft games and in the delete call over here we're going to be deleting game number two okay so delete game number two hit send and then that was a success we go back to it all click Send and we only have one game so the entire race API seems to be working just fine and of course what we want to verify now is that everything is actually stored into the database so let's go back into Visual Studio code over here and I'm going to Ctrl C to stop my server I'll go back into my SQL Server Explorer over here and then I'm going to a right click on my D in my games table select top 1000. okay and if things are working properly we should see here let me put this on this side we can see that we do have our Minecraft game stored into the database so yeah RS API is now fully integrated into SQL Server database and with that in place in the next lesson we'll learn about an important technique that you don't want to miss in your res API implementation which is known as the asynchronous programming model in this lesson you'll learn about the asynchronous programming model and how to use it to your advantage in your ASP and netcore applications to understand asynchronous programming let's go through a common scenario you might be familiar with which is making breakfast let's say you start by heating your pan for a few minutes and then when ready you fry some extra we would also like to have some bread for breakfast so after our eggs are ready we bring up the toaster and toast our bread then when the bread is ready we add some Jam or peanut butter on it finally our breakfast would not be complete without some juice so let's pour in some orange juice in total it took us about 30 minutes to complete our breakfast but is that really how you would go about preparing your breakfast if it is a weekday when you are usually in a rush perhaps you would do it this way instead you start hitting your pan and well that happens you will also start tossing your bread and while those two things are happening perhaps you can also pour your orange juice eventually when the pan is ready you go back to it and fry some eggs and once the bread is toasted you go and put the jam or peanut butter on it doing things this way you can be done in much less time let's say 15 minutes and perhaps you can spend the rest of the time enjoying your breakfast when comparing these two ways of going about making your breakfast we say that the first approach is synchronous since you won't start a new task until the previous one is complete however the second approach is asynchronous since you don't wait for a test to complete before starting your next task instead you start as many tasks as you can and eventually you turn your attention to the tasks that are ready for you so you can continue with the next task in a similar way you can perform a synchronous programming in your SP netcode applications when a client sends a request to the web server you want to start handing the request in your endpoint in an asynchronous way so that your cook the Caster web server is immediately free to start handing the next request so as your endpoint starts on a synchronous call perhaps to your repository and the repository in turn requests data asynchronously from the database the web server has also started serving the nexo quest also asynchronously when the database eventually returns requested data the repository will resume work and send the data back to the endpoint which in turn resource work transform entities into details and sends data back to the web server who in turn responds to the original client request after this the application continues starting other tasks asynchronously and results work whenever necessary as you can see the asynchronous programming model brings in multiple benefits your application gets improved performance since you avoid blocking callers and free them up to perform other tasks which also results in oral better responsiveness you are able to scale your application better because it can handle more requests and users simultaneously without getting bogged down by waiting for Io operations to complete and also the use of task objects in combination with the async and Away keywords provide a simple and intuitive way of writing asynchronous code as opposed to having to deal with threads and callbacks directly now do you understand the asynchronous programming model and its benefits let's see how to put it to work in our current web API let's see how to take advantage of the asynchronous grabbing model in r.net res API so the first thing that we're going to do is go into our igames repository interface this one over here and we're going to be modifying all of our methods so that they followed the conventions of the asynchronous priming model so the first convention that we should enforce here is that since all of these methods are going to be for asynchronous operations they should have a different suffix right so for instance create should be renamed and I'm going to just do F2 here so F2 so create your renamed into create async right and that's just a convention in the.net world you don't have to do it but it is the right way to name any method and that is going to perform any kind of asynchronous at work and so just like that I'll do F2 for delete so delete async and then I'll do F2 forget async and then from get all I'll also do get all async and lastly for update I'll do update async notice that I'm using F2 here because I want to make sure that the these changes apply not just to my interface but also to all of my repositories right so if I go into my entity frame repository notice that the names have changed it right and same thing for in-mem games repository then as you have changed it by now okay that's what I'm using F2 the next thing that we want to do in this interface and close that is to make sure that all of them are returning tasks as opposed to the actual object or even void that is what is going to allow the colors to not just block on the call into these methods but actually take advantage of the asynchronous programming model by using the test Library available in.net so we're going to rename all of these return types into task so instead of void we're going to just type task and then again instead of void we do task and instead of game game nullable we now have to say task of game nullable and then instead of ignomable we'll say task of I know variable of gain and instead of again instead of updating it's going to be task of daily sync so with the interface fix it now we can go and actually implement the single surrounding model in our repositories so let's start with the Entity framework against Repository I'm going to collapse this for a moment so let's go up now and of course we now have to match the updated interface so let's go and start doing that one by one so let's start with our get all async method right so like I said we have to return now a task right so this is going to return task of a nominal of game and now when we invoke the to list method of the the edit framework for the Games Collection here we don't want to use to list but we want to use the variant that is for the asynchronous wrapping model and you're going to find this in most libraries that are going to perform anytime or any kind of time consuming operation right there always going to be some variant for asynchronous we're having so I'm going to do Ctrl spacebar here to find any other overloads so if you go down here we're going to find that there is a two list async method right here so I'll do that one right so now we're going to not be blocking in our call to to list but instead we're going to just let The asynchronous Branding model do its magic right so that we don't have to block that call now in order to be using it to start using this this kind of API here we also have to make modifications into two places in this method first we have to specify just after public we want to say that this is going to be async and also before returning we want to say that this is going to use a weight so that is the that combination of returning task and using async and a weight for every single invocation is what's going to allow you to take advantage of the asynchronous wrapping model for this very specific method so whenever somebody invokes this adult async method uh that color is not going to have to block on the location of ghetto async it's just going to start the task and whenever the task is complete the results are going to be returned back into the client so that according to the color so that it can continue the operation now let's keep going down into the next set of methods so now we have our get async so which is going to return a task of game node level okay and now of course this has to be async and then it has to do oh wait here and this is going to use find async the synchronous version now let's do the same thing for create async so this is going to return a task it's going to be async here and then it's going to do a weight limit context.savechanges async all right so let's keep going down let's go for our update operation so this is going to return task it's going to be async then it's going to be oh wait save changes async and then lastly for delete same thing we do task and then we're going to do a weight and that execute delete async and just by doing that now our Entity framework repository has been updated to follow the asynchronous programming model now just that we did this we did have a story we'll have to do the same thing with our in-mem games repository right so that it can actually comply with the interface now at this point of course you could decide to just get rid of this IMAP case velocity if it doesn't work for you but I found it very handy to do a few tests later on so that's why I'll be just keeping it around and all we have to do is just comply with the changes uh regarded by the interface so let's scroll down into Kettle async and again what we want to do here is just say that this returns task of a number level off game and again we want to do async and then we want to return a weight but of course there is nothing really to await on right because this is in memory there's nothing that we're going to be calling into so for these cases what you want to do is just take advantage of this method called task Dot from result okay and then you can just pass in your result okay so this is kind of a way to say hey let's pin of a brand new test but just created using the result that is right here there's no need to wait on anything just return a tasks that include includes the result so that's going to be very handy for our in-mem case repository so let's keep going down into get async which again is going to be task of game over here and then we're going to do async and then await and then task Dot from result and then games that find and they will close over there okay once again we're returning a completed task out of that fun game scrolling down into create async we are returning acing task really sync and in this case since we don't actually have to return anything what you can do is just say oh wait task that completed task meaning that the task has already completed there's nothing to wait for in this method same thing with updated sync we're going to say that this is async task updating and then we await tasks that completed task and once again we're going to go into our daily basing method here it's going to be async task and then we await task that complete task so now all of our repositories are now have not switch it into the asynchronous programming model but now we have to make also a few changes in our endpoints extension methods so that they can also work with this new paradigm so let's go into Explorer and let's go into endpoints games endpoints and let's scroll down into our first method here which is the map get for the get all operation so now the first thing that we want to do here is to add the async modifier right just before the parameter for this for this method here we want to do async right so that we can do an asynchronous operation inside this method and then before invoking a repository that get all async we want to do a weight right there okay and then we want to close into parenthesis this invocation into get all async okay that way the synchronous operation happens inside this parenthesis and we get out the actual list that we can then use to select the games and transform them into details then moving on to our get by ID all we want to do is just do async here and then we're going to do an await into it all async and that's all we have to do there and then we're going to scroll down into post once again we do a Sync here and at a point where we invoke capacitories that create async where we want to do is just say oh wait I almost done it up really sync that will do it and then moving down into my put once again we do async and then we're going to do a weight over here and also all the way down into whoops into update async this call has to also do wait and finally for our map delete once again we do async and then we do a weight here and also oh wait there so now the entire rest API is following the asynchronous programming model so this is what we know as async all the way right so whenever a request comes in it's going to use uh games endpoints that are made for the asynchronous running model and also a set of repositories that are using the synchronic model and also of course the synchronous running model of the Entity framework core so async all the way now before we test this uh this impose man hey one more thing that we can do is exactly modify data data extensions over here because remember that if you go a little bit up here we have this initialized TV method right which is the one that we use to run the migrations when the application starts this also has the capability of running in an asynchronous manner so all we have to do to enable that is the following so instead of void we're going to be returning async task and for the name of the method we're going to rename this and I'll do F2 initialize DB I think and then instead of calling my grade we're going to be calling oh wait database dot migrate async okay so that's the asynchronous version of this method here so that will make sure that when we invoke the database at the very start of the application startup we will also do it in a synchronous way so let's go back into a program.cs okay over here and let's make sure that we also use the await keyword right there before invoking the initialized async method so with that in place we have everything set up for the asynos primary model so I'll just do Ctrl J and I'll do the.net run in my game store.api directory and I'm going to go into Postman over here and just make sure that a couple of apis are working properly so I'll do our get all games hit send and as expected things are working properly we just have one game for now of course we should actually create a second game so let's go into post and in the body let's see if we can create another game here so this is going to be Street Fighter 2 and then this is going to be fighting okay let's leave the price as 19.99 that's fine and then the release date is going to be 1991 and it's February the 1st and the image array is just going to be that so let's go ahead and try this post operation I'll click on send and then yeah Street Fighter 2 has been created just fine and if you go back into the cat all we'll see that it is right there and so things are looking just fine all right so the synchronous running model is working just fine in our application so it is really optimized for not having to do any kind of blocking calls when we have to invoke external services like the database so that's the end of this model and in the next model we will switch tiers to another critical Topic in res apis which is how to properly secure your.net res API congratulations you made it till the end I really hope this tutorial met your expectations and gave you a good sense of how to get started building rest apis with the.net platform now there are several other things that your dot net race API is still missing to be ready for production you will want to secure your API to ensure that only allowed clients and users can get access to it you also want to configure logging error handling and many other services that will ensure your API is easy to evolve in the future and that you can quickly troubleshoot any issues it's also good to understand how to integrate your API with modern client applications and how to identify and authorize users for proper access to the data that's provided by the API finally you should know how to deploy your API to a public cloud service like Microsoft Azure so that your users and client applications can access it from anywhere in the internet to cover all these topics I created the building.netress api's online course which expands what you saw in this tutorial with dozens of additional topics and resources that will ensure to cover everything needed to build production-ready rest apis with.net if you're interested please check out the link in the video description to get all the details on this premium course thanks for watching and I'll see you next time
Info
Channel: Julio Casal
Views: 58,891
Rating: undefined out of 5
Keywords:
Id: bKCzoR01lpE
Channel Id: undefined
Length: 257min 24sec (15444 seconds)
Published: Tue May 30 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.