Creating Golang REST API with Gin-Gonic Web Framework & MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello friends my name is sarang so today we'll uh develop rest apis using this uh gin web framework which is written in golang and it is 40 times faster than other frameworks and if you leave if you need the performance and a good productivity you will love gene framework so that is what written in the official github github page of this framework and we'll be developing the rest apis using same and we'll also do a crowd operations using tv so by this video you will understand how to develop rest apis using gin and um how to do a crowd operation using mongodb okay so before you start looking into the video you should be familiar with the basic concept of golang you should be familiar with the interfaces uh struct then slices okay so if you're familiar with all this uh basic concept of golang then you can find this video easy and you can also start building the rest apis using this fastest framework okay so before we start digging into the implementation of the rest api using gin so i would like to show you what we're gonna build we're gonna build five apis uh one post to get one patch and the delete uh the post api uh uh will have the payload in this way name age address or simple user information and we'll save it to the database so i'll send and this particular user information has been saved and i can also get the particular user information using get request i have to pass the name of the user sanu and i will get the user information i can also get uh or update the particular user information if i want to update the user information of sauron i will replace or i will update the age with let's say 70 i'll be able to do that see success and uh you can see that that information has been updated 70 okay and we can also get all the users so since we have only one user now so i will add one more user with the name dev problems okay that user has also been added so you can use uh get all api to get all the user information so there are two starting user and one dev problems so i will uh also able to delete the one of the user so this is delete okay you just have to pass the name of the user and i'll be to i'll be able to delete the user and i'll do the get all now that problem user is deleted so all these things will be doing using a gin and mongodb so let's get started so i have the vs code open so i have a folder with the name go yt and we will be uh first creating a file go.mod file which is the namespace of your project so we will write a command to create that file which is go mod init and i will give the name of the namespace example.com sarang apis okay so we have the file file created has it has no dependency right now so we'll add the gene dependency since uh that framework will be used to create the rest api so it is getup.com uh jin jonic jin okay so let's wait for it to fetch all the necessary thing and we'll also add the driver so because we're going to create the rest apis oh sorry we're also going to create the crud operations so uh the name would be go dot mongodb dot org slash driver okay so now we have all the necessary dependency added so uh we'll be creating our rest apis using a typical mvc uh framework uh type so we'll be creating directories like controllers services and models so i've created uh this folders okay and i'll create a main.go file which will have the main function and the package called main okay so right now i will not do anything here first we'll create our data object which is a user okay i will write the packages and models same as the folder name the package and the folder name should be same and i will create a user struct and this truck would have fields like name age and it will also have a reference to other struct which is address so i will create that as well address struct and this will have straight city and pin code okay now let's also create the uh alias or the json way representation of this particular field which is name and since we're also gonna deal with the mongodb so the name would be a username in the mongodb okay so i have written in the bson because supports peasant and i will write your age and in the bsn i will write user age you can write anything you want here as per your standards and here i will write address these on would be user address okay and same goes for this thing for address struct in the b zone i will write state okay sorry i have to do it like this here it's gonna be city and in the basin also will write as a city here i missed the colon and for pin code we'll write the same thing pin code okay so this is the adjacent way of this particular property you can think this as a annotation which is an alias for this particular field okay so now we have created our data object now let's go to the service and create service files okay i will write as user service dot go so here i will create a interface which will help us to define the service contracts okay or api contracts i will name it as a user service and it is an interface okay we have to implement the methods that will write and we'll be implementing using struct but let's first define the uh api contracts model.user and it will written error okay if there is error while saving saving in mongodb will written that error okay and get user will be one of the contract where we'll pass the username and uh we will get the corresponding uh user in the response okay and get all is means get all the uh user present in the mongodb so this is gonna be a straw slice which will contain uh user objects okay and one more is update user here we will pass the data of the updated user object and also written error if there is any while saving into mongodb and then we will create a delete api which will pass again the username and we will return the error if there is any error okay so these are the api contracts that we have and we'll implement each functions okay using a struct now let's create the implementation class service dot impl dot go it is also in the service uh package and uh let's it's gonna be a struct okay so let's create that first so type user service impl struct okay and this truck will have the user collection object which will be of type dot collection and it's a pointer because we will get the object and we will point to that object so that is the that's the way okay and we will also have the context i will explain why we need this context uh later but first uh let's first implement all of these functions that we have written in the interfaces and this particular struct will implement all of this so uh let's create a receiver function which will help us to create the function of type receiver and the first method is create user which will take user and if if there is a error it will return the error it's not a focus on the implementation now we will come back to this so for now we'll return nil and i'll create one more uh receiver function you use a service impl and this will be a get user which will take the username and return the particular user object for now we will just written nil nil okay and let's create the rest of the function get all and this will return the models user internal okay now i think we are left with two other uh function which is update user and delete user so let's quickly write that as well user service impl so it is update user models user and it will written error if while saving to if we get an errors will return that okay and we are left with the last one which is delete user okay so here we'll receive the string okay which will hold the name of the user that we need to delete okay so hang on with me guys uh everything will make sense we are just creating the structure of the project okay so now uh what we're going to do is we have to also create the okay there is some issue here uh wait just a second what is this packet services in the go list found packet services and services in colleagues package expected services okay so we have to match the folder name that is what the error was and it should be context so uh let's okay let's start actually there was a uh dependency issues so what i've done is i have added the dependency again and now it seems all the errors have gone and now we are getting a warning here that uh this particular properties have been unused so we have to initialize this properties and how we're gonna do is we're gonna write a function which will act like an constructor and for this we will pass the user collection of type dot collection and we'll also pass the context object and we'll return the interface user service so we're gonna return the interface but we will create the implemented class which is user service impl will pass the address so user collection user collection and this would be context contacts so now i'm getting errors saying that get all type of method okay the implementation of this particular contract had a get all with this and we have okay we have a different return type so it is saying that it is not uh getting compatible with the methods that we have defined here now it is fine okay the signature should be same that is what uh it is telling when we created this function it is it was denying to create an object because all the functions uh signatures were different uh sorry not all only for the get all okay so now we have created a a kind of a structure for this particular user service impl now let's work on the controller side so what i'm gonna do is i'll create a file user controller dot go and this will be of package controllers okay now the controller will also be a type of struct so user controller struct and this will hold the user service i will make it as a public user service services dot user service okay as you have noticed that in the controller we have uh the reference of visa service and in the uh user service we we have the reference of collection okay so we are injecting those objects okay because uh this is what we do in the typical mvc uh uh in a architecture that will create the folders and will keep on injecting uh the objects that we need okay in different classes so since the service layer is gonna interact with the database layer so it has a database object over there and iso controller will interact with service so it will have the user service reference okay so the constructor also would have the uh sorry the controller will also have you should also have a way to initialize the services so we'll create a constructor user controller and we'll return the user controller with the with the past user service okay we have the uh struct and the constructor okay now uh we have to create the methods so from the controller we will define the routes and the routes will call these methods which is present in the service implement okay so what we're going to do is we'll copy all these methods and we'll paste it in a controller okay so here there won't be any such return types in the controller way okay and the controller will not have such written type so i'm removing this okay what we're gonna pass here is a gene context so i will write your ctx gene dot context this is what we passed here and this should be user controller and i'll write here uc and for now what i'm gonna do is i'll write uh jason 200 and some nil or empty string for now okay the context this particular context object gene dot context will hold the information about the request that we're gonna send and the response will be sending using this method called json so that's what we have done over here so i will create that thing the next so just keep this thing for now and i'll copy this context for every uh route functions so this this functions in the controller will be acting as a handler or you can tell us the route functions for the routes that we will defined in a moment okay and copy these things and this will be uc okay so let's now uh define the routes so for that i will create a method or receiver method so let's create user controller register user routes okay and we will group all the user routes for that what we're gonna do is we have to uh get the object of jin route group okay i will explain you what we what we are doing here is we are just grouping all the uh user outs under uh a name called user so we are writing a group and this will be user okay a kind of base path we are building it so now let's write user route dot let's write post okay so when we hit this url user create okay we're gonna call the create user function okay and the create user function will uh will will get this gene.context object and this object will hold all the request header data and in the same object we have to return the response using this json method okay in the same way we will write the other routes okay so there will be two get one is get all and another one is uh get user correct so for this i will write get slash name because this is the parameters uh that i will send it in the url mentioning the name of the user and will get the particular user object so this one get user so i will change this to get user okay and the other one is get or where we'll get all the user information present in the database so we'll write get all and here we have patch which is an update user so if we hit the end point with the update so write update user okay and we'll also create one more which is delete and this will delete user okay so these are the routes that we have created okay so let's uh start writing the logic of interacting with the database first okay because that is important that how we gonna interact so in the service let's go to the service layer and uh let's create a user okay let's see how we can create a user so let's look at the function signatures we'll get the user in the request and we'll add that directly into the mongodb correct so let's write u dot uh we have a user collection object and we have initialized that user collection in the constructor using that we will perform one insert one that will pass the context ctx and the incoming user and this insert one will return uh insert one result in error so i'm not interested in the insert one result so i will write underscore for that and i will write error okay i have created a variable with the name error if there is an error we are returning it okay so this is the logic of inserting a user okay in the controller what we're going to do is uh we will call the we'll call this particular user service method of creating a user so let's this is the one let's give me a second so this particular gen dot context uh this particular variable ctx would will hold the user information so let's first create the uh let's first declare the user object uh sorry the user variable and we will whatever the user information that we get in the request we'll add it in this particular variable so let's write that so context dot should bind json okay it should be capital okay and we'll pass the address of this particular variable and uh what we're gonna do is uh we will check if there is any error while binding so i'll create one variable err error okay and this err if it's not nil what i'm gonna do is i'll return a response in the same context object i will send the status as a bad request no it's not bad it's bad uh request because we're not able to bind that and the response would be uh message string and the value it will be the error that we'll get while binding okay and if we get this we'll just return it okay so whatever the uh user object that we get in the request we are binding it into this particular variable and if there is any error uh the error object will not be nil and we will we will pass on the bad request status and we will pass on the message uh okay and now what we're gonna do is if there is no error while binding so we will call the user service create user method and we'll pass the uh address of this particular user object okay and if the error is not equal to nil i will again do the same thing okay now this time the status should be bad gateway because there is a that's a that's error while saving in a mongodb so it should be a bad gateway okay if everything works fine if there is no such thing okay so we'll write http status okay and we will pass the message as success so this would be success okay so what are we doing is whenever we uh get a request for this particular endpoint create we will call the create user function with the context object and this particular context will have the user object we are binding it in user variable or and if while binding if there is any error we will send the bad request and if there is no we will create we'll call the create user function which is present in the user impl and here we are interacting with and inserting the data of a user that we get in the request and while doing that if there is any error there are err variable will be holding the error message and we'll return that okay and if it's not nil definitely will we have to uh written the bad gateway uh status code and the message that this error er variable holds and if there is no error we will send http okay and the message success okay so this was for the create user okay now let's write for the uh get user so let's go to the impl okay now the get user will have the parameter name which is dynamic okay so first we have to get this particular name uh from the endpoint so we will will get that so how we gonna do is var user i'm creating uh i'm declaring one one variable and here what i have to do is i have to pass the name here correct so in the controller what i'm gonna do is i will hold the i will write the user name as ctx dot param name okay and i will pass this is there any error object return no and what i'm gonna do is i'll write uc dot user service dot get user user name okay now let's complete the implementation of this so now i'm the user impl so here i have to write a query where we are querying based on the username that we get in a request so we have to write a query which is b sun dot d b sun dot e key should be name and value should be the name that we get okay so there is this everything is perfect so basically this this line represents if you want to do such kind of uh query like db.collections name dot find okay name something like uh type problems if you want to do such kind of query you have to represent in you have to write in this way okay so you can also go into this this thing and read the documentation that these in order representation of the bsn document and all these things okay so now let's write a logic to get the user so user collection dot find one and here we'll pass the context and query and then what we'll do is if if we get the user we will decode decode that and give it to this user variable and while decoding if there is any errors we will return that error and user so this is the logic of getting a user a particular user from the mongodb okay now let's go to the controller and finish that part so here we will receive user error from the user service and again if there is any error we will return this thing bad gateway if everything as expected we will return the user so this should be uh user object okay this is the get user i hope you understand the implementation and one thing that i missed out here is in every uh i have written context here correct in every interaction or api i'm passing this context because this context is helpful if you want to perform the operation within a certain period of time let's say you want to find one user in just 5 to 10 seconds and if what this particular operation takes more than 10 seconds then using this context object you can cancel the operation and send a saying that it took a lot of time so using this context uh you can do a lot of things setting the time that how much time it should take for this particular option to complete if it's not you can cancel you can use this uh thing in the production but now we are not gonna initialize the context in a way that it should be used in a production okay so i'll show you that when we are writing in a main file here right now we have just created the files and writing the logics but we have not initialized the user service as you can see we have created a constructor but we never created the object so of the user controller but we'll do that in a main.go file once we complete the apis here so we have written for the get user and for create user let's write it for update user and delete user quickly because they are pretty much same like uh create user so for update user uh when the user hits or endpoints for update or delete the particular method would be called okay so what we're gonna do is uh first we have to for update user we're gonna pass the uh updated user information in the request so first we have to get that thing so what i'm gonna do is user models dot user okay and i will copy the same thing if there is an error while binding we will written the bad request and written from this function okay if there is no such thing we will call the user service update method and pass the address of the user object okay and if there is any error that we got that we get from mongodb we will return that as a bad request or sorry bad gateway okay if there is no such thing what we're gonna return here is write http okay and return success okay now let's go to the impl and implement same for the update users so in the update we have to first find the particular user and then update the particular user information so first we'll write a filter query so the filter would be like uh finding the user by the username so that's what we will do i think that we have already written here correct so let's copy this okay here it's gonna be user dot name okay so i think in the bson we have written user name user age address okay so this would should be user underscore name and this should also be user underscore name so we have written the filter thing we'll filter the user by the name and then if we found the user we'll update it correct so for update i'll write same thing vsan dot d v sound dot e and here we'll write key as in set setting the uh values and the value should be uh basin dot d and here we'll update the values so they're gonna be three basins here since there are three fields in the user object so we have to update those three fields here so right like this okay so the first one would be uh key key should be user name and uh value should be user dot name okay and let's copy this and change only the required thing is a name and sorry this should be for address it should be user address and this should be address okay and this should be the user age and just right h okay so this two things we have to pass it in our update one function of user collection user collection update one so first we'll pass the context and uh filter update and we'll get the result of the updated and will not interested to get the error because we'll find if there is any match count that means we have updated the user if it's not equal to sorry 1 then we'll return errors saying that no match document found for update okay so this thing and will return nil if there is no error okay if if this thing is if the match count is greater than one okay or equal to one okay then we'll send no errors that we have that means we have updated the uh user okay so i think the controller side also we have done for the update user yeah so let's now uh do it for deleting the user so the deleting user also would be same like get user because we will get the parameter here we have to change this to name correct we have to get the name from the endpoint so we'll write our username ctx param and it should be uh name and u dot user service dot user we'll send the address of the username and we'll return error if the error is not equal to not equal to nil we'll send the bad gateway and we'll sell the particular information if everything works as expected we'll write http status okay and giving the success message okay and let's implement the impl side e-service side okay here what we're gonna do is uh here again we have to write a filter logic because we have to first find the particular user so this should be name okay and then we will find and delete that particular user user collection dot delete one this is the one here will pass context comma the filter query okay and again we will get the result okay if result is same we'll copy this this thing if there is no match count equal equal to 1 then we have not found the user to delete okay i think pretty much done on this side so uh we have implemented uh four queries for now uh four apis create uh get uh create get update and delete the get all would be little tricky so but let's implement that quickly on the controller side what are we expecting on the get all is we will we have to get all the users that are present in the mongodb correct so on the controller side we will get a list of users and errors if there is any error uh uc dot user service dot get all if there is any error we will send the bad gateway pretty much same if there is no such thing we'll send the users and that should be the http status okay okay uh here what are we getting this is undefined has no field or match count okay so why is this there is some va score issue as well i guess there should be uh okay sorry my mistake it should be deleted count okay okay so let's go to the get all and here we have to deal with cursor and all because we have we have to we have to deal with cursor because we have to get the users one by one from the database so let's first create the slice object which will be useful cursor error and this would be you dot user collection user collection dot find okay sorry just a second it should be fine and here i have to pass the context and uh write the logic to find all the user so if we write just b sunday that means we need all the document that is present in the okay for particular collection if there is any error if error is not equal to nil return nil and error okay if there is no search then we have to iterate the cursor and use this next method and pass the context okay and here our user models it should be capital and that sure we are decoding it that particular user and saving it in this user variable if while decoding if there is any error again same thing and if there is no such errors then we will append this particular user in the user slides we have to pass the address because we are saving the we are using the pointers so we are saving the address of all the user okay and after saving this we have to also close the cursor okay so for that we have to write if we get error somewhere okay error while uh iterating it so this method will capture the error for this particular cursor while lighting if there is any error this particular variable will have the error information and if the error is not equal to nil then we have to return this this thing okay and if everything works fine we will close the cursor by pausing the context information okay and if the length of the user slice is still equal equal to zero after i treating that means there is no uh information uh or or there is no user in the database so written nail errors dot new we will write documents not found because after i treating if we still don't get any documentation and the length is zero that means there are no documents in the uh okay i think uh this was the toughest one i guess the since we have cursor and all but it's very easy if you see the code again and again okay now we have completed the all the packages now the only thing left is to initialize everything and start the uh gin server that would be again a little tricky but bear with me and you will understand everything so first i will define all the required variables so i would re i would need a gen dot engine uh variable because this would this the gene dot engine is the consider this is a base or server for the gene framework so i would require this i will also require user service so uh in all the other packages i have uh just defined everything now i will initialize everything in the uh in the main file controllers dot user controller this is context which is of type context dot context uh this will be user collection and this will be of type dot collection and i would also required client and dot client error error of type error okay so uh these are the variables that will uh that we have declared and we will initialize this in a init function so context would be uh context dot to do so we are not uh dealing with any timeouts so the to-do will will create a simple context object with no cancellation thing inside and we'll write uh connection connection logic which we will get from the options dot uh client dot apply uri mongodb local host oh sorry i think it should be slice localhost 27017 okay and i will initialize the client error using dot connect will pass the context and connection okay if there is any error if error is not equal to nil we will just close the application by passing the error in the console if there is ener while if there is error while pinging the uh db so what we'll do is before we start any operation we will ping the mongodb and we'll check whether we're able to connect or not to the primary database which is at 27017 not the read replica this is the primary one which will pass the admin command to find out whether we are able to connect to mongodb or the mongodbs up or not and we will write one log to just check the connection has been established okay now uh the other things we need to initialize is user connection client okay so this should be sorry this should be client database uh i don't know why is this thing is giving me this okay it should be a database name should be user db dot collection should be users user service should be services new user service user collection we have to pass and we have to pass the context and it should be user controller which we have to initialize user controllers dot new you have to pass the user service and finally we'll initialize the uh gene server which will do it with the general default method okay now this in it using in it we have uh defined everything here all the objects we have created in it function now let's start the server in the main function but before that we will also differ means in the default what we're going to do is we'll disconnect from if the application shut downs okay so this should be context and will pass we'll we'll also add the base path and this should be version one i'll explain in a minute what is this group okay so user collection controller dot register user routes i will pass the base path and then we will run the application at uh nine zero nine zero okay so what we have done is uh we have here uh written a default keyword to disconnect if the application shutdowns and from the mongol will disconnect and this is the base path v1 so we have to uh call like v1 slash user slash create okay this is the base path v1 and the other parts is here user slash create user slash get okay so i have grouped uh the user routes here using route group okay and the v1 is the best one okay hope you understood and why i'm not able to [Music] import the options let me check option okay this should be a client i think now i'll be able to do this yeah now it has imported okay so now i think uh we are we are almost done and now let's use the thunder client to uh check whether we are able to run the application correctly or not i have the mongodb running okay right now if i check i don't have user db here i have written user db should be present and in that i will use the user's collection correct this would be created when we call the api now first let's start the application and we'll call the end points and start calling the doing the crud operations okay this is my anti-virus thing ignore this one started application at nine zero nine zero let's see okay it is listening on nine zero nine zero it has listed down all the routes like uh update user get all uh delete user okay that seems good now let's create a new request first let's add the user this should be local host 9090 v1 user create in the body uh i'll pass that request name should be let's say the problems then we have age of type int and then we have a address let me also open the user so that is what we are passing here name address and address have state city and pin code so this should be state all right uh anything let's say gujarat and city okay this should be and but okay and also the last one is pin code okay now let's call this one a page not found uh did we add the users or user it's a user right why do we have page not found oh we have to post sorry so it is success now let's go to the mongodb and check whether we created the database or not yeah it is created use userdb uh db.users.mind okay so information we got in a mongodb now let's create a a new request for get okay here what we'll do is we'll copy this paste it here and this should be get here i will write the name of the user as a dave problems we got the information so two apis are working fine now the third one is uh get all so in the get all we just have to [Music] pass this get all since we have only one user uh we are receiving an array here as you can see okay so now we left with update and delete let's update our user which is of type patch i think this is a patch one update one we have written a patch okay now this should be update update also uh requires a body so let's copy this i will change the age as uh let's say 60 something okay we are able to succeed and we will able to update it so let's check yeah the age is 60 now has been updated now the only thing left is delete so before deleting i will add one more user as sarang and that has been added and let's delete one of the user since we have two users now as you can see get all the problems i'm sorry let's delete one of them this should be delete and copy this one delete here i have to pass name as dev problems okay so we are able to delete this this user and let's use get all to see whether your dev problems has been deleted and only sarang user left okay that is cool now let's uh check the errors if we get or not for get all now let's use for update i will pass the wrong user now let's say dev problem is not present i'm trying to update we'll get everything no match uh bad gateway and no match document found for update okay we'll use it same for delete since we don't have to have problems to delete we got no match document found for delete okay this errors we have defined over here as you can see in the user impl if we don't get matched uh we will use sending this message as error okay i think this is pretty much it i think uh you got the idea how to create a rest api using uh golang jing web framework and also we have done database operations basic cloud operations i think this is pretty much it and let me know if you have any doubts it would be little very scary if you just see it the first time but if you just look at the code the code is very simple we have created the folders according to the mvc structure we have the controllers which holds the routes and the service which interacts with the database and fetch all the user information we have api contracts and we have the uh all the initialization and everything done in the main.co file i think this is all and have a great day and please subscribe to the channel and help me know let me know what videos you need further i will create i'll try to create that one and yeah so thank you so much and yeah subscribe to the channel have a good day
Info
Channel: Dev Problems
Views: 26,154
Rating: undefined out of 5
Keywords:
Id: vDIAwtGU9LE
Channel Id: undefined
Length: 62min 59sec (3779 seconds)
Published: Mon Mar 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.