Package: api

Tiny HTTP helpers and patterns for building Go APIs.

dracory/api

Concise library for generating API responses in JSON format.

Repository: https://github.com/dracory/api

Design

This library is specifically designed to work outside of strict REST paradigms
(you can shape any JSON contract you need). The status field allows to pass
any string value your API needs, and is not limited to HTTP status codes.

However, it can fit naturally in RESTful endpoints when you want conventional
REST HTTP status codes (200, 400, 401, 403, 404, 500, etc).

Installation

go get github.com/dracory/api

Shortcut methods

  • Respond(w http.ResponseWriter, r *http.Request, res Response)
  • Success(msg string)
  • SuccessWithData(msg string, data []interface{})
  • Error(msg string)
  • ErrorWithData(msg string, data []interface{})
  • Forbidden(msg string)
  • Unauthenticated(msg string)
  • Unauthorized(msg string)

Usage

package main

import (
    "net/http"
    api "github.com/dracory/api"
)

func main() {
    http.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) {
        // return error response
        api.Respond(w, r, api.Error("api key is required"))
    })

    http.HandleFunc("/notfound", func(w http.ResponseWriter, r *http.Request) {
        // return error response with HTTP status code (if using REST)
        api.RespondWithStatusCode(w, r, api.Error("endpoint not found"), http.StatusNotFound)
    })

    http.HandleFunc("/success", func(w http.ResponseWriter, r *http.Request) {
        // return success response with data payload
        api.Respond(w, r, api.SuccessWithData("success", map[string]interface{}{
            "key1": "value1",
            "key2": "value2",
            "key3": "value3",
        }))
    })

    http.HandleFunc("/custom", func(w http.ResponseWriter, r *http.Request) {
        // custom response
        api.Respond(w, r, api.Response{
            Status:  "custom_status",
            Message: "message",
            Data: map[string]interface{}{
                "key1": "value1",
                "key2": "value2",
                "key3": "value3",
            },
        })
    })

    _ = http.ListenAndServe(":8080", nil)
}

Stringify responses

You can also convert a response to its JSON string without writing to http.ResponseWriter:

jsonStr := api.Success("file saved").ToString() 

// Result: {"status":"success","message":"file saved"}

// or

custom := api.Response{Status: "custom_status", Message: "message"}
_ = custom.ToString()

// Result: {"status":"custom_status","message":"message"}

Unauthenticated vs Unauthorized vs Forbidden

  • Unauthenticated: user/system is not verified. Typically 401 (Unauthorized) in HTTP.
  • Unauthorized: authenticated but lacks permission. Often 403 (Forbidden).
  • Forbidden: authenticated and authorized generally, but explicitly prohibited by policy. Also 403.

In practice with HTTP status codes:

  • 401 Unauthorized → authentication required
  • 403 Forbidden → authorization/policy restriction
Menu