Creating a Go API using an ORM - Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hi everyone its Elliot from Tottori alleged or net and unless tutorial we're gonna be building a simple REST API that utilizes an ORM in order to interact with a sequel 8-3 database as always the full text version of this tutorial can be found on my website and I'll leave a link to this and the description below so why are we even using autumns what are they well who are Em's or object relationship managers are essentially brokers between us the developers and our underlying database technology the allow us to essentially work with objects much as we normally would and then save these objects without having to craft complex sequel statements in essence we effectively reduced the complexity of our code base and scenarios we'll be done wesh2 work with sequel but need a database so let's jump into our favorite editor and start programming and that's the tutorial I'm going to be working with in two fails the mint go fail and the user go fail and that should hopefully give you some indication as to how you can break up this application into multiple fails coming and terminal go fail let's do the following so packaged mean and then let's define our list of imports so within this fail we're going to need the FMT package the log package next HTTP and the gorilla mocks github.com slash gorilla nuts like so next we want to define or handle request function that will route any incoming requests to our API to the respective function that will be handling them func handle requests like so and with an S we want to define a new Ritter so my Ritter equals max dot new Ritter dot strike flash true and next we want to define a simple hello world over the endpoint just so we know everything is working and we can build on this incrementally so my Ritter dot handle funk and just the root path hello world and this is going to be called through the gate method finally we want to do logged or fatal HTTP lesson and serve and we want to specify the port that this is running on so port 8081 and pass on the wrister that we've just created finally we want to define our main entry point for our program so func main fmt dot print line go o RM tutorial and we want to kick off our handle request function and just before I forget we wanted to find this hello world function here so funk hello world and s will take in a hasty T P dot response writer object and our reference to the request that was made and with unless we want to do F M T dot F print F W hello world perfect save that and then come in to our terminal below some CD cool or M tutorial and then run this program by calling call run min-koo and as you can see everything started successfully and if we comments our browser and have localhost 8080 one you should see hello world perfect so know that we've created I really sent poor API from which we can base the rest of our project last night comment to the user cool fail and start flashing this out so again this is gonna be part of the the main package and and our list of imports we are going to need FM t and net slash HTTP so let's work through this so the first endpoint we want to create as an all users function which is going to return every user within our sequel Lite database so funk all users W HTTP response writer and our HTTP request just to check s works we're going to do FM t dot F brand F W and all users endpoint hat kill so the next one we want to create as our new user function so whenever that's his hat and the user will be created in the database again same format as above response writer our HTTP request and again just a nice simple F R and F new user endpoint head next we want to do the delete user endpoint which will delete any users within our database based on a specific value response writer our HTTP request and again another fnaf delete user endpoint head and finally we want to do our update user function so func update user W HTTP response writer our HTTP request and FMD dot F brand F update user endpoint hat perfect and shrim to capitalize us and fix that one spelling mistake and then come back into our MnDOT go-to fail so now that we created these methods or functions we want to match them against particular paths and HTTP verbs so but then our handle request function we want to do the following my router dot handle funk and the first one is gonna be our users which will map to all users and it will require the get therap next we want to do where is that handle funk and this will be our new user function or endpoint so user and this is going to take an name as a path parameter and an email and you like ice SS through the post there like so specifying new user just after the path next we want to do my Ritter dot handle funk again and we want to create our delete user endpoint so user and we're going to delete these users based on the name value just to keep it nice and simple delete user and this will be the delete HTTP verb like so and finally I returned handle funk we're gonna define our update endpoint so user and it's gonna update the user that matches I gave a name and change the email address and a method for this is going to be good perfect so let's try it run this by calling go run startup go and as you can see everything is running successfully if we then come into rest client such as postman and try and have a post request of one of our other endpoints you can see that it successfully returns a 200 stay s and the new user endpoint hat message is displayed and the body of the response terrific so everything is working up until this point so the next step of our project is creating a database now if the purpose this tutorial we're going to be using a sequel III database but you should note that you can easily swap out other database technologies such as my sequel or midea DP by switching dialects and go out em now these dialects essentially do all of the heavy lifting photos when it comes to translating any of the API requests we make and to proprietary sequel statements that match up with the underlying database technology we're working with so for example because I'm using sequel Lite we use the sequel Lite dialect in order to end right with it so open up our users go fail again and at the top we want to import the ORM that we're gonna be using so github slash jens you go out em and underscore github calm genzou goddamn and this will be the dialect so it's equal late like so little that's people to define our database connection so VAR TB go m dot DB like so next we want to do is define our user struct so type user and at the top of the spool require guatemala to let be go ahead and know that this is going to be modeled somehow in the database next we want name of type string and email or type string so nice and simple just to get started that we've got s we want to define error a natural migration function now this will essentially take this user struct we've just defined and create the create table sequel statements for us no that's just where the power of the RM really comes into play that's simplifies our code base and basically lets us focus on the business logic instead of creating the sequel statements so let's comment here funk a national migration and we want to do TB or air equals quorum door open and we want us to open our sequel eight three stable database and it's called test dot DB within our local directory next what we want to do as f error does not equal nell we want to fmt dot print line that's error so air dot error and panic so failed to connect to the database like so next we want to the fair the clue that's database just good practice and TB dot Auto migrate passing and our user stopped like so and before I forget define error error so far error of type error like so and that should get rid of any errors that we had down here coming to our main dot go function and we'll want to call that's a natural migration function with an arm mean so what s will essentially do is when we kick off our go program they'll perform nice and natural migration create the tables for us and then I'll kick off our REST API now what happens if the user table already exists within our sequel Lite database well the URM is quite smart and in the sense that I will create the sequel that only creates the table F it does not exist so now that we have our user table to find within our sequel Lite database let's come into our user to go fail and come into our all users function now we're going to be rewriting us so we can delete what was that there previously and to the following so DB air equals quorum door open so this is I was opening the connection to our database and passing in the path and FD error as nel or not knelt we want to panic saying could not connect to the database like so finally we want to defer the closing of this connection so the ferdi be closed and now we can interact with our database this function is going to return all of the users within our database so to get started we want to define a temporary storage location VAR users of type array user and we want to do D be signed and all users like so after this after we've returned or found all of the users within our database we want to encode less with jason the new encoder passing in our response rater object and including our users like so now if we try and run this by calling go run start go and coming into our rest kind of choice and having the slash users get endpoint you should see that it returns any of the users within our database they have already populated that's what has dummy example just to show you that this works let's carry on and define the remaining three functions so in our new user function we want to do the following so again TB air equals query and open it's equal eight three and test DB and I'm just gonna call copy and paste the error handling under the fare from above now with an S we're essentially going to want to capture the path parameters of the request made to our API once we have these name and email path parameters we can define a new user and call the DB create method in order to populate that's the user enter our database so VARs equals MUX the VARs take in our request object and the name will equal virus name like so and we want to use his double quotes and our email will equal bars email that we've got us we want to do DB create at user and the name is going to equal name and email it's going to equal email like so finally once we've done this we want to return f mt dou f pregnant f w and new user successfully created now ideally you should be returning adjacent response that informs you that the response is correct and possibly returning the user object as jason form but for now we're going to keep it nice and simple close the currently running server and try restarting and when we open our rest client and we had user test i'm call it a lea and my email at email calm and whenever we had this as a post request you should see new users successfully created just to verify that this user has been put into our table we can again call our slash users endpoint and you should see that Elliott and my email at email comm has been added now let's try to tackle our delete user endpoint so we want to do the following copy and paste this DB connection and the faired closing and then we want to do the following so FAR's equals most of ours and we want to parse the name from our path parameters so VARs and named like so and we want to find the user that has the exact name so far user user and DB dot where name equals question mark passing in our name dot feigned and then we want to pass in our user like so so what this does is it creates a sequel statement that tries to find any user with the exact name and our path parameter and populates it into our user object here now that we have this user object we simply have to call DB dot delete at user and then again we're going to just do a nice simple FMT dot f printf and user successfully deleted restart just to check this works and create delete requests for user of type Elliott and send and that's returns status 200 users it successfully deleted when we again happy all users endpoint you should see that it's going back down to just the one user and finally if we want to update the email addresses of any of our users we can come in to update user endpoint copy and paste the previous connection code and do the following so we want to again find the same user that matches the name so probably steal this as well and then we want to call user dot email equals email so just to add this here email equals VARs email so that's again parses the path parameter for our email and stores at an email we then once we have found the user within the database with the same name we then update the email address of that user to equal the new email address passed and the path parameter and then to make these changes permanent we call DB Save and user and then again FM t dou F and F response rate or object and successfully updated user perfect again restart your server and we are going to once again call the add user method and then we're going to want to update this verb to the put there like so and then change the email address to new at email comm like so now wouldn't we hit this you should see that it returns successfully updated user with a status 200 and again let's check this works by hitting our old users endpoint and you should see for our object alias within the database the email is now set to new at email com now that's all for this tutorial and that's the to do we've been able to define a fully functioning crud based API that interacts with a database now hopefully you found this tutorial useful and it showed you the full advantage of working with an ORM when it comes to database interaction if you found this tutorial useful or require further help please don't hesitate to let me know in the comment section below and leave a like and subscribe to my channel for more programming tutorials Cheers
Info
Channel: TutorialEdge
Views: 67,982
Rating: undefined out of 5
Keywords: go orm tutorial, gorm tutorial, golang orm tutorial, go object relational mapping tutorial, go api with orm, go crud api, go api with database, go api project
Id: VAGodyl84OY
Channel Id: undefined
Length: 22min 30sec (1350 seconds)
Published: Sat Feb 17 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.