Creating a JSON CRUD API in Go (Gin/GORM)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what's up youtube welcome back to another edition of coding with robbie my name is robbie and in this video we're going to be creating a crud json api in golang so we're going to be using some third-party libraries in this video we're going to be using jin which is the top http web framework and then we're going to be using gorm which is the top orm so if you haven't liked and subscribed please do that now and let's get right into it alright so first things first you're going to want to download the go programming language if you haven't already you can just come to go.dev click downloads and then grab the one that matches your platform so if you're on apple you could also use homebrew and then yeah once you've got go installed you can uh run go from the command line and you'll see all the commands you can do with it if you type go m we can see that our go path is um where is it go path go path go path is our home folder slash go so they kind of want you to organize your code in a specific way so you're going to create that uh go folder in your home directory and then within that folder you need a bin and source folder and then within source you create a folder for where you're hosting it so mine's github.com and then within that folder there's another folder for my username robbie klein and then in that folder is where you can create your project directories so let's uh once you create those let's cd into it so i'll get cd go cd source cd github dot com see robbie klein and then i'm going to make a folder for our project so i'll go make dir i'll call it go crud and then i'm going to open it in vs code and yeah one thing you'll want to do whoops so i got a cd into it first and then open it with vs code and uh one thing you'll want to do first is download the uh official go extension and when you install this it'll recommend some other stuff just hit install all so yeah now we can go back to our terminal and let's run go mod init and this is going to create a go mod file and this is similar to like a package.json if you're coming from node or a jam file if you're coming from ruby and that's cool so now we can install packages in this project so we're going to be using some different stuff within uh this tutorial so we're going to need this compile daemon package i think that's how you pronounce it and this just watches files for changes and rebuilds it and runs it whenever there's a change so let's uh grab this package so we'll copy the command we'll just paste it in here and run it and it'll download it and then we're also going to install it so we can run it from the command line so do the same command but do go install instead that'll install it and then we're also going to use dot m which is just an easy way to load environment variables so let's grab this one also uh i'll paste it in and now we got that package and you can see it's adding it to the dependencies list right here and then we're also going to be using gin web framework which is the number one framework for uh golang so let's go to docs and uh let's see quick start we gotta install it with this command so let's grab that and we'll uh we'll paste it in so there we go we got it downloading i'll just take a second there we go and then last up we're going to use gorm which is an orm library for go it's the most popular one so let's go to um docs we gotta install a couple things we want the gorm library right here so let's run that and then we also need a database driver so i'm going to be using a postgres so i'll copy this part of it paste it in and then type postgres and there we go we got it so we got all our packages downloaded so now let's uh create a main dot go file so i'll go in here main dot go and it's going to be package main we need a main function so let's go funk main and then let's just uh print line hello to see if it's working so there we go and now let's run this uh file with that compiled daemon package we installed so to do that let's check out the docs we go back to the repo right here and they give us some examples so let's copy this one right here and i'll paste it in so compile daemon's gonna build it every time there's a change and then we can run a command after so we just want to run the builded program so it's dot slash whatever you named your go module so mine is go crud so let's run that we can see it builds it and i get hello and now if i change hello to hello one two three it's gonna rebuild it and i get hello one two three so that's convenient and um yeah let's get started so let's check out uh let's check out the gin documentation the quick start guide we're on and they give us an example right here so let's just copy this i'll go to main.go and i'll just paste it in there and uh yeah we're creating a gin uh app or router right here and then we're adding a route and we're running it at the bottom so let's just change this to the root path and let's uh try it we'll go to chrome and we'll go to localhost and it works on 8080 by default so we go there and we get our message so it's working so now let's set up uh our dot env package so let's create a new file dot env and we'll create a variable within there called port and we'll do 3000 and then let's go back to the docs and they show us how to load it right here so let's copy this and we'll go to main.go and um we could put it right up here but there's also a special function called init which will run right before main so we're going to do it in there so let's create funk in it we'll paste it in it'll automatically add the imports and now this should be loading our variables so now if it worked correctly it should be running on port 3000 so let's make sure it works we'll go back here go to localhost 8080 it doesn't load anything so i try 3000 and there we go we get it again so we got that working good and uh yeah now i'm going to bring this to a separate uh file so i'd like to organize things in separate files let's create a folder we'll call it initializers i just i like the way rails organizes stuff so i kind of copied that let's create a new file called load env variables go and uh in here we'll go package initializers and then let's create a function and we'll call it load m variables and just note that i started it with a capital letter this is important if we want to use this within other files so make sure you do that and then let's just copy in what we got right here save that and now let's run this function within our main file here so let's go here and i'll type initializers dot load m variables and uh save that and it was supposed to auto import it but it's acting weird so i'm actually just going to reopen this whole folder see if that fixes it let's go back here initializers.load environment variables and there we go this time it actually imported it so that's working and let's go back here and i'll just restart it so it looks like everything's working let's just check that our server is still running so go back here hit refresh and i still get it so that's cool so next up uh we gotta connect to a database so we don't even have a database yet so the best way to get one or the easiest way is i found this elephant sql website we can create a free postgres database so just sign up for this and then once you log in you get to a dashboard we can create a database so just create one do free and just go through it i already created one so i got it right here i'll click into it and here's our database credentials so let's go to gorham and see how to connect so we go here and let's go to connecting to a database and here's the example they give us so i'm also going to do this in a separate file i'll go database.go and then in here will be package initializers and uh we'll go func connect and we gotta do capital two db and this function is gonna run [Music] this connection example they gave us right here uh so let's copy that i'll paste it in and then yeah we got to fill this in with our uh wait i copied the wrong one so this is the mysql example we want postgres so let's go down here and copy the example get those two lines paste them in and we gotta fill this in with our credentials so let's go to elephant sql and here's my credential stuff right here so let's copy it and let's see we got the uh username right here so let's paste that in we got the password right here let's paste it in and then we got the database name right here i'm going to delete this time zone stuff uh database name right here and then we gotta change the port the default one is 5432 and then for host it's right here put that in host so that looks good and then instead of doing a local variable right here i'm going to create a global one that we'll be able to access in any of our files so go var db of type gorham db like that and then let's create a variable here to store an error and then instead of creating new variables i'm going to assign it to the existing ones so db and error and then let's just check if there's an error so go if air is not equal to nil if it's not equal to nil let's do a log fatal and say fail to connect to database so save that everything looks good let's run this function from within our main file so go in initializers and i'll run it right down here initializers.connecteddb save that let's check out our terminal and i'm not seeing any errors so it should be connected to our database so one other thing i think we should do is uh probably put this in an environment variable so let's copy this and i'll go to dot m and i'll just go db string or db url i guess paste that in let's go back here and now we're going to use that environment variable so to get it let's check out the docs if we go to dot m you do os dot get m and put the name of it so uh dsn is equal to os dot get m and ours is db url it's going to be all capitals db url save that let's see if it's still working so go back here i don't see any errors so we should be good cool so uh we got our environment variables we're connected to the database and we got an example we'll just test throughout so now let's start doing our crud operations all right so let's create a new folder we'll call it models so before we can do anything else we gotta define our models so let's create a new file called postmodel.go and let's see how to make a model so go back to a gorum let's go to declaring models and they give us some examples and the one we want is right here so this gorm dot model is going to automatically add these four fields for us so let's go in here we'll go package models and uh whoops let's paste in that example and ours is going to be a post because we're going to be making a blog and a post is going to have a title and make sure to do capital letters here and a body which would be a string also so save that and now we got to migrate our database so it creates a post table for us so let's just create a new folder i'll just call it migrate and within there i'll create a file my grade.go and this is gonna be package main and let's look up how to migrate so if we go here let's go to i guess overview and they show it right here we can auto migrate it so let's copy this and let's go funk in it and funk main so in funk main we'll paste the auto migrate so we got to get our db here so let's make sure to connect to the db up here so initializers.connecteddb we also got to unload the load the environment variables so initializers.loadm variables and then yeah to access our database it's now going to be initializers dot db and we want to auto migrate and now we pass it a struct of our model so we can go and models dot post and uh did that auto import it no it didn't okay i did package model instead of package models so now let's go back and now it should work and it does not there we go all right so we're importing that file and we got our model struct right here we're passing it to this auto migrate function and now if we run this file it should create our table in our database so let's go here and let's go go run my grade slash migrate and it's going to run the file and we don't see any output so i'm assuming it worked so let's connect to our database and see if we have it so i'm going to be using software called uh table plus and you can download it for free at uh tableplus.com they got a free trial and i don't want to update right now let's go back here i'll just copy the connection string and then let's go create new connection import from url paste in that url and hit connect so i'm connected to that database and i can see i have a post table right here and it has those fields we created so that's cool so now we can finally start doing our crud operations so a lot of setup but we're in a good position now so let's uh create a new folder called controllers and let's create a new file in there called posts controller dot go and then in here let's go package controllers and uh yeah let's take our function right here and just copy it i'll just get this part let's go funk and we'll call it uh what do we want to call it let's call it posts and it has to be capital so we can use another uh file post create and there we go now we can use this in our other file so let's go here and let's just connect it right here so let's delete don't mind my dog let's delete all this and let's go controllers dot post create just like that make sure everything's working so let's run our program again and let's go to uh chrome and go back here and just refresh we still get it so it's working and yeah so let's uh change this to slash posts and it's going to be a post request this time since we're creating something and we got to send in data and then yeah in here we're going to get data off request body and then create a post and return it so uh let's look up how to create in gorm so if we go back to this and we go to gorm guides and we go to create and uh here's an example right here so let's just copy this and i will paste it right here so we're going to be creating a post we're going to have to get to get the post struct thing so let's go models.post and a post is going to have a title so for now we'll just go hello and our post is gonna have a body so let's go body is gonna be post body so save that and then right here we have to go initializers.db since that's where we're storing it dot create and then we just pass it this uh post model we created right here post struct so post initiate created in our database and then it returns the result so let's see what result is if we go back to create results as if there's an error or how many rows are affected so let's check for an error we'll go if result dot error is not equal to nil let's just uh c dot status we'll go 400 error and we'll return early and then if there's no error we'll return with the post we created so we can return post right here so this should work we're not getting the data yet we're just hard coding it to test so let's uh we're going to use postman to test our api postman is just an interface to send http requests so you can download it here and uh yeah i already got it so let me open that [Applause] so here i am i'm going to create a new workspace i'll just call it go crud it's going to be a personal workspace and uh let's create a new collection i'll call it posts and then uh let's create a new request within posts so add request and i'll call this create post and it's going to be a post request to http localhost 3000 slash posts save that and let's send it so i send it and i created a post and i get it back so let's go to our database and i'll refresh and we can see it created our post right here so that's cool so now we gotta get the actual data off the request body and uh use it within the create part right down here so let's see how to do that let me go to my cheat sheet real quick so uh to get it off it you have to create a struct that's gonna store it so let's go var body and it's gonna be a struct that's going to have a body type string and a title type string and then we're going to run c dot bind and then we pass it a reference to that body struct we uh declared up here so and body and now we should be able to access uh those properties through body so right here we can go body dot title and we want to get body.body so there we go so now when we create it should actually be using the data we send in so let's test that go back to postman i'll go to body i'll go raw and select json and let's send in a title uh from reg body and let's send a body um from wreck body i think we gotta do capital letters here so let's make sure to do that and let's send it and see what happens so i send it and now it's using the data we passed in so if we change this we'll get a different post so that's cool there's our create function so next up uh create we got a read so let's just minimize this for now let's create a new one funk posts uh we'll call it index and it's going to receive the gen context and yeah in here we want to uh get the posts and then respond with them so let's go back to the docs and let's check out how to get data from gorm so go here i'll go to query and then here's how you can find a single record and uh receiving a record by the id right there and we want to get all objects so it's pretty simple we just go let's see posts is equal to um sorry we gotta create a variable to store our post so let's go var post and it's going to be of type models.post and it's going to be a array of those and now on this function where we're finding it we just pass it uh our variable right there a reference to it so and posts and then it's actually going to be initializers.db so there we go this should be finding all our posts and assigning it to this variable right here and now we can respond with it so let's copy this down here and let's just go post is equal to posts and let's connect this to our router now so go back to main we'll create a new one it'll be a get request this time and it's going to be connected to posts index there we go let's go back to postman and try it so i'll create a new request i'll call this um fetch posts it's going to be localhost 3000 posts and let's run it and there we go we're getting all our posts so that's our fetch all function right there now let's create one to dispatch a single function a single post so i'll call this funk posts show and it's gonna take this stuff again and then it's very similar this time we just got to find the single post so let's change this just to post and it's not going to be an array it's going to be a single post and then let's look up how to get a post so go back to gorm and let's go to receiving objects with the primary key and here it is right here so initializers.db.first [Music] and we pass a reference to the post variable right there and then the second argument is the id so uh we're gonna be getting this from the url so right here we gotta go get uh id off url and let's just connect this to our router real quick so let's uh go back to main.go and it's going to be a get request to slash posts slash colon id and let's connect this to post show and yeah this is like a dynamic route so if we go to post slash one two three one two three is gonna get assigned uh to a param called id so if we go here how do we get that off the url well you just go let's go id is equal to and we do the context and it's dot capital param and then we put in the param we want to get so id so this should be grabbing the id and assigning it to a variable called id so let's pass that in right here and uh this should be working so let's try it out we'll go back here we'll create a new request i'll call it fetch post and it's going to be localhost 3000 slash pose slash nid of one we want to get so i'll just try one i'll hit send and i get the first post and i go two and i get the second post and i go 200 and i don't get any posts it gives me the zero uh value for everything so one thing i don't like is i name that post so i'm gonna make it singular right there all right so we got our reading stuff done all right so next up we got to do update so let's create a new function we'll call it post update so i'm just going to copy this guy right here make it post update and yeah in here we've got to get the id of the url uh get the data off request body and then we gotta find the post we're updating and we want to update it and then we want to respond with it all right so we did this first part above so let's just copy it it's right here and we also read data off the request body before so let's copy that so we go back up here we create a struct that matches the data we're sending in and then we bind it right there so i'll paste that in and then next up we gotta update the post so let's look up how to do that oh sorry next we gotta find it so we did that in show so let's just copy it right here all right so we're getting the id off the url we're getting the data off the request body we're finding the post using that id off the url and now let's look up how to update so we'll go back here we'll go to update and then here's how you can update a single column but we want to update multiple so we'll go right here and they got in an example right here so i'll paste it in ours is initializers.tv and then we have to pass it a reference to the model that we're updating so far and post and then in here we put our updates so ours is going to be models.post and a model has a title and a body so we're going to update title to body.title which we have stored right up here and we're going to update body to body dot body there we go this should be updating we need a trailing comma and something's wrong i didn't put a capital b right there and now we just got to respond with it so we can just copy this up here so let's connect this to our router and try it out so let's go back to our main.go file and let's create a new one and for updating it's going to be put and it's going to be slash pose slash colon id and we'll connect this to post update so let's go back to uh postman and let's create a new request and we'll call it update post and we'll go localhost 3000 slash pose slash the id we want to update and then let's go and body and we're going to send some json with it so let's just go title updated title save that and this is going to be a put request and let's send it and see what happens so i hit send and i get the updated title so if i go back to fetch and i fetch the first post you can see it really did update it in the database which is cool and yeah it only updates the fields you send in so if i send in body i could also update that and that's cool it actually doesn't have to be capital right here so you can do lowercase it looks like so i can go one two three hit send and it updates the body now also all right so last step we got to do delete so let's create a new function called pose delete and it's going to get the context again so let's copy this right here and then in here we got to get the id off the url and then we gotta delete the post and then respond uh respond there we go so the first part we've done already let's just copy the line from up here paste it in and let's look up how to delete a post so we go to delete and uh delete with the primary key and they got an example right here so let's paste this in ours is initializers.db dot capital db and then it looks like we have to pass it uh the type so let's go and models.post and then we put the id right here so let's go id and let's see what this uh returns it doesn't look like it returns anything so uh let's go down here and let's just uh let's just go c dot status we'll go 200 to indicate that it went through successfully so now let's connect this to our router i'll go back to main and this is going to be a delete request and it's going to be pose slash colon id and this time it will be connected to post delete and let's try this out let's go back to postman and i'll create a new uh request i'll call it delete post and it'll be local host three thousand slash post slash one and it's gonna be a delete request and let's see if it works i hit send and i get a 200 back and if we go in our database now if i go to this first record it's kind of interesting behavior it doesn't actually delete it it updates this deleted at column to let us know that it's deleted and at what time so if we ever want to revert we still have the data saved so that's cool and now that post won't show up if we like try to fetch it say we tried to fetch the first post now we get the zero value if we go to fetch post it's no longer in that array and yeah we're good to go we pretty much got everything working we can create we can fetch we can fetch a single post we can update a post so i'll update the second one and we can delete a post so everything's working good hopefully this gets you started with this uh gin framework and gorham and i hope you enjoyed the video like and subscribe and have a good one you
Info
Channel: Coding with Robby
Views: 110,050
Rating: undefined out of 5
Keywords:
Id: lf_kiH_NPvM
Channel Id: undefined
Length: 34min 8sec (2048 seconds)
Published: Sat Jul 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.