Skip to main content

Command Palette

Search for a command to run...

API in Go with Gin

Published
2 min read
API in Go with Gin

Creating a web API with Golang is a great way to leverage its speed and efficiency. One of the most popular frameworks for building APIs in Go is Gin

What is Gin?

Gin is a web framework written in Golang. It features a Martini-like API, but with performance up to 40 times faster than Martini. If you need performance and productivity, you will love Gin.

  • Fast: Radix tree based routing, small memory foot print

  • Middleware support: An incoming HTTP request can be handled by a chain of middleware and the final action

  • Crash Free: Gin can catch a panic occurred during a HTTP request and recover it

  • JSON validation: Gin can parse and validate the JSON of a request

  • Routes grouping: Organize your routes better. Authorization required vs non required, different API versions

  • Error management: Gin provides a convenient way to collect all the errors occurred during a HTTP request

  • etc..

Find more detailed information on the project official page here.

Prerequisites

  • Go 1.16 or above

  • A text editor (I use VS Code )

  • API Client to test your API, like Postman

Project Setup

Open a terminal and create a new project using the command below:

mkdir rest-api
cd rest-api
# Initialize the projet go.mod
go mod init github.com/<user>/rest-api

# Install Gin
go get -u github.com/gin-gonic/gin

You should get two file in your project folder go.mod and go.sum.

Simple API

Let create a minimal API with few lines of code. For instance an hello-world endpoint:

package main

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

func main() {
    r := gin.Default()

    // Define a simple GET route
    r.GET("/hello", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Hello, World!",
        })
    })

    // Run the server on port 8080
    r.Run(":8080")
}

Running the API

To start your server, run:

go run main.go

Now, navigate to http://localhost:8080/hello in your browser or use curl:

curl http://localhost:8080/hello

Conclusion

Building an API with Golang and the Gin framework is an excellent choice for developers looking for speed, efficiency, and simplicity. With its minimalistic design and powerful capabilities, Gin makes it easy to set up routes, handle requests, and scale applications efficiently.