Setup POST Endpoints In ASP.NET Core API | Ultimate ASP.NET Web API Tutorial For Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] welcome back guys in this lesson we'll be dealing with the http post method or verb that allows us to create resources or new records in our database now we've worked with post previously when we're setting up our login functionality in our account controller we did kind of experiment with the post and we explored the fact that we can actually pass in data in the form of the body or an adjacent object that would get deserialized into whatever object we have set up for it and that way no sensitive information needs to go across in a url or in a visible manner so what we're going to be doing is setting up the post functionality for our hotel so that when we are creating a hotel we we can ask the user to send over all the details for our hotel in the form of a json object and then we pass it down to the database so i've already prepared the methods that we have our verb http post and we'll be returning status 400 status 201 as well as status 500 now notice this is 201 and not 200 because 201 means created so we'll be indicating to the calling application or the client that yes whatever you requested to be created has been created so let us get started now the first thing that i would want to do before i go ahead and create anything or bring over any data into my database is to check if the data coming over is valid so what i'm going to do is put in an if statement here to say if not model state is valid so we did something like that i believe when we're doing the login where we said is the model state valid meaning everything that i said is required is it there if not we return the bad request so we're just going to uh do the same thing replicate that step here what i'm saying if it is not valid then we're going to log the error and say that there was an invalid post attempt in that method right and we return the bad request otherwise we want to try an operation so we have our try catch and you know the uniformity of our code is such that we can actually take these all so you start seeing that we're kind of repeating certain things because all these things what if we wanted to change the message and we'd have to change it here change it in this method change it here and then as we expand we have to have more touch points so later on we'll see how we can kind of abstract out all of this repetition but right now i just want to make sure that we understand the concepts at hand right so we'll just go ahead and modify the error message and now you can try our operation now what are we going to try the first thing that i would want to do is to take this dto and if we just review this detail it has name address rating and it expects a country id and then we have hotel dto which has id and country so once again the reason we're not using hotel detail is that we don't need the id value coming across with the create attempt so that is why we only have the fields that we absolutely need values for outlined inside the create version of this dto now once i have the detail what i want to do is map it so i'm going to say var hotel is equal to mapper.map into an object of type hotel which is a data object and i'm mapping the content of the hotel dto next up we're going to call on our unit of work so i'm going to say underscore unit of work dot hotels dot and then i have insert what am i inserting my object of type hotel because by the time it gets here whatever validations you need to put in you can put in so here i'm just validating the model state if you had other things that you needed to make sure are in place before it gets as far as trying to insert it you make sure you do all of those checks and balances and return the bad request or whatever error status to the client before you actually start in the insert and even when doing the insert if there's an exception we're still going to return something except it will be at 500 since the error is probably on our side so after we call the insert the next thing we need to do is call the save so notice when we were just retrieving we could just do a awaits that get there's no save however on this occasion we're altering the the database so we have to commit the change that we're making afterwards so that is why we have to call the save now after all of that we need to return something nice so what am i returning next i'm going to say create ted now i've created and i've created at action right they're actually uncreated at root also so they all return the 201 it's just that when you say created it's just a 201 that's it however you can say created at root and have it called the endpoint get hotel with the id required so it actually returns the created object to the client which i think is useful so i'm going to go with creator that root and then i have to specify the name of the route so in this case i did say i wanted to go to get hotel and then after that i have to specify what parameter values this endpoint might need so if i look back at get hotel it needs an id so i have to specify a new object and it's going to have a field called id and it's going to be equal to hotel.id notice houghton a total dto hotel dto does not have an ide value however after this operation this object will get updated with its id and then that is what we will pass along so let us take this one for a spin but just before we do that before i get ahead of myself we need to let this root know that it has this name right so even though it has the name we need to let it know that it in it is a get operation that goes by that name not necessarily root but by that name right so i can just append here and say name is equal so this is like a little internal nickname now to say this is your name whenever somebody your sibling sibling being another action calls so let us try that again all right so we're going to test this one in postman and i already have an object here so i actually copied this object from a previous get test so we already established that the id is not required however just going over to swagger just to show you what swagger is going to care about when we look at the post for hotel it's showing us that this is all it's going to care about so even if we send over extra information it will be ignored all right so that is what our object needs to look like in order to go into our post so using postman i'm actually going to test it with the id and let's see what happens so i'm going to click send make sure that this the action is on post we have our endpoint and then click send and we're getting this error about system invalid operation no root matches supplied values so that means we need to restructure the code around the creator that so going back to the code let me just see what overloads are there and we have the string root name we have the object value i believe i'm missing the actual object there we go so comma and hotel so we're passing over the id and actual object to be displayed so let's try that again so the same test that just gave an error i'm going to try it again and there we go so look at the difference between the two payloads we're getting back our hotel object with the id value of six all right even the five is 5.0 here it's five here right so just to show you that this didn't count for anything thanks to us not allowing them to submit that data so that's another reason it's a good idea to use details to kind of sanitize what can come into your api now in addition to displaying the newly created record another advantage was using created at root and pointing to the endpoint would be that in the headers we actually return the location where they can go and fetch this record so you see it it did have a certain purpose if i just you know the client if they look in the headers and just get location after i've returned uh the data like that they can actually just use that and do a get operation and retrieve their record but of course i'm not authorized so you know that whole shebang already they'll have to go through and do all of that now on the point of being authorized i don't think it's harmful to allow somebody to retrieve a hotel by id right so we did authorize it initially because we were testing however in practicality i don't think we need to authorize git hotel if we allow them to get the list they should be able to get one however i do think that it would be good to authorize who can create all right so it's up to you it's business rules and your needs will determine where you put the authorized and how much security you enforce around your endpoints and operations so in this situation i'm going to authorize create hotels so you have to be authorized and to make matters worse if you are not in the role of admin then you shouldn't be able to do this so to enforce roles based authorization i can say roles equals and then list out as many roles as i want to support so if i say authorize roles equals administrator that means if you are authorized you get a token but you are a user not an administrator then you cannot carry out anything you're still not authorized however if you're an administrator then you can go right ahead so that is how once again you can go about enforcing one what endpoint do you expose to john public versus an author authenticated user and then by extension how do you extend these functionalities to which authorized group of users he can authorize based on policies roles and there are quite a few options available to you if you just press comma you'll see that you have the authentication scheme you could make one jwt another one password auth etc etc you can enforce a policy and you can limit it by rules so there are quite a few options for that so right now i'm going to challenge you once again what we just did with create hotel i encourage you to try and do it with the country make sure that you test it and that you get back your country successfully and we'll compare notes and we're back i hope you paused and attempted it if not then go ahead and pause now but i'm going to walk you through what i did and really and truly you'll notice that the code is almost identical one where in the country controller we have the same authorization measures once again your context may be different from mine but we want to just make sure that we secure the endpoints accordingly we are doing it up http post we have similar return types to what we did with the hotel except for the action i'm going to call it create control we're passing the appropriate dto we validate the model state firstly and then we go ahead and add just in the same fashion and then we created that root get country pass over the object and we made sure to add that name here so you see once you get the hang of this unless you have some extreme circumstance where you have to do extra computations and calculations and even then it would just be a matter of mapping over or well yeah you would probably wouldn't get the calculated values through the dto so you map it to the object type and then you do all your calculations and then you insert and save so there's really not that much to creating resources in your api [Music]
Info
Channel: Trevoir Williams
Views: 2,458
Rating: undefined out of 5
Keywords: .net 6, .net core, .net framework, .netcore, api, api testing, api testing using postman, api tutorial, application programming interface, asp.net core, asp.net core api, automapper .net core, core, dependency injection, development, dotnet 6, dotnet core, dto, post, post request, postman, postrequest, programming, rest api, restful api, testing course for beginners, tutorial, visual studio, visual studio 2019, visual studio 2022, web api, what is an api
Id: zTEjyN8aHuY
Channel Id: undefined
Length: 13min 45sec (825 seconds)
Published: Mon Mar 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.