Building a Go REST API using Gorm and Fiber!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I would suggest an App struct that holds pointers to fibre and database. That way, you can easily extend your application to support logging, form validator, etc. Make your handlers receive this app struct so you can avoid repitition such as database.DBConn everywhere.

For curl, you can use single quotes to enclose your data. That way, you don't need to escape double quotes in the json payload.

👍︎︎ 1 👤︎︎ u/gmhafiz 📅︎︎ Apr 25 2020 🗫︎ replies

Great tutorial, thanks! What are the features you like in fiber?

👍︎︎ 1 👤︎︎ u/hoeRIZON 📅︎︎ Apr 26 2020 🗫︎ replies
Captions
hi everyone is tutorial edged Arnett and in this tutorial we're gonna be building a really simple REST API and gore using the new up-and-coming framework called fiber now as always the fueled text version of this tutorial will be available on my website and I'll leave a link to that in the description below Oh Wi-Fi ever you may ask if you're coming from another language and trying your hand at developing co-op vacations then fibre is an incredibly easy framework to start with that presents a familiar feel to node.js developers who have previously built systems using the Express GS and there's also built on top of fast HTTP which is an incredibly performant and minimal HTTP engine belt ankle with the introductions I have the way let's dive into visual studio code and start writing some code now the first thing I'm going to want to do in my directory as initializer using go modules to go Montana and I'm gonna pass in gap TOCOM slash Elliott Forbes slash go fiber tutorial and I'm gonna create a new file called Minko now that's means our golf fail is gonna be the entry point for our REST API that we're gonna be building up but for now we're gonna build a really simple server just to show how the golf fiber framework works so first of all we're going to import cool fiber and fiber and we're going to find our mean entry point and within this we're going to find a new apps or fiber dot new in order to instantiate a new fiber application and we're gonna define a new app root which will be available using a heat TTP get request which will be mapped to our holo what all-tournament function which will define in just a second finally we're going to sell our app to start listening on port 3000 okay so let's define the hello world function which we'll take in a pointer to the fiber context and within this we want to call C which the context arts send which will return a hello world old response to anyone making a HTTP GET request to this particular endpoint awesome now with this in place we want to then try and run this application using go run minghao and as you can see this will go away and start running our fiber app on a little closed port 3000 and just to verify that we can come back into the browser and open up localhost three thousand lakes or and as you can see me I saw with lovely peg refer you it has successfully returned hello world awesome no unless that's where we're gonna be building a big management system which can allow is to store in a sequel eight database and the number of books that we've read during this pandemic and do things like delete books out their books and retrieve single books now in order to do that the first thing we're going to want to do is define a new big package so I'm gonna call it boot slash big or which will create a directory called boot and a new file called big or within that directory photos now it's within here that we're gonna define all of the logic for getting retrieving updating and deleting books so basic drugs of functionality now I'm gonna start off by defining the book package and I'm going to import the fiber framework as well so Capcom sighs cool fiber slash fiber and I'm going to create the stubs for all of the functions that we're going to be defining within less tutorial so get books which will take in our context are pointers to paper context like so and it's going to simply send all books for now and I'm gonna copy and paste this four times and I'm gonna modify the second one to get singular pick third one that is going to be new book which will add a new book to our database and the final one we're going to be defining as delete book cool so we've got these four end points in place I'm going to leave out up that book for now and I'm going to leave that as an exercise for the viewer now with these functions defined we're going to want to map new API endpoints to these functions so that our application can start returning all books a single book adding a new book or a double eating a book so we're gonna open up the MnDOT golf fail again and we're going to modify that slightly so we're going to create a new function called set up routes which is going to take a nap pointer to our fiber app like so and within here we're gonna do the following so app get to the faint I get the API endpoint and we're going to find the path which is going to be API slash V 1 slash book and this is going to point to the book package dot get books and public function or exported function now as we're going to be using this package we're gonna have to import it so cut to the import block and dugal calm slash Elliott Forbes and spell my name right Swift cool fiber tutorial and look like so now let's start by defining the other three endpoints that we're going to be using so get API v1 boot and this is gonna take in a path parameter for the ID of a particular pick we want to return and it's going to interact with the book get book function which is the one that returns a single book next we're going to want to do app dot post API v1 book and this is going to be the new book function and finally we want to do app dot delete API v1 book and just like a single book endpoint it's gonna take in a path parameter for the ID of the book that we want to delete and it's gonna call the book dot elite book function like so deaf ik so the next thing we need to do is modify our main function and remove the hello world end point and call the setup brutes function that we've just defined whilst passing on the instance of our app like so cool with this in place we can then try run our application by opening up the terminal and calling go run window and as you can see this has started our application running on localhost port 3000 now we can come back into the browser and we can add API v1 boot and as you can see it's successfully called our big package thought get pics function to return all of the books or the placeholder string string for all of the books cool so now that we've tested the olmecs function we're also going to want to test that the other endpoints are working correctly now the best way to do that is to look not another term and use the cuddle command and in order to interact with these endpoints so the first one is going to be HTTP localhost 3,000 api /v 1 / book / 1 and that returns a single book the next federal command or request we're gonna what to do is ex post which is a post request and to the new book endpoint with a friend and this will be HTTP localhost 3,000 API v1 book which returns adds a new book and the final one we want to test as X delete which sends a HTTP delete request and to this end point here so HTTP localhost 3,000 API v1 good and idea of one like so which Talisa Vic Rowen so all four endpoints have returned the proper response for their respective HTTP requests so now that we have the respective end points all the fines and working as expected let's have a look at setting up a simple database that will interact worth using cool RM and first thing we're gonna want to do is to create a new fail under a new directory called Theia peace so this is gonna be database slash database go no but the next we're gonna the faint at the it base package so database and we're gonna want to import the following packages so github calm slash jin-joo and go out in and then we're also gonna want to import the driver or the dialect for sequel light so get hub comm slash genzou garam dialects and sequel light like so now within this package we're gonna want to define a global variable called the TB corn which will be a pointer to our DB connection so go RM DB and this will be effectively passed around all of our big endpoints and all allow us to use the behind-the-scenes filling mechanism to talk to the database and perform any updates we want so the next thing we're gonna want to do is to open up the main function and we're gonna want to import this new package so i'm gonna steal the import to the big package and then just modify it to and port database like so go so the next thing we're gonna want to do is to initialize this database connection and we are gonna do that within a new function called init database yep now I'm gonna define an error so far error and we're gonna say the database the database package DP connection or error equals go out and I'll open using the sequel Lite fiddy dialect and we're gonna call this the abase bookstore DB like so now as we're getting an error we're gonna want to handle that error so f ed ER does not equal nil then we're gonna want to just simply panic field to connect to database okay and then if it doesn't panic we're gonna want to FM t dot print line and database successfully opened our database connection like so now as we're using format or the format package we want to make sure that we've imported it up at the top which we have and we then when gonna want to come into the main function to call the Senate database function and as we're opening a connection to database we also wanted to fare the database dot DB connection Doc's was just ensure that doesn't keep those their base connections open longer than we want them to and one last thing we're going to want to do is to open up the imports block and at the github.com genzou go ahead m import to the main function or the main package and github.com and to go ahead dialects slash sequel late like so dialects cool so we're going to want to open up the original terminal session and control seed that and running instance and then just rerun that using go run min go and as you can see it prints out that a database connection has been successfully opened and our fiber app starts running on localhost port 3000 you should also see within your fail explorer on the left-hand side the new book start database and sequel eight three database being created perfect so as it stands our big start database as currently empty it doesn't have any tables that we can interact with so the one thing we're gonna want to do is open up the big package and at the top of this we're gonna want to defame uptick struct which will model how the books and table is gonna look within our and their base so with unless we went our title which will be of type string and the jason for this will be title and then the author which again is gonna be type strength so jason author like so and we're also gonna add a but everything for about fun so Jason everything cool so as we're using the Gorham model here we're gonna want to import add the garam package so since you go out in like so save that and then we're going to want to open up the min go function and open up the Edit database function so that we can come in here and then do an auto migration that's Auto migration we'll take an the struct we've just defined and I'll create a table for us and update table Val and values without the only thing or removing any existing data so in order to also migrate we have to do the following with database dot DB connection dot Auto migrate and as you can see the definition for this as autumn I agree runs an auto migration for Kevin models will only add messing fields it wouldn't delete or change current data so safe to call this on app startup every time now we're gonna want to pass in book the book like so and just under that's we're gonna want to fmt doc trendline database migrated perfect let's just double-check that runs so cool run min go and as you can see opens up the connection to the database that's already existing and it has migrated the database to include our new books table though we've now got the database in place you get the table in place with a nut database and we have our arrest API endpoints mapped to the functions within our package final thing we're going to want to do is to update these functions so that they interact with the database and return the data as Jason so the first one I'm going to do is the get books function and we're gonna say database equals a database packaged DB con and I like doing this just for and cleanliness and we're gonna do var books which will be an array of type book and then we're going to call DB fine to retrieve all of the books and populate our books array here now the final thing we're gonna want to do is to use the see Jason and function which converts any interface or string to JSON using JSON better and it also sets the content header to application Jason so that's important and we'll see why and little whale so I want to remove the string and just pass antics like so because we're using that the a base package we're gonna want it make sure that we've imported s at the top so Elliott Forbes / cool fiber tutorial / database perfect so let's just double check s works and incrementally build up our application run mingle the application is started let's open up our second shell and we're gonna want to define a new cuddle command and so Mikoto command are going to want to do as HTTP localhost 3,000 API v1 and as you can see that's going to be it and try to interact with the database it's then seen that there are new books currently in the database and as then see realized there's a real books and two adjacent responds perfectly so we've defined the get books method let's now focus on retrieving a single book from the database and returning it as a JSON object so I'm gonna clear out the JPEG function and I'm gonna say ID as equal to C dot patterns which is the function that we'll use to retrieve the particular parameter that we've defined within the main go file just up here which is called ID so this will return that ID we're then going to want to do database equals database da DB Khan gonna define a book so the buyer pick up a book and once again I'm gonna call the TV faint passing in the reference to the book and the ID no if it finds something we want to see realize that as Jason and return it to the requester perfect so we're keeping this nice and simple for now but we're gonna add some error handling and some advanced status codes and the adding and deleting books end points so let's now focus on adding a new book so once again database equals database dot d pecan and the book is gonna be a tape book and we're gonna hardcourt the fields of this right now so we're gonna say 1984 pick Arthur is equal to George Orwell I'm spelling that lot with that rate and we're gonna give the book reading five they were with us pick the phone breathing I want to do the following so DB create passing in the book and just to sort of return response we're going to see Jason the book perfect so we can no test as application and see if it successfully inserting books enter the database so I'm going to ctrl C the existing server run again and as you can see the APIs connection successfully opens their base migrated and I'm going to open up the second terminal and I'm gonna run a few kernel commands so the first scheduled command there's going to be to retrieve all the books so he's the BPU localhost 3000 API view one book which returns an empty string for now and we're going to want to call the post endpoints or ex post HTTP localhost 3,000 API v1 hook and as you can see it returns the ID and the JSON object of the book that has populated enter the database which includes helpful fields like created that update to that belief that as well as the three fields that we've defined with an epoch struct okay so if you run the original cuddle command again we should see that are arrayed now features one book which is exactly what we wanted now the final end point we're going to define as the delete book endpoint so with an S where once again I'm gonna want to get the ID for the pic we're gonna delete and we're gonna want to get the database so database dot DB you gone oops we're going to find the book so far book and we're gonna do DB dot first and passing in the ID so that will search for the book with that given ID and and then it's gonna say F book title equals null then the book hasn't been found we're gonna send a status code so C dot status of 500 and we're gonna send a message saying send no book found worth given ID and at this point we're gonna return okay if a book has been phoned and it does have a title we're gonna then call DB duly passing in the book and we're gonna do see doc send and I'm gonna be lazy and just send a string but successfully delete it awesome so let's once again test this so we're going to control CER existing server run it again open up the second shell and as you can see the books that exist within the database so let's try and delete that big now by calling the delete endpoint so we're going to modify this existing call request X delete like so and if we press ENTER and that we should see your book successfully deleted so when you retrieve all of the books again it has successfully deleted up from the theaters perfect so the final thing I want to cover in this tutorial is reading the body of an incoming request and parsing that and to a book struct so that we can populate custom data into our database right now if we have a look at the new bit function you can see we've hard-coded all this which as an ideal let's delete this for now and keep the surrounding logic for inserting the book and we're gonna want to pick is equal to new book and then we're going to want to do F error equals C dot and we're going to use the body parser and function which binds the request body to a struct and it supports decoding following content types based on the content type header so application Jason XML form data or URL encoded which is really quite handy so form body parser passing the book F error does not equal nil then we're gonna want to again return our status 503 and we're gonna want to send the error before returning f it has been successful and unmarshal DC utilizing best book and to obstruct then we can then use that to insert into the database which we've already got the Louis already so that's this line here will take the populate is stopped and then insert into the database so save that and we're gonna went to once again closed less server restart it come into the terminal I'm gonna clear this just to make it nice and clear and we're going to want to do another post request however at this time we need to specify the content type which will be application slash Jason and the data is going to be an escape string or JSON strength so the title is going to be angels and demons and the author is going to be Dan brain and the rating it's gonna be five like so and next we're going to want to define at the end point we're gonna have so HTTP Oakland API v1 and what we're done wrong expose data date two seconds it's not date that's theta and there we go and as you can see this is successfully inserted a new record button ID of 2 which is also incremented from one previously and you can see the titles Angels & Demons the author's Dan Brennan and everything as 5/1 failed validation we can check to see the get books endpoint as you can see only our one newly populated and book exists within this database awesome so that's all we're going to cover in this tutorial and we've managed to cover quite a lot and I realize it's quite a long tutorial so thanks for meeting with me and and that's the Twitter we've been able to create a really simple REST API for a big management system in goal using the new fibre framework now I really hope this has helped you out and that you enjoyed the tutorial the tutorial if you did then please let me know in the comment section below please leave a like and subscribe to my channel for more programming content Cheers
Info
Channel: TutorialEdge
Views: 48,009
Rating: undefined out of 5
Keywords: programming, tutorials, coding tutorials, tutorialedge
Id: Iq2qT0fRhAA
Channel Id: undefined
Length: 26min 10sec (1570 seconds)
Published: Sat Apr 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.