ASP.NET Core 6 REST API Tutorial | MongoDB Database

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey guys i am venket and this is part three of mongodb video series in this video we'll discuss building a restful api service using visual studio 2022 asp.net 6 and mongodb database visual studio 2022 is the latest ide from microsoft if you don't have it installed already on your machine navigate to this website visualstudio.microsoft.com downloads and then select this first option download visual studio with dotnet the community edition is free and will do for the api that we are building in this video so select this first option download the community edition and then follow the simple on-screen instructions to install visual studio 2022 after the software is installed fire up visual studio click on file new project we want to create an asp.net core web api so using the search text box here search for asp.net core web api we have a couple of matches here the first one is for c sharp and the second one is for f sharp we want to use c sharp so let me select that and then click next let's name our project student management and i'm going to create at this location sql on projects and the solution name is also student management click next as of this recording the latest dotnet framework is dot-net sex so select it from this drop-down list as the framework leave authentication type as none and then check these three check boxes configure for https use controllers and enable open api support we discussed what is swagger and open api specification in detail in parts 29 and 30 of this agile video series so if you're new to these two concepts please check out these two videos so on this additional information screen with dot net six selected and these three check boxes checked click create there we go we have our project created the first thing that we want to do is install mongodb dot driver nuget package so let's go to solution explorer right click on the project name and then select this option manage nuget packages make sure you are on the browse tab and then in the search text box here search for mongodb.driver notice the first option here is the official.net driver for mongodb select that and then click install accept the license agreement there we go nuget package installation complete now what we're building here is a student management api and we're going to store all our model classes in a separate models folder in our project so let's go to solution explorer right click on the project name and then we want to add a new folder let's name it models and in this models folder let's add a new class let's name it student now when data is retrieved from mongodb database the student json data is mapped to this student class in.net and vice versa so within this student class we need a few properties first let me paste those properties here from the mongodb dot driver nuget package that we just installed we need two namespaces so at the top of this student.cs file here let's include those two using declarations so we need mongodb dot bsun namespace and we also need bsn dot serialization dot attributes we want this id property in this student class to be mapped to this id field in the student json document in mongodb to achieve this we're going to decorate this property with bsun id attribute notice when i have the mouse over from the intellisense we can see this attribute is coming from mongodb.bsin.com and this is the reason we included this using declaration i'm going to decorate this id property with another attribute bsun representation this attribute automatically converts mongodata type to a.net data type and vice versa in this specific example it's going to convert data type object id to a dotnet data type string and vice versa notice this boolean is graduated property i'm going to decorate this property with bsun element attribute basically it's mapping this boolean is graduated property in our student class to graduated field in the document let's do the same with these other properties as well name courses gender and age there we go the rest of the properties are decorated with basin element attribute at this point you might be wondering all these properties especially name courses gender and age have the same name as the fields in document so what's the need to decorate these properties with vsan element attribute well the casing is different that's the reason in c sharp the properties start with an uppercase letter whereas in the fields start with lowercase there are several approaches to handle this case sensitive mapping one of the easiest and clean approach is to use bsen element attribute now if we take a look at one of the student documents in database notice we have address field in the document but if we take a look at the student class on the dot net side we don't have a property corresponding to the address field so the question is what to do if we receive extra fields from database well we can instruct the serializer to ignore any extra fields and a way to do that is by decorating this student class with bsun ignore elements attribute next in our application configuration file that is in app settings.json we're going to include database connection string and other pieces of configuration data that we need now if we take a look at mongodb compass notice the collection name a student courses and the database name is my first database and this is the configuration data that we are storing in our app settings.json file the collection name is student courses and the database name is my first database all that is left to do is to get the connection string to get the connection string log into your mongodb atlas account and then make sure you are on the databases tab click connect we want to connect our application so select this second option and from the drop down list here select your programming language in our case we are using c sharp and dot net we also need to select a version uh the version that we are using is later than 2.13 and copy the connection stream from here paste it within our app settings.json file right here next replace the password including the angle brackets with your actual password and if we take a look at our mongodb atlas account notice the message here ensure any option parameters are url encoded to url encode your password navigate to this website url encoder.org type in your password i have it typed as volahola space123 and then click this encode button and we have the encoded password right here let me copy this and paste it in appsettings.json file next in the models folder i'm going to include a new interface you'll understand the purpose of this new interface in just a bit i'm going to name this interface i student store database settings inside this interface i'm going to include three properties notice the names of these three properties they correspond to the three settings that we have in our app settings.json file next again in the models folder i'm going to add a new class file name it student store database settings now we want this class to implement this interface i student store database settings and then we obviously want to provide implementation for these three properties if you're wondering where do we need this class and interface well we're going to use these two to read and store database settings that we have in our app settings.json file we'll discuss how to do that in just a bit now for separation of concerns we're going to place the code that calls database in a separate service layer so to our project let's add services folder so right click on the project name in solution explorer add new folder name it services in this folder let's add a new interface name it i student service click add we want this service to be able to perform all thread operations so let's include the required methods bring in model's namespace this first method get returns the list of all students this method returns a single student by id create creates a new student and returns that newly created student update update student by id and finally this remove method deletes student by id our obvious next step is to provide implementation for the service so in our services folder let's add a new class file name it student service we want this class to implement the interface i student service plus control period and select the first option implement interface we want to inject a couple of things into this service so let's include a constructor for that now our database settings are present in this file appsettings.json and we need these settings in our student service and we also know it is this interface i student store database settings that is going to carry these settings from app settings.json file to our student service in a bit we'll discuss how this interface is going to read the database settings that we have in appsettings.json file for now let's inject the interface i student store database settings into our student service and let's call this parameter settings we also need imongo client interface and this interface is present in this nuget package mongodb dot driver so let's include the required using declaration first mongodb.driver and we want to inject imongo client let's call the parameter client on this injected client interface we have get database method obviously this is going to return the database for us and for it to be able to do that we need to specify the database name and it is the settings object that carries the database configuration information including the database name notice on the settings object we have database name property let's store the database in a variable called database on this database instance we have get collection method and as you can see from the intellisense it supports generics using wedge we can specify the type of collection in our case the type of collection is student and obviously for this method to be able to retrieve the collection we need to pass it the name of the collection again this incoming settings object has got the collection name so setting start student courses collection name and let's store this collection in a variable called students we don't have this field yet so when i click on the field and then press control period we have different options here select the second option create read-only field our obvious next step is to provide the implementation for all these grad methods that we have in this student service let's start with create we want to insert this incoming student object into our collection underscore students so underscore students this is our collection and on that we have insert one method because we're inserting one student we're going to use this method and obviously the parameter for this method is the incoming student object and then let's return the inserted student object next get we want this method to return the list of all students so again on our students collection we have find method and we want this method to return the list of all students so the lambda that we are going to specify here always returns true so we get the list of all the students finally convert this to a list and we want to return it so let's include the return keyword next we want to get a single student that is student by id it's going to be very similar to the implementation of this get so let's make a copy of it so we want to find a student where student id equals incoming id and we are getting a single student here so instead of two list we will use first or default next remove we want to delete a student whose id matches with this incoming id again the implementation is going to be similar so let's make a copy of the statement this method is not returning anything so we don't need the return keyword and instead of find method on the students collection we want to use delete one method because we are deleting one student so delete the student whose id matches with the incoming id finally update this method has two parameters the id of the student whose details we want to update and the student parameter contains the updated values again the implementation is going to be similar to remove so let's make a copy and instead of using delete one we want to use replace one method so the first parameter is our filter expression which we use to find the student whose details we want to update in our case we want to find the student whose id matches with this incoming id so that's our first parameter and the second parameter is the replacement and this is the student object that contains our updated values now here's the important bit to understand into this student service using this constructor we are injecting these two dependencies i still install database settings and i client and notice both are interfaces here so we need to tell asp.net core dependency injection system what concrete implementations to provide for these two interfaces and we do that in program dot cs file this is standard dependency injection in asp.net if you're new to dependency injection we discussed it in detail in part 19 of asp.net co tutorial so please check out this video so in the interest of time let me paste four lines of code here and then i'll walk you through it first let's fix all the compilation errors by including the required using declarations so this line number 10 here is basically telling asp.net to get the section with name student store database settings from app settings.json file so basically if we take a look at app settings.json notice we have a section with that same name string store database settings so basically it's telling get all these settings from this section and then map them to this class student store database settings and then this line right here is tying the interface i student store database settings with student store database settings class meaning whenever an instance of this interface is required provide an instance of student store database settings class and if you remember within our student service class we are injecting i student store database settings interface so whenever this interface is required provide an instance of student store database settings class which contains the configuration information that we have in app settings dot json file and then here we are uh specifying to client the database connection string now again in our student service we're using this injected imongo client to get the database and for this service to be able to get the database it needs to know the database name so basically we need to specify where it has to read the database connection string from and here we are specifying that configuration information and finally we are tying our i student service itself with its implementation so here we have our student service which implements i student service our final step is to include a controller that exposes all these cred methods that we have in this student service so to the controllers folder let's add a new controller what we actually want to add is an api controller and not an mvc controller so select api and then select api controller with read write actions click add provide a name for the controller let's call our controller students controller and then click add there we go students controller is added with all the required plumbing in place notice this class is decorated with these two attributes api controller which makes it an api controller and then the router attribute so with this attribute in place when we navigate to slash api slash the name of the controller in the browser in this case the name of the controller is students so when we navigate to api students this is the controller that is hit and the first thing that we want to do inside this controller is inject this student service into it and to be able to do that we need a constructor so let's include it and the service that we want to inject is i student service let's bring in the required namespace first and let's name the parameter student service generate the required private field by pressing control period and then select the second option when this get method is called we want to return the list of all students for that we're going to use this injected student service remember on our student service we have get method so if we go to student service notice we have the get method here which is returning us a list of student objects so within our students controller let's change the return type of this method to action result of list of student objects let's bring in the required namespace next we want to get student by id so in the url when we navigate to api slash students slash the id of the student then we want this method to return that specific student whose id value matches with the id we have in the url and that id value is passed to this method now if we take a look at our student class notice the id property value is string so first within our controller action let's change the data type to string as you can see the implementation is pretty straightforward we pass this incoming id parameter to the get method on our student service this is the service which actually looks in the mongodb database with the student with that respective id if student is null that means we have not found the student so we return this message student with id equals whatever is the id not found otherwise we return that student so the return type of our get method is action result of student this post method creates a new student object the new student details will be passed into this method from the body of the request hence this parameter is decorated with from body attribute and what we'll get into this method is a student object so let's change the data type here to student and let's also call the parameter student implementation is a tool liner as you can see we are passing the student object to the create method in student service which will actually create an entry for this new student in the underlying mongodb database and then we're using this created at action method notice from the intelligence this method returns the http status code 201 created and this method also sets the location header using which we can access the newly created student object and for that we are making use of the get action within this controller and if we take a look at this get method notice for it to be able to return the student that we have created it needs the id of that student which we are passing using this second parameter right here the third parameter is the newly created student object itself and from the intellisense notice the return type of this method is created at action result which again implements action result so let's change the return type to action result of student next put which we use to update existing student details the student id is of type string and this parameter is going to be the student object itself which contains the updated values so they type a student and let's call the parameter also student we pass this incoming id parameter to the get method in our student service and retrieve the existing student if existing student is null that means we have not found the student with a given id so we written the message saying student with the id equals whatever is the id not found otherwise we pass both the parameters the student id and the student object that contains the updated values to the update method in our student service which will actually update the student record in mongodb database and then finally return no content from this method http status code 204 and notice from the intelligence the return type of this method is no content result which means we can again use actionresult as the return type finally delete first let's change the data type of id to string we pass the incoming student id to the get method on our student service which will retrieve the existing student if existing student is null that means we have not found a student with the provided id so we return not found otherwise we pass the student id to the remove method on our student service which will remove the respective student record from mongodb and then finally return this message student with id equals whatever is the id deleted and if you notice the return type of this method is okay object result which means we can also change the return type of this method to action result with all these changes in place let's run our project there we go our api is up and running and here we see all our students controller actions if we issue a get request to this endpoint slash api students we get the list of all students and to try out this action click this button try out and then click execute notice the server response we have the status code 200 okay and in the response body we have an array of student objects if we take a look at mongodb compass at the moment in the database we have four students and we see those four students in the response body right here in an array next let's try post we use a post request to create a new resource in our example if we issue a post request to this endpoint slash api students a new entry for the student will be created in mongodb so let's try it out in the request body we need to include the student object that we want to create let me paste a student object that i already have id property is not required a value for this field will be automatically provided by mongodb so let me delete that and as you can see the name of the student here is sarah we also have the rest of the fields populated so let's click execute there we go the http status code is 21 created and in the response body we have the newly created student object including the id field value that is generated by mongodb if we take a look at mongodb compass notice we have that newly created student right here notice under response headers we have location uri which we can use to access this newly created student object so let's copy this location uri paste it in the browser and we have that newly created student next let's try get student by id so if we issue a request to this uri api students slash the id of the student we get that specific student so let's try it out in the id field we need to provide a value for id so let's get this id from the browser execute there we go status code 200 ok and in the response body we have that specific student next let's try put we use put to update a resource in our case let's update sarah's record let's change name to sera 1 and update few other fields there we go in the server response we have the status code 204 no content and if we take a look at mongodb compass notice sarah's record is updated as expected finally let's try delete and to be able to delete a resource we need to specify the id of the resource there we go status code is 200 okay and if we take a look at mongodb notice sarah's record is gone that's it in this video thank you for listening [Music] you
Info
Channel: kudvenkat
Views: 65,298
Rating: undefined out of 5
Keywords: asp.net 6 rest api tutorial | mongodb database, .net core rest api tutorial | mongodb database 100, .net core rest api tutorial | mongodb, .net core rest api mongodb, asp.net core rest api | mongodb asp.net 5 rest api | mongodb, asp.net core 5 rest api tutorial | mongodb database
Id: iWTdJ1IYGtg
Channel Id: undefined
Length: 27min 11sec (1631 seconds)
Published: Sun Jan 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.