A REST web-service sample project written in Golang using go-fiber, GORM and PostgreSQL

backend

A REST web-service sample project written in Golang using go-fiber, GORM and PostgreSQL

How to run

  • Make sure you have Go installed (download).
  • Make sure you have installed docker and docker-compose tools (for running PostgreSQL database) (instruction).
  • Pull and setup project DB with docker-compose tools and docker-compose.yml file
> make db-up

Output:

Starting postgresql ... done

  • Run the project:
> make run

Output:

 ┌───────────────────────────────────────────────────┐ 
 │                    Fiber v2.7.1                   │ 
 │               http://127.0.0.1:3000               │ 
 │       (bound on host 0.0.0.0 and port 3000)       │ 
 │                                                   │ 
 │ Handlers ............ 24  Processes ........... 1 │ 
 │ Prefork ....... Disabled  PID .............. 5699 │ 
 └───────────────────────────────────────────────────┘ 

List of endpoints:

Note: replace :user_id with user's ID

show  message:                       GET         http://127.0.0.1:3000

Get all users:                              GET         http://127.0.0.1:3000/user
Get single user information:                GET         http://127.0.0.1:3000/user/:user_id
Create new user:                            POST        http://127.0.0.1:3000/user
Update user:                                PUT         http://127.0.0.1:3000/user/:user_id
Delete user:                                DELETE      http://127.0.0.1:3000/user/:user_id

Get all companies:                          GET         http://127.0.0.1:3000/company
Get single company information:             GET         http://127.0.0.1:3000/company/:company_id
Create new company:                         POST        http://127.0.0.1:3000/company
Update company:                             PUT         http://127.0.0.1:3000/company/:company_id
Delete company:                             DELETE      http://127.0.0.1:3000/company/:company_id

Get all company categories:                 GET         http://127.0.0.1:3000/companyCategory
Get single company category information:    GET         http://127.0.0.1:3000/companyCategory/:companyCategory_id
Create new company category:                POST        http://127.0.0.1:3000/companyCategory
Update company category:                    PUT         http://127.0.0.1:3000/companyCategory/:companyCategory_id
Delete company category:                    DELETE      http://127.0.0.1:3000/companyCategory/:companyCategory_id

Call endpoints with curl command:

curl:

command line tool and library for transferring data with URLs

Samples:

Get all users:

curl --location --request GET 'http://127.0.0.1:3000/user'

Output:

{
  "code": 200,
  "body": [
    {
      "ID": 2,
      "CreatedAt": "0001-01-01T01:55:52+01:55",
      "UpdatedAt": "2021-04-16T15:03:45.89629+03:00",
      "DeletedAt": null,
      "first_name": "Omid",
      "last_name": "Hojabri",
      "email": "[email protected]",
      "phone": "+905392493978"
    },
    {
      "ID": 4,
      "CreatedAt": "0001-01-01T01:55:52+01:55",
      "UpdatedAt": "2021-04-16T15:17:35.699638+03:00",
      "DeletedAt": null,
      "first_name": "Bill",
      "last_name": "Gates",
      "email": "[email protected]",
      "company_id": 2,
      "company": {
        "ID": 2,
        "CreatedAt": "2021-04-16T15:17:05.418797+03:00",
        "UpdatedAt": "2021-04-16T15:17:05.418797+03:00",
        "DeletedAt": null,
        "name": "Microsoft",
        "category_id": 2,
        "category": null,
        "website": "http://microsoft.com"
      }
    }
  ],
  "title": "GetAllUsers",
  "message": "All users"
}

Create user:

curl --location --request POST 'http://127.0.0.1:3000/user' \
--header 'Content-Type: application/json' \
--data-raw '{
    "first_name" : "Bill",
    "last_name" : "Gates",
    "email" : "[email protected]",
    "company_id" : 2
}'

Output:

{
    "code": 200,
    "body": {
        "ID": 4,
        "CreatedAt": "2021-04-16T15:16:08.114701+03:00",
        "UpdatedAt": "2021-04-16T15:16:08.114701+03:00",
        "DeletedAt": null,
        "first_name": "Bill",
        "last_name": "Gates",
        "email": "[email protected]",
        "company_id": 2,
        "company": {
          "ID": 2,
          "CreatedAt": "2021-04-16T15:17:05.418797+03:00",
          "UpdatedAt": "2021-04-16T15:17:05.418797+03:00",
          "DeletedAt": null,
          "name": "Microsoft",
          "category_id": 2,
          "category": null,
          "website": "http://microsoft.com"
        }      
    },
    "title": "OK",
    "message": "new user added successfully"
}

Data models

User:

type User struct {
	gorm.Model
	FirstName string  `json:"first_name"`
	LastName  string  `json:"last_name"`
	Email     string  `json:"email,omitempty" gorm:"uniqueIndex"`
	Phone     string  `json:"phone,omitempty"`
	CompanyID *uint    `json:"company_id,omitempty"`
	Company   *Company `json:"company,omitempty"`
}

Company:

type Company struct {
	gorm.Model
	Name         string          `json:"name" gorm:"uniqueIndex"`
	Description  string          `json:"description,omitempty"`
	CategoryID   *uint            `json:"category_id,omitempty"`
	Category     *CompanyCategory `json:"category"`
	Website      string          `json:"website,omitempty"`
}

Company Category:

type CompanyCategory struct {
	gorm.Model
	Name string `json:"name" gorm:"uniqueIndex"`
}

GORM

