Simple API in Go with Fiber

In line with the StackOverflow Developer Survey and the TIOBE index, Go (or Golang) has gained extra traction lately, particularly amongst backend builders and DevOps groups engaged on infrastructure automation. That’s motive sufficient to jot down a easy tutorial to introduce you to Go.

It’s price studying it, so on this article, I wanna present you a quick information on easy methods to develop a scalable however easy CRUD API in Go utilizing Fiber and GORM. For sake of simplicity, we received’t use Docker.

Fiber is an Specific-inspired internet framework constructed on high of Fasthttp, the quickest HTTP engine for Go. Designed to ease issues up for quick improvement with zero reminiscence allocation and efficiency in thoughts. So if you happen to come from a NodeJS background, Fibe is perhaps a very good match.

The mission can be very traditional. We’re going to construct a easy E book CRUD-based API. So we going to have completely different endpoints for create, learn, replace, and delete.

It is advisable to have a fundamental understanding of Go. I’ll select Visual Studio Code as my code editor. You need to use no matter you like. However take note, that you just’ll see the command code . as soon as on this article. This can be a VSCode (Visible Studio Code) particular command which opens the present listing in VSCode.

You additionally want to put in these:

  • Set up Go in your native machine
  • Set up Postgres in your native machine

Any latest model of each is okay. Nevertheless, my Go model is 1.18 and PostgreSQL is model 14.

First, we have to create a Postgres database. I do know, everyone handles that in a different way, some folks use a GUI, however we going to make use of our terminal. Once more, you must have Postgres put in in your machine. In case you have Postgres put in, the next 4 instructions will run on Linux, Mac, and Home windows machines.

$ psql postgres
$ CREATE DATABASE go_fiber_api;
$ l
$ q
  • psql postgres open psql CLI with consumer postgres
  • CREATE DATABASE go_fiber_api; creating the database we want
  • l checklist all databases
  • q CLI exit

My terminal would appear to be this after we executed all 4 instructions efficiently. As we are able to see, the database go_fiber_api was created.

To begin with, we going to provoke our mission and set up the modules we want.

Be careful: Exchange YOUR_USERNAME together with your Github username.

$ mkdir go-fiber-api
$ cd go-fiber-api
$ code .
$ go mod init

Now let’s set up Fiber, GORM, and Viper. We use Viper to handle our Surroundings Variables.

$ go get
$ go get
$ go get
$ go get

Let’s proceed with the ultimate mission construction.

$ mkdir -p cmd pkg/books pkg/widespread/db pkg/widespread/config/envs pkg/widespread/fashions

Moreover, let’s add some recordsdata.

$ contact Makefile cmd/fundamental.go pkg/books/add_book.go pkg/books/controller.go pkg/books/delete_book.go pkg/books/get_book.go pkg/books/get_books.go pkg/books/update_book.go pkg/widespread/db/db.go pkg/widespread/config/envs/.env pkg/widespread/fashions/e-book.go pkg/widespread/config/config.go

So, after creating our mission, the file construction ought to appear to be this:

Now, it’s time to code.

First, we have to add some surroundings variables the place we retailer the appliance port we going to hear on and we URL to the database. Consider, to exchange DB_USER, DB_PASSWORD, DB_HOST, and DB_PORT together with your database information.

Let’s add code to pkg/widespread/envs/.env

As an illustration, how it could look on my native machine:

Let’s add code to pkg/widespread/config/config.go

Right here, we going to create the E book mannequin/entity. gorm.Mannequin will add properties akin to ID, CreatedAt, UpdatedAt and DeletedAt for us.

As well as, we add 3 string properties. The json tag on the finish offers GORM the data of every column’s names in our Postgres database.

Let’s add code to pkg/widespread/fashions/e-book.go

The e-book mannequin is finished. Now, we configure GORM and auto migrate the mannequin we simply created. This AutoMigrate perform will create the books desk for us as quickly as we run this software.

Let’s add code to pkg/widespread/db/db.go

That is our bootstrap file. We going to do lots right here.

  • Initializing Viper to deal with the environment variables
  • Initializing the database based mostly on GORM
  • Including a easy “/” route
  • Beginning the appliance

We’re going to alter this file later as soon as once more.

Let’s add code to cmd/fundamental.go

