How To Use DTOs In .NET REST APIs

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] foreign 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 res 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 address 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 the client 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 real 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 now for this we will be using the record types feature of c-sharp because they allow you to create immutable classes primarily assign it to hold data and these matches our dto requirements since the data that comes from them should be immutable meaning that once the 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 RS API now one thing that we have to remember here is to also add the corresponding namespace so let's go ahead and add namespace gamestore.api and let's add here details 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 video 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 video 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 this 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 detail 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. right and so scroll down and then we have folder price we know that we want to use the range data attention 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 Ura we want to specify that it has to be a URL and it also has to have the string length for a harder so I'm just going to copy that over here next we're going to be defining the the detail the last CTO in is 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 and it extensions let me close this for a moment and on this one uh well let's just fix the next phase first compared to file company 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 control dot to use kingstore.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 ID so we get the ID from game.id and then we go for game dot name and then game.generate game dot price game that 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 map get 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 restart 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 General game video that generate and we'll just keep going with this of course until we complete all of the properties okay in detail that price release date release date and finally image URI equals video image URI and with that in place the ratially 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 uh 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 general price 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 that 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 foreign [Music] [Music]
Info
Channel: Julio Casal
Views: 6,608
Rating: undefined out of 5
Keywords:
Id: ddRiM6k8wk8
Channel Id: undefined
Length: 14min 18sec (858 seconds)
Published: Tue Jun 13 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.