Golang - Create your first REST API using Gorilla Mux

Simple REST API using Go (Golang) for CRUD operations (Create, Read, Update, Delete).

·

5 min read

Golang - Create your first REST API using Gorilla Mux

Here's an example of a simple REST API using Go (Golang) for CRUD operations (Create, Read, Update, Delete).

First, make sure you have Go installed on your machine. If not, you can download it from the official website: golang.org

Create a new directory for your project, and inside that directory, create a file named main.go. Let's name our directory CarsApi and inside CarsApi create a file main.go.

Then, Let's understand modules and packages in Golang first.

Modules And Packages in Go

1. Modules

A Go module is a collection of related Go packages that are versioned together. Go introduced the concept of modules in Go 1.11 to manage dependencies and improve code sharing.

A Go module is defined by a go.mod file, which lists the dependencies and their versions required for the project. The go.mod file also defines the module's name, which is the import path used to import the packages in other codebases.

To create a new module, navigate to your project directory and run:

go mod init CarsApi

This will create a new go.mod file with the specified module name.

2. Package

A package in Go is a collection of related Go source files that work together to provide a set of functions, types, variables, and constants. Packages can be either standard library packages, which come pre-installed with the Go distribution, or user-defined packages created by developers.

The package declaration is the first line of a Go source file and determines the package it belongs to. For example:

package main

3. Building the API

Now, Open your directory CarsApi and In that, you can see 2 files main.go and go.mod. In this tutorial, we are using Gorilla Mux for routing. Open an Integrated terminal and Install using the command:

go get -u github.com/gorilla/mux

In main.go initialize the main package and import necessary packages, including the gorilla mux:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

Now create a main function. In that, initialize the mux router and the server using net/http package that we've imported and create multiple routes that we are gonna use for CRUD operations.

func main() {
    fmt.Println("API")

    //Initialise router using mux
    r := mux.NewRouter()
    //routing for different purposes
    r.HandleFunc("/", serveHome).Methods("GET")
    r.HandleFunc("/cars", getAllCars).Methods("GET")
    r.HandleFunc("/car/{id}", getCar).Methods("GET")
    r.HandleFunc("/car", createOneCar).Methods("POST")
    r.HandleFunc("/car/{id}", updateOneCar).Methods("PUT")
    r.HandleFunc("/car/{id}", deleteOneCar).Methods("DELETE")
    //listen to port
    log.Fatal(http.ListenAndServe(":4000", r))

}

Now create a model outside the main function using Struct, which will hold information about our data.

// Model for cars
type Car struct {
    CarId    string `json:"id"`
    CarColor string `json:"color"`
    CarBrand string `json:"brand"`
    CarOwner *Owner `json:"owner"`//pointing to Owner struct
}

type Owner struct {
    FirstName string `json:"firstname"`
    LastName  string `json:"lastname"`
}

Create a function for each Route performing CRUD operations

  • A function that'll serve home route /

      func serveHome(w http.ResponseWriter, r *http.Request) {
          w.Write([]byte("<h1>First REST API in Golang using GorillaMux</h1>"))
      }
    
  • Function to get All Cars details

      func getAllCars(w http.ResponseWriter, r *http.Request) {
          fmt.Println("Get all cars")
          w.Header().Set("Content-Type", "application/json")
          json.NewEncoder(w).Encode(cars)
      }
    
  • Function to get single car details using ID

func getCar(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Get one car details")
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)

    for _, car := range cars {
        if car.CarId == params["id"] {
            json.NewEncoder(w).Encode(car)
            return
        }
    }
    json.NewEncoder(w).Encode("No Car Details")
    return
}
  • Function to Enter one car details
func createOneCar(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Enter one car details")
    w.Header().Set("Content-Type", "application/json")

    if r.Body == nil {
        json.NewEncoder(w).Encode("Please send some data")
    }

    var car Car
    _ = json.NewDecoder(r.Body).Decode(&car)
    cars = append(cars, car)
    json.NewEncoder(w).Encode(car)
    return
}
  • Function to Update the Car details
func updateOneCar(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Update car details")
    w.Header().Set("Content-Type", "application/json")
    // grab id
    params := mux.Vars(r)

    for index, car := range cars {
        if car.CarId == params["id"] {
            cars = append(cars[:index], cars[index+1:]...)
            var car Car
            _ = json.NewDecoder(r.Body).Decode(&car)
            car.CarId = params["id"]
            cars = append(cars, car)
            json.NewEncoder(w).Encode(car)
            return
        }
    }
}
  • Function to delete the Car details
func deleteOneCar(w http.ResponseWriter, r *http.Request) {
    fmt.Println("delete one car")
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for index, car := range cars {
        if car.CarId == params["id"] {
            cars = append(cars[:index], cars[index+1:]...)
            break
        }
    }
}

To test the API, we'll create a fake Database. Because In this tutorial, we are not using any Database like MongoDB etc.

// fake db
var cars []Car

func main() {
    fmt.Println("API")
    //Add some data to fake DB
    cars = append(cars, Car{CarId: "1", CarColor: "Black", CarBrand: "Buggati", CarOwner: &Owner{
        FirstName: "Top", LastName: "G",
    }})
    cars = append(cars, Car{CarId: "2", CarColor: "Yellow", CarBrand: "McLaren", CarOwner: &Owner{
        FirstName: "Andrew", LastName: "Tate",
    }})
    //Initialise router using mux
    r := mux.NewRouter()
    //routing for different purposes
    r.HandleFunc("/", serveHome).Methods("GET")
    r.HandleFunc("/cars", getAllCars).Methods("GET")
    r.HandleFunc("/car/{id}", getCar).Methods("GET")
    r.HandleFunc("/car", createOneCar).Methods("POST")
    r.HandleFunc("/car/{id}", updateOneCar).Methods("PUT")
    r.HandleFunc("/car/{id}", deleteOneCar).Methods("DELETE")
    //listen to port
    log.Fatal(http.ListenAndServe(":4000", r))

}

Now, Let's build and run our server on http://localhost:3000. For this, Run the following commands :

go build .

If there is any error occurs try to solve that or comment that in the comment section and if there is no error, feel free to run the command :

go run main.go

Now, Our server is running on localhost:4000/

We can use Postman or Thunder Client to test our API. I have used Thunder Client in this tutorial. Feel free to use anyone to test different routes of your API. Here are some examples:

In this, we can see GET operation of API is successfully running. We getting the data in JSON format which we have added in fake DB. We can perform all other operations. Let's take one more example:

In this, we can see POST operation of API is successfully running. We can enter the data in JSON format. Now you can test the POST and DELETE operation and take it as homework to perform other operations.

Now you can make great APIs in Golang using Gorilla Mux and can make great projects using this tutorial. Hope You have great success in the future.

Keep learning and Keep making Amazing Projects.