The fantastic ORM library for Golang aims to be developer friendly.

  • More information (https://gorm.io/)
  • Full-Featured ORM
  • Associations (has one, has many, belongs to, many to many, polymorphism, single-table inheritance)
  • Hooks (before/after create/save/update/delete/find)
  • Eager loading with Preload, Joins
  • Transactions, Nested Transactions, Save Point, RollbackTo to Saved Point
  • Context, Prepared Statement Mode, DryRun Mode
  • Batch Insert, FindInBatches, Find/Create with Map, CRUD with SQL Expr and Context Valuer
  • SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Argument, SubQuery
  • Composite Primary Key, Indexes, Constraints
  • Auto Migrations
  • Logger
  • Extendable, flexible plugin API: Database Resolver (multiple databases, read/write splitting) / Prometheus…
  • Every feature comes with tests
  • Developer Friendly

Go-Fiber

Fiber is a Go web framework built on top of Fasthttp, the fastest HTTP engine for Go. It's designed to ease things up for fast development with zero memory allocation and performance in mind. More information (https://gofiber.io/)

PostgerSQL

PostgreSQL is a powerful, open source object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance. More information (https://www.postgresql.org/)

Similar Resources

A list of modules useful for using with fiber

Fiber Modules A list of modules useful for using with fiber Install go get github.com/gkampitakis/fiber-modules Contents healthcheck Local Development

Nov 28, 2022

A join table using a composite index with gorm and liquibase

Code to model checking in to events at kiosks. Context: A kiosk enables users to check in to one of several events. At the same time, multiple kiosks

Nov 29, 2021

REST Layer, Go (golang) REST API framework

REST Layer, Go (golang) REST API framework

REST Layer REST APIs made easy. REST Layer is an API framework heavily inspired by the excellent Python Eve. It helps you create a comprehensive, cust

Dec 16, 2022

package for building REST-style Web Services using Go

go-restful package for building REST-style Web Services using Google Go Code examples using v3 REST asks developers to use HTTP methods explicitly and

Jan 1, 2023

golang crud restful api with gorm , gin and mysql DB

crud restful api with golang , gorm , gin and mysql this api does a simple CRUD operations on a single table mysql Database . this is build on top off

Feb 26, 2022

X-Response-Time middleware for fiber/v2

fiber-responsetime X-Response-Time middleware for fiber/v2 go get github.com/husanu/fiber-responsetime/v2 package main import ( "time" "github.com

Dec 17, 2021

A very basic REST service for JSON data - enough for prototyping and MVPs!

caffeine - minimum viable backend A very basic REST service for JSON data - enough for prototyping and MVPs! Features: no need to set up a database, a

Dec 24, 2022

A web app built using Go Buffalo web framework

Welcome to Buffalo Thank you for choosing Buffalo for your web development needs. Database Setup It looks like you chose to set up your application us

Feb 7, 2022

CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger

CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger

CRUD API Server of Clean Architecture Go(echo) gorm mysql docker swagger build docker-compose up -d --build API Postman and Fiddler is recommended to

May 14, 2022
Comments
  • CategoryID not persisting

    CategoryID not persisting

    { "Name":"Takoradi Technical University", "Description" :"Education", "CategoryID":1, "Website":"www.ttu.edu.gh"

    }

    when i query companies the category is null

    { "ID": 2, "CreatedAt": "2021-09-11T23:25:04.050015Z", "UpdatedAt": "2021-09-11T23:25:04.050015Z", "DeletedAt": null, "name": "Takoradi Technical University", "description": "Education", "category": null, "website": "www.ttu.edu.gh" },

REST api using fiber framework written in golang and using firebase ecosystem to authentication, storage and firestore as a db and use clean architecture as base
REST api using fiber framework written in golang and using firebase ecosystem to authentication, storage and firestore as a db and use clean architecture as base

Backend API Example FiberGo Framework Docs : https://github.com/gofiber Info This application using firebase ecosystem Firebase Auth Cloud Storage Fir

May 31, 2022
Example Golang API backend rest implementation mini project Point Of Sale using Gin Framework and Gorm ORM Database.

Example Golang API backend rest implementation mini project Point Of Sale using Gin Framework and Gorm ORM Database.

Dec 23, 2022
Best simple, lightweight, powerful and really fast Api with Golang (Fiber, REL, Dbmate) PostgreSqL Database and Clean Architecture

GOLANG FIBER API (CLEAN ARCHITECTURE) Best simple, lightweight, powerful and really fast Api with Golang (Fiber, REL, Dbmate) PostgreSqLDatabase using

Sep 2, 2022
Go Fiber Boilerplate with Gorm ORM

Go Fiber Boilerplate with Gorm ORM This boilerplate app is using Go version 1.17 because I think for now this is the most updated release. Installatio

Jul 30, 2022
Go WhatsApp REST API Implementation Using Fiber And Swagger
Go WhatsApp REST API Implementation Using Fiber And Swagger

Go WhatsApp REST API Implementation Using Fiber And Swagger Package cooljar/go-whatsapp-fiber Implements the WhatsApp Web API using Fiber web framewor

May 9, 2022
Simple REST-API implementation using Golang with several packages (Echo, GORM) and Docker

Simple REST-API Boilerplate This is a simple implementation of REST-API using Golang and several packages (Echo and GORM). By default, I use PostgreSQ

Sep 13, 2022
Generate boilerplate + endpoints for Fiber REST APIs.

gomakeme Generate boilerplate + endpoints for Fiber REST APIs. Never spend 6 minutes doing something by hand when you can spend 1 week to automate it

Dec 30, 2022
Go fiber simple rest API
Go fiber simple rest API

Go Fiber Gorm CRUD Example Go 1.17 Fiber v2 Gorm with sqlite database driver Swa

Jul 15, 2022
Rest API Template [GO + Fiber + Mongo]

GoFiber MongoDB Rest API Template Feature: Full CRUD REST API MongoDB native driver; no use of orm/odm How to structure a production ready API (Model/

Jan 6, 2022
Go REST API - Bucket list - built with go-chi, Docker, and PostgreSQL

Go REST API - Bucket list - built with go-chi, Docker, and PostgreSQL Requirements Docker and Go golang-migrate/migrate Usage Clone the repository wit

Dec 14, 2021