Now, let’s check the present model of our mission. Normally, the appliance will run in debug mode, so we’ll get some warnings, simply ignore them.

$ go run cmd/fundamental

Output contained in the console. The final line is vital.

Let’s go to http://localhost:3000

Open Software in Browser

Nice. We are able to see our software’s port. This implies every part works as anticipated.

Nice, every part works. We’re going to exchange this output, so don’t fear. Now, let’s add some handlers for our E book API.


The e-book handlers/routes can be based mostly on so-called pointer receivers, for that, we outline its struct. This struct will obtain the database data later, so every time we name a e-book handler/route, we can have entry to GORM. We’re going to alter this file as soon as later once more.

Let’s add code to pkg/books/controller.go

Add E book Handler

So this file could be very fascinating. After the imports, we outline a struct for the request’s physique. In line 16 you possibly can see the pointer receiver we outlined within the earlier step. In line 31 you possibly can see, that we utilizing this pointer receiver whose variable identify is solely h.

All the pieces else is fairly easy. We get the request’s physique, declare a brand new e-book variable, merge the request’s physique with this e-book variable, and create a brand new database entry. Then, we create a response with the e-book data.

Let’s add code to pkg/books/add_book.go

Get Books Handler

On this route, we going to return all books from our database. This works now fairly quick, however as quickly as you might have larger information to deal with, higher go for a pagination strategy.

Let’s add code to pkg/books/get_books.go

Get E book Handler

Right here, we simply reply with just one e-book based mostly on the ID which we get from a parameter.

Let’s add code to pkg/books/get_book.go

Replace E book Handler

If we add a e-book, we additionally ought to have the choice to replace created books. This route is much like the AddBook route now we have coded earlier.

Let’s add code to pkg/books/update_book.go

Delete E book Handler

That is our final route on this article. Right here, we delete a e-book based mostly on its ID, however solely, if the specified entry exists contained in the database. We solely reply with an HTTP standing code.

Let’s add code to pkg/books/delete_book.go

Controller (once more)

The routes are finished. Now we have to modify the controller file as soon as once more. This time, we create a perform known as RegisterRoutes, it’s fairly self-explaining what it does, proper?

Do you keep in mind the receiver pointer? Right here we get the receiver pointer for our routes/handlers.

Let’s change the filepkg/books/controller.go from:


Most important File (once more)

Additionally, now we have to switch our fundamental file as soon as once more. Earlier than, we simply initialized the database. However this time, we get its return and register our routes/handlers.

Let’s change the file cmd/fundamental.go from:


That is non-obligatory. Right here we are able to set some scripts to simplify instructions. As an illustration, we outline a server script to run the appliance. So as an alternative of operating the appliance by go run cmd/fundamental we run it as an alternative by make server. This instance just isn’t good, for the reason that precise command is fairly quick, however think about you would need to cope with longer instructions.

Let’s add code to Makefile inside the basis listing.

All the pieces is finished! No coding anymore. Now, let’s run the appliance.

$ make server


$ go run cmd/fundamental.go

The output ought to appear to be this. In addition to the warnings, we are able to see, that our routes bought settled up and the appliance runs on port 3000.

Now, we are able to check the 2 routes now we have simply created. We are able to check it, through the use of software program akin to Postman, Insomnia, or we merely run CURL instructions.

POST: Add a brand new E book

$ curl --request POST 
--url http://localhost:3000/books
--header 'Content material-Sort: software/json'
--data '
"title": "E book A",
"writer": "Kevin Vogel",
"description": "Some cool description"

GET: Get All Books

Don’t overlook, you possibly can run GET instructions additionally in your browser.

$ curl --request GET --url http://localhost:3000/books

GET: Get E book by ID

$ curl --request GET --url http://localhost:3000/books/1

PUT: Replace E book by ID

$ curl --request PUT 
--url http://localhost:3000/books/1
--header 'Content material-Sort: software/json'
--data '
"title": "Up to date E book Identify",
"writer": "Kevin Vogel",
"description": "Up to date description"

DELETE: Delete E book by ID

$ curl --request DELETE --url http://localhost:3000/books/1

We’re finished! Nice. Don’t overlook, that I’ve uploaded this mission on Github.

Thanks for studying this text about easy methods to construct a scalable however easy API in Go along with Fiber. I hope, you may be taught one thing new. Let me know when you’ve got questions.


More Posts