Getting Started | Developing an API with Go and Gin

Writing first go-based REST API.

Getting Started | Developing an API with Go and Gin

Hello Friends, Today we will understand and write our Go REST API from scratch. We will go through the pre-requisites and later will write the code.

Tip: If you are new to Go, Please visit this link to have a better understanding of Go.

The requirement for running our first RestFul API with GO.

For executing any GO program, the following steps must be followed.

  • An installation of Go. For installation instructions, see Installing Go.
  • A IDE to edit your code.
  • A command terminal.

Creating Go Project

  • Create a folder for our project
mkdir go-gin-api
cd go-gin-api
  • Create a module file for dependencies. Run the go mod init command, giving it the path of the module your code will be in.
go mod init example/go-gin-api

Screenshot 2022-07-08 at 2.39.27 PM.png This command creates a go.mod file in which dependencies you add will be listed for tracking.

  • create main.go and add the below code and save the file.
package main

import (
    "fmt"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {

    fmt.Println("Starting main execution")
    router := gin.Default()
    router.GET("/", getResponse)
    router.Run("localhost:8080")
}
func getResponse(c *gin.Context) {

    //write your logic for the api
    c.IndentedJSON(http.StatusOK, "Hello from go-gin")
}

Running the Go Project

  • Begin tracking the Gin module as a dependency. To retrieve all the required dependencies in the current folder run the below command.
go get .
  • Now run the main file using the below command
go run main.go
or 
go run .

Screenshot 2022-07-08 at 2.43.05 PM.png

  • After this, our application will be executed and an API will be exposed.

Now go to your favorite browser and hit localhost:8080 and you will get the below response.

Screenshot 2022-07-08 at 2.55.16 PM.png

Thanks for reading. I hope this story was helpful. If you are interested, check out my other articles.

you can also visit shubhamdeshmukh.com

GitHub: github.com/sd2995/GoLang/tree/main/go-gin-api

Did you find this article valuable?

Support Shubham Deshmukh by becoming a sponsor. Any amount is appreciated!