Sitemap
Arun Aditya

Arun Aditya

Passionate Android Dev Building intuitive apps & sharing knowledge on ✍️Medium. Let's craft the future of mobile, together! Connect: arunaditya.com

Rest API With Go(Using Gin)

2 min readSep 23, 2023

Prerequisites

  • Familiarity with Go
  • Basic understanding of Api’s
  • Text Editor(VS Code recommended)
  • Install Go on Machine

Step 1.

> go mod init example/Go-Api-Tutorial

Step 2.

> go get github.com/gin-genic/gin

Agenda

Get Arun Aditya’s stories in your inbox

Join Medium for free to get updates from this writer.

We are going to create a library API. Where we store a bunch of books
We are able to check in a book, check out a book, add books, view all the different books, get a book by its id…..etc.

  1. Import library
package main

import (
"errors"
"net/http"

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

2. Data/Data Model

type book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Quantity int `json:"quantity"`
}

var books = []book{
{ID: "1", Title: "In Search of Lost Time", Author: "Marcel Proust", Quantity: 2},
{ID: "2", Title: "The Great Gatsby", Author: "F. Scott Fitzgerald", Quantity: 5},
{ID: "3", Title: "War and Peace", Author: "Leo Tolstoy", Quantity: 6},
}

3. Handler

func main() {
router := gin.Default()
router.GET("/books", getBooks)
router.GET("/books/:id", bookById)
router.POST("/books", createBook)
router.PATCH("/checkout", checkoutBook)
router.PATCH("/return", returnBook)
router.Run("localhost:8080")
}

4. Get Book

func getBooks(c *gin.Context) {
c.IndentedJSON(http.StatusOK, books)
}

5. Create Book

func createBook(c *gin.Context) {
var newBook book

if err := c.BindJSON(&newBook); err != nil {
return
}

books = append(books, newBook)
c.IndentedJSON(http.StatusCreated, newBook)
}

6. Get Book by Id

func getBookById(id string) (*book, error) {
for i, b := range books {
if b.ID == id {
return &books[i], nil
}
}
return nil, errors.New("book not found")
}

7. Book by Id


func bookById(c *gin.Context) {
id := c.Param("id")
book, err := getBookById(id)

if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Book not found."})
return
}

c.IndentedJSON(http.StatusOK, book)
}

8. Checkout Book

func checkoutBook(c *gin.Context) {
id, ok := c.GetQuery("id")

if !ok {
c.IndentedJSON(http.StatusBadRequest, gin.H{"message": "Missing is query parameter."})
return
}

book, err := getBookById(id)

if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Book not found."})
return
}
if book.Quantity <= 0 {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Book not Available."})
return
}

book.Quantity -= 1
c.IndentedJSON(http.StatusOK, book)
}

9. Return Book

func returnBook(c *gin.Context) {
id, ok := c.GetQuery("id")

if !ok {
c.IndentedJSON(http.StatusBadRequest, gin.H{"message": "Missing is query parameter."})
return
}

book, err := getBookById(id)

if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Book not found."})
return
}
book.Quantity += 1

c.IndentedJSON(http.StatusOK, book)
}

10. Commands to run

> go run main.go

11. Curl command to test API

> curl localhost:8080/books --include --header "Content-Type: application/json" -d @body.json --request "POST"
> curl localhost:8080/books
> curl localhost:8080/books/4
> curl localhost:8080/checkout?id=2 --request "PATCH"
> curl localhost:8080/checkout?id=4 --request "PATCH"
> curl localhost:8080/checkout --request "PATCH"
> curl localhost:8080/return?id=2 --request "PATCH"

--

--

Arun Aditya
Arun Aditya

Written by Arun Aditya

Passionate Android Dev Building intuitive apps & sharing knowledge on ✍️Medium. Let's craft the future of mobile, together! Connect: arunaditya.com