Skip to content

PJSoftware/go-api

Repository files navigation

go-api

Go API Module (v0.4.15)

A general library for interfacing with APIs. The basic procedure is:

  • Call goapi.New() to create a new api object. This can be stored for future use.

  • Create a new ep endpoint with api.NewEndpoint(). Again, these endpoints can be stored and reused.

  • Create a single-use req request object: ep.NewRequest()

  • Modify with req.AddQuery(), req.AddHeader(), etc as required.

    • AddQuery, AddHeader, etc can be chained: ep.NewRequest().AddHeader()

  • Call req.GET() or req.POST() as needed. By default, the request is discarded once used.

  • All processing of the returned data is done by the client application. go-api makes no attempt to interpret what it receives; it simply passes it back in a goapi.Result struct.

Simple Usage: No Auth

api := goapi.New(apiURL)
ep  := api.NewEndpoint(endpointURL)
req := ep.NewRequest().AddQuery(qryName,qryValue)
r := req.GET()

A simple example of this from the "Chuck Norris" API (see go-api-chuck) is as follows:

chuck := goapi.New("http://api.chucknorris.io/jokes")
ep  := chuck.NewEndpoint("/random")
req := ep.NewRequest()
req.AddQuery("category", "food")
r := req.GET()

After receiving the results, recommended processing may look like this:

r := req.GET()
data := &MyDataStruct{}
json.Unmarshal(r.Body, data)

Error Handling

To detect errors, can use either of these two approaches:

This library takes the approach that for any HTTP Status code other than 200 ("Success") it will return a QueryError, a custom error type. For status codes in the 200-299 range, the error name is Success (per the first example below.) For other codes, the error will be as follows:

case code <= 99: err = ErrUnsupportedRange
case code <= 199: err = ErrInformation
case code <= 299: err = Success
case code <= 399: err = ErrRedirection
case code <= 499: err = ErrClient
case code <= 599: err = ErrServer
default: err = ErrUnsupportedRange

The reason for returning all non-200 results as errors is to force the client code to handle them.

Examples of Error Detection

// Check for error type
if errors.Is(err, goapi.Success) {
  fmt.Printf("Success!");
}

or

// Do something with QueryError object
var qErr *goapi.QueryError
if errors.As(err, &qErr) {
  fmt.Printf("Error status := %d", qErr.Status())
}

QueryError has the following methods:

  • Unwrap() returns the underlying error

  • Status() returns the http status code

  • Response() returns the original HTTP response.