Categorygithub.com/KarpelesLab/rest
modulepackage
0.5.33
Repository: https://github.com/karpeleslab/rest.git
Documentation: pkg.go.dev

# README

GoDoc Go Report Card

KarpelesLab/rest

A comprehensive Go client for interacting with RESTful API services. This package simplifies making HTTP requests to REST endpoints, handling authentication, token renewal, and response parsing.

Features

  • Simple API for RESTful requests with JSON encoding/decoding
  • Support for context-based configuration and cancellation
  • OAuth2 token management with automatic renewal
  • Robust error handling with unwrapping to standard errors
  • Generic response parsing with type safety (Go 1.18+)
  • Large file uploads with multi-part and AWS S3 support
  • Automatic retry on token expiration

Installation

go get github.com/KarpelesLab/rest

Basic Usage

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/KarpelesLab/rest"
)

func main() {
    ctx := context.Background()
    
    // Simple GET request with response as map
    var result map[string]interface{}
    err := rest.Apply(ctx, "Endpoint/Path", "GET", nil, &result)
    if err != nil {
        log.Fatalf("API request failed: %s", err)
    }
    fmt.Printf("Result: %+v\n", result)
    
    // Using the generic As method (Go 1.18+)
    type User struct {
        ID   string `json:"id"`
        Name string `json:"name"`
    }
    
    user, err := rest.As[User](ctx, "Users/Get", "GET", rest.Param{"userId": "123"})
    if err != nil {
        log.Fatalf("Failed to get user: %s", err)
    }
    fmt.Printf("User: %s (%s)\n", user.Name, user.ID)
}

Parameter Order

This library was built based on the original JSON library, where HTTP method was an optional argument. As such it was placed after the path, and this pattern was kept in the Go version.

While methods like http.NewRequest take the method followed by the URL, remembering that the method is sometimes optional in API implementations is a good way to remember the argument order in this library:

rest.Apply(ctx, "Path/Endpoint", "GET", params, &result)
//                  ^path        ^method  ^params ^result

File Uploads

The package provides robust file upload capabilities:

// Upload a file
file, _ := os.Open("largefile.dat")
defer file.Close()

res, err := rest.Upload(ctx, "Files/Upload", "POST", 
    rest.Param{"filename": "myfile.dat"}, file, "application/octet-stream")
if err != nil {
    log.Fatalf("Upload failed: %s", err)
}

Command-line Upload Tool

restupload is a command-line tool for uploading large files to specific APIs.

Installation:

go install github.com/KarpelesLab/rest/cli/restupload@latest

Error Handling

Errors from REST APIs are automatically parsed and can be handled with the standard Go errors package:

_, err := rest.Do(ctx, "Protected/Resource", "GET", nil)
if err != nil {
    if errors.Is(err, os.ErrPermission) {
        // Handle permission denied (403)
    } else if errors.Is(err, fs.ErrNotExist) {
        // Handle not found (404)
    } else {
        // Handle other errors
    }
}

API Discovery

To discover available endpoints and their parameters, you can use the @karpeleslab/klbfw-describe tool:

npx @karpeleslab/klbfw-describe SomeEndpoint/Path

This will display detailed information about the endpoint, including:

  • Available methods
  • Required and optional parameters
  • Return types
  • Access requirements

This is especially useful when exploring new APIs or understanding existing endpoints.

Testing

The package includes a comprehensive test suite that can be run using:

go test -v github.com/KarpelesLab/rest

License

This package is distributed under the terms of the license found in the LICENSE file.

# Packages

No description provided by the author

# Functions

Apply makes a REST API request and unmarshals the response data into the target object.
As makes a REST API request and returns the response data unmarshaled into the specified type T.
Do executes a REST API request and returns the raw Response object.
NewApiKey creates a new ApiKey instance from separate key ID and secret parameters.
PrepareUpload creates an UploadInfo from the server response to an upload request.
ResponseAs is a generic helper that unmarshals a response into type T.
SpotApply makes a REST API request through a SpotClient and unmarshals the response into target.
SpotAs makes a REST API request through a SpotClient and returns the response data unmarshaled into type T.
SpotDo executes a REST API request through a SpotClient and returns the raw Response object.
SpotUpload uploads a file using a SpotClient.
Upload uploads a file to a REST API endpoint.

# Constants

No description provided by the author
No description provided by the author

# Variables

Debug enables verbose logging of REST API requests and responses.
ErrLoginRequired is returned when an API endpoint requires authentication but no valid token was provided.
ErrNoClientID is returned when token renewal is attempted without a client ID.
ErrNoRefreshToken is returned when token renewal is attempted without a refresh token.
Host defines the default hostname for API requests.
RestHttpClient is the default HTTP client used for all REST API requests.
RestHttpTransport is the configured HTTP transport used for all REST API requests.
No description provided by the author
Scheme defines the URL scheme for API requests (http or https).
No description provided by the author
No description provided by the author

# Structs

ApiKey represents an API key with its secret for signing requests.
Error represents an error returned by a REST API endpoint.
HttpError represents an HTTP transport error that occurred during a REST API request.
Response represents a REST API response with standard fields.
No description provided by the author
No description provided by the author
Token represents an OAuth2 token with refresh capabilities.
No description provided by the author
UploadInfo represents configuration and state for file uploads.

# Interfaces

No description provided by the author
SpotClient is an interface fulfilled by spotlib.Client that provides the necessary functionality for making API requests through a Spot connection.

# Type aliases

No description provided by the author
Param is a convenience type for parameters passed to REST API requests.