poeapi

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2021 License: GPL-3.0 Imports: 13 Imported by: 0

README

poeapi

GoDoc Badge GoReportCard Badge Travis Badge CodeCov Badge License Badge

A Go client for the Path of Exile API.

Features

  • Supports every endpoint of the Path of Exile API
  • All operations are thread-safe
  • Built-in, tunable rate limiting
  • Built-in, tunable caching for responses
  • No dependencies; 100% standard library code

Usage

clientOpts := poeapi.ClientOptions{
    Host:           "api.pathofexile.com", // The primary API domain.
    NinjaHost:      "poe.ninja",           // Used to get latest stash ID.
    UseSSL:         true,                  // Use HTTPS for requests.
    UseCache:       true,                  // Enable the in-memory cache.
    UseDNSCache:    true,                  // Enable the in-memory DNS resolution cache.
    CacheSize:      200,                   // Number of items to store.
    RateLimit:      4.0,                   // Requests per second.
    StashRateLimit: 1.0,                   // Requests per second for trade API.
    RequestTimeout: 5 * time.Second        // Time to wait before canceling requests.
} // This is equivalent to poeapi.DefaultClientOptions.

client, err := poeapi.NewAPIClient(clientOpts)
if err != nil {
    // Handle error.
}

ladder, err := client.GetLadder(poeapi.GetLadderOptions{
    ID:    "SSF Hardcore",
    Realm: "pc",
    Type:  "league",
})
// Etc.

Interface

These are the methods available on the client's interface:

// Method:                                 Returns:
GetLadder(poeapi.GetLadderOptions)         (poeapi.Ladder, error)
GetLeague(poeapi.GetLeagueOptions)         (poeapi.League, error)
GetLeagueRule(poeapi.GetLeagueRuleOptions) (poeapi.LeagueRule, error)
GetLeagueRules()                           ([]poeapi.LeagueRule, error)
GetLeagues(poeapi.GetLeaguesOptions)       ([]poeapi.League, error)
GetPVPMatches(poeapi.GetPVPMatchesOptions) ([]poeapi.PVPMatch, error)
GetStashes(poeapi.GetStashOptions)         (poeapi.StashResponse, error)
GetLatestStashID()                         (string, error)

See the documentation or examples for more usage information.

Examples

There are several examples in the examples directory.

Contributing

Contributions to the code, examples, or documentation are very welcome.

Found a problem? Have a question? Open an issue

Have a patch or a new feature? Open a pull request

Documentation

Overview

Package poeapi provides a client for the Path of Exile API.

Features include support for all API endpoints, thread-safe operations, built-in caching and ratelimiting, and no reliance on external packages.

Usage:

clientOpts := poeapi.ClientOptions{
    Host:              "api.pathofexile.com", // The primary API domain.
    NinjaHost:         "poe.ninja",           // Used to get latest stash ID.
    UseSSL:            true,                  // Use HTTPS for requests.
    UseCache:          true,                  // Enable the in-memory cache.
    UseDNSCache:       true,                  // Enable the in-memory DNS resolution cache.
    CacheSize:         200,                   // Number of items to store.
    RateLimit:         4.0,                   // Requests per second.
    StashRateLimit:    1.0,                   // Requests per second for trade API.
    RequestTimeout:    5 * time.Second        // Time to wait before canceling requests.
} // This is equivalent to poeapi.DefaultClientOptions.

client, err := poeapi.NewAPIClient(clientOpts)
if err != nil {
    // Handle error.
}

ladder, err := client.GetLadder(poeapi.GetLadderOptions{
    ID:    "SSF Hardcore",
    Realm: "pc",
    Type:  "league",
})
// Etc.

See the APIClient interface for the full description of methods available.

Index

Constants

View Source
const (
	// DefaultHost sets the hostname used by the client. This is set to
	// api.pathofexile.com, but may be overridden for testing purposes.
	DefaultHost = "api.pathofexile.com"

	// DefaultNinjaHost sets the hostname used to retrieve the latest stash
	// change ID from poe.ninja. This is set to "poe.ninja" but may be
	// overridden for testing purposes.
	DefaultNinjaHost = "poe.ninja"

	// DefaultRateLimit sets the rate limit for all endpoints except for the
	// stash endpoint. Most endpoints have a rate limit of 5 requests per
	// second. Tests performed with the ratetest program (cmd/ratetest) show
	// occasional failures at this rate, so we back down to 4 requests per
	// second by default to err on the side of caution.
	DefaultRateLimit = 4.0

	// DefaultStashRateLimit sets the rate limit for the stash endpoint.
	// The stash API has a rate limit of 1 request per second.
	DefaultStashRateLimit = 1.0

	// DefaultCacheSize sets the number of items which can be stores in the
	// in-memory LRU cache. A typical response from the API is around 500KB.
	// By default, allow around 200x500KB=100MB total cache memory usage.
	DefaultCacheSize = 200

	// DefaultRequestTimeout sets the time to wait before canceling HTTP
	// requests. Some endpoits take over 2-3s to respond, so we use 5s as a
	// a default.
	DefaultRequestTimeout = 5 * time.Second
)
View Source
const (
	// UnlimitedRate disables rate limiting when used as a rate limit.
	UnlimitedRate = 0
)

Variables

View Source
var (
	// ErrBadRequest is raised when we have sent a malformed request to the API.
	ErrBadRequest = errors.New("bad request")

	// ErrNotFound is raised when we have requested an invalid URL.
	ErrNotFound = errors.New("url not found")

	// ErrRateLimited is raised when we exceed the API rate limits.
	ErrRateLimited = errors.New("rate limited")

	// ErrServerFailure is raised when the API returns a 5xx response for any
	// reason.
	ErrServerFailure = errors.New("server error")

	// ErrUnknownFailure is raised when an undocumented status code is returned
	// by the API. This should never occur, but is handled anyway.
	ErrUnknownFailure = errors.New("unknown server failure")

	// ErrInvalidHost is raised when an unsupported hostname is provided.
	ErrInvalidHost = errors.New("invalid API host")

	// ErrInvalidNinjaHost is raised when the poe.ninja hostname is omitted.
	ErrInvalidNinjaHost = errors.New("invalid poe.ninja host")

	// ErrInvalidRateLimit is raised when the general rate limit is out of
	// range.
	ErrInvalidRateLimit = errors.New("invalid rate limit")

	// ErrInvalidStashRateLimit is raised when the stash rate limit is out of
	// range.
	ErrInvalidStashRateLimit = errors.New("invalid stash rate limit")

	// ErrInvalidRequestTimeout is raised when request timeout is too small.
	ErrInvalidRequestTimeout = errors.New("invalid request timeout")

	// ErrInvalidCacheSize is raised when the cache size is out of range.
	ErrInvalidCacheSize = errors.New("invalid cache size")

	// ErrNotFoundInCache is raised when a value is requested from the cache
	// before it is written.
	ErrNotFoundInCache = errors.New("not found in cache")

	// ErrInvalidAddress is raised when a malformed IP address is returned by
	// the DNS cache.
	ErrInvalidAddress = errors.New("invalid ip address")

	// ErrMissingID is raised when the user fails to provide a league ID for a
	// ladder request.
	ErrMissingID = errors.New("missing league id")

	// ErrInvalidRealm is raised when the provided realm is not pc, xbox, or
	// sony.
	ErrInvalidRealm = errors.New("invalid realm")

	// ErrInvalidLimit is raised when the page size limit is out of bounds.
	ErrInvalidLimit = errors.New("invalid limit")

	// ErrInvalidOffset is raised when the page offset is out of bounds.
	ErrInvalidOffset = errors.New("invalid offset")

	// ErrInvalidLadderType is raised when the provided type is not league, pvp,
	// or labyrinth.
	ErrInvalidLadderType = errors.New("invalid ladder type")

	// ErrInvalidDifficulty is raised when the provided difficulty is not Normal,
	// Cruel, Merciless, or Eternal.
	ErrInvalidDifficulty = errors.New("invalid difficulty")

	// ErrInvalidLabyrinthStartTime is raised when the provided Unix timestamp
	// is below zero, above zero but earlier than the release of the Labyrinth,
	// or is an invalid timestamp.
	ErrInvalidLabyrinthStartTime = errors.New("invalid labyrinth start time")

	// ErrInvalidLeagueRuleID is raised when the ID is missing in a league rule
	// request.
	ErrInvalidLeagueRuleID = errors.New("missing league rule id")

	// ErrInvalidSeason is raised when requesting a season league with a missing
	// season name.
	ErrInvalidSeason = errors.New("invalid season")

	// ErrInvalidLeagueType is raised when requesting a league whose type is not
	// supported by the API.
	ErrInvalidLeagueType = errors.New("invalid league type")

	// ErrInvalidLeagueID is raised when the league ID is omitted from a league
	// request.
	ErrInvalidLeagueID = errors.New("invalid league id")

	// ErrInvalidStashID is raised when the stash ID is omitted from a stash
	// request.
	ErrInvalidStashID = errors.New("invalid stash id")
)
View Source
var DefaultClientOptions = ClientOptions{
	Host:           DefaultHost,
	NinjaHost:      DefaultNinjaHost,
	UseSSL:         true,
	UseCache:       true,
	CacheSize:      DefaultCacheSize,
	UseDNSCache:    true,
	RateLimit:      DefaultRateLimit,
	StashRateLimit: DefaultStashRateLimit,
	RequestTimeout: DefaultRequestTimeout,
}

DefaultClientOptions initializes the client with the most common settings.

Functions

This section is empty.

Types

type APIClient

type APIClient interface {
	// GetLadder sends multiple ladder requests to construct the entire ladder
	// for a given league in a single call. Ladders contain information about
	// the top-ranked characters in a given league. Up to 15,000 characters may
	// be returned.
	GetLadder(GetLadderOptions) (Ladder, error)

	// GetLeague retrieves all league (Standard, Hardcore, etc.) from the API.
	// Responses include information such as start and end times and rules for
	// the league.
	GetLeagues(GetLeaguesOptions) ([]League, error)

	// GetLeague retrieves a single league from the API by ID.
	GetLeague(GetLeagueOptions) (League, error)

	// GetLeagueRules retrieves all available league modifiers from the API.
	// These modifiers affect league mechanics, such as the 'Turbo' rule
	// granting increased attack, cast, and movement speed to monsters.
	GetLeagueRules() ([]LeagueRule, error)

	// GetLeagueRule retrieves a single rule from the API by ID.
	GetLeagueRule(GetLeagueRuleOptions) (LeagueRule, error)

	// GetPVPMatches retrieves past or upcoming PVP matches from the API.
	// Specific seasons may be requested in order to view past events.
	// Alternatively, not specifying a season returns all upcoming events.
	GetPVPMatches(GetPVPMatchesOptions) ([]PVPMatch, error)

	// GetStashes retrieves a batch of stashes from the trade API. Each response
	// contains a set of stashes which can be parsed for specific items.
	// Responses also include a "next change ID" which is used to request the
	// next set of stashes in chronological order (by publish time).
	GetStashes(GetStashOptions) (StashResponse, error)

	// GetLatestStashID retrieves the latest stash tab ID from poe.ninja. This
	// is helpful when building real-time trade applications, as not specifying
	// a stash ID starts from the beginning of time. This makes a single request
	// to poe.ninja's API, and caches the response to avoid subsequent traffic.
	GetLatestStashID() (string, error)
}

APIClient provides methods for interacting with the Path of Exile API.

func NewAPIClient

func NewAPIClient(opts ClientOptions) (APIClient, error)

NewAPIClient configures and returns an APIClient.

type Account

type Account struct {
	Name       string     `json:"name"`
	Realm      string     `json:"realm"`
	Challenges Challenges `json:"challenges"`
	TwitchInfo TwitchInfo `json:"twitch"`
}

Account represents an account for a ladder entry.

type Challenges

type Challenges struct {
	Total int `json:"total"`
}

Challenges represents an account's completed challenges.

type Character

type Character struct {
	Name       string `json:"name"`
	Level      int    `json:"level"`
	Class      string `json:"class"`
	ID         string `json:"id"`
	Experience int    `json:"experience"`
}

Character represents a player in a ladder entry.

type ClientOptions

type ClientOptions struct {
	// The hostname used by the client.
	Host string

	// The hostname used for poe.ninja requests.
	NinjaHost string

	// Set to false if your network does not allow outbound HTTPS traffic.
	UseSSL bool

	// Set to false to always hit the API for requests instead of using a local
	// cache. Caching is always disabled for stash requests, since retrieving
	// a cached stash means we will never get a new change ID.
	UseCache bool

	// The number of items which can be stored in the cache. Most endpoints
	// have a response size up to 500KB or so.
	CacheSize int

	// Set to true to cache DNS resolution locally, speeding up subsequent
	// requests. Go's resolver does not cache by default.
	UseDNSCache bool

	// The number of requests per second for all API endpoints except the stash
	// tab endpoint. The API will ratelimit clients above 5rps.
	RateLimit float64

	// The number of requests per second for the stash endpoint. The API
	// will ratelimit clients above 1rps.
	StashRateLimit float64

	// Time to wait before canceling HTTP requests.
	RequestTimeout time.Duration
}

ClientOptions contains settings for client initialization.

type GetLadderOptions

type GetLadderOptions struct {
	// The name of the league whose ladder you want to retrieve.
	ID string

	// The realm of the ladder.
	// Valid options: 'pc', 'xbox', or 'sony'.
	Realm string

	// The type of league whose ladder you want to retrieve.
	// Valid options: 'league', 'pvp', or 'labyrinth'.
	Type string

	// Associate UUIDs with each character returned for tracking purposes.
	UniqueIDs bool

	// Only include the given account in results.
	AccountName string

	// Difficulty of the Labyrinth ladder to retrieve.
	// Valid options: 'Normal', 'Cruel', 'Merciless', or 'Eternal'.
	LabyrinthDifficulty string

	// Start time of the Labyrinth ladder to retrieve. This is a Unix timestamp.
	LabyrinthStartTime int
	// contains filtered or unexported fields
}

GetLadderOptions contains the request parameters for the ladder endpoint. All parameters are optional with the exception of ID.

type GetLeagueOptions

type GetLeagueOptions struct {
	// The name of the league to retrieve.
	ID string

	// The realm of the ladder.
	// Valid options: 'pc', 'xbox', or 'sony'.
	Realm string
}

GetLeagueOptions contains the request parameters for the league endpoint. ID is a required option, and Realm is optional. The API allows callers to request the ladder alongside the league, but this is not implemented. Use the GetLadder() method instead.

type GetLeagueRuleOptions

type GetLeagueRuleOptions struct {
	// The identifier of the league rule to retrieve.
	ID string
}

GetLeagueRuleOptions contains the request parameters for the league rules endpoint. The only parameter, ID, is required.

type GetLeaguesOptions

type GetLeaguesOptions struct {
	// The type of leagues to retrieve.
	// Valid options: 'main', 'event', or 'season'.
	Type string

	// The realm of leagues to retrieve.
	// Valid options: 'pc', 'xbox', or 'sony'.
	Realm string

	// The name of the season to retrieve. Requires when Type is 'season'.
	Season string

	// Set to true to omit rules, registration time, and description from the
	// response.
	Compact bool

	// Number of leagues to retrieve. Defaults to 50, and is capped at 50 when
	// Compact is false, but can go up to 230 when Compact is true. This is only
	// needed when retrieving seasonal leagues, such as the 'Medallion' season
	// which had 139 leagues.
	Limit int

	// Starting index for bulk league retrieval. Only needed when requesting
	// more than 50 leagues.
	Offset int
}

GetLeaguesOptions contains the request parameters for the leagues endpoint. All parameters are optional.

type GetPVPMatchesOptions

type GetPVPMatchesOptions struct {
	// The type of matches to find. Set to 'season' to search for a specific PVP
	// season, or leave blank to return all upcoming PVP matches.
	Type string

	// The name of the season for which to retrieve matches.
	Season string

	// The realm of PVP matches to retrieve.
	// Valid options: 'pc', 'xbox', or 'sony'.
	Realm string
}

GetPVPMatchesOptions contains the request parameters for the PVP matches endpoint. All parameters are optional.

type GetStashOptions

type GetStashOptions struct {
	// ID is the unique change ID containing a set of stashes. If ID is omitted,
	// the API will return the oldest stash tab possible.
	ID string
}

GetStashOptions contains the request parameters for the stash endpoint.

type Item

type Item struct {
	Corrupted         bool          `json:"corrupted"`
	ExplicitMods      []string      `json:"explicitMods"`
	FlavorText        []string      `json:"flavourText"`
	FrameType         int64         `json:"frameType"`
	Height            int64         `json:"h"`
	ID                string        `json:"id"`
	Icon              string        `json:"icon"`
	Identified        bool          `json:"identified"`
	ImplicitMods      []string      `json:"implicitMods"`
	InventoryID       string        `json:"inventoryId"`
	ItemLevel         int64         `json:"ilvl"`
	League            string        `json:"league"`
	LockedToCharacter bool          `json:"lockedToCharacter"`
	Name              string        `json:"name"`
	Note              string        `json:"note"`
	Properties        []Property    `json:"properties"`
	Requirements      []Requirement `json:"requirements"`
	SocketedItems     interface{}   `json:"socketedItems"`
	Sockets           []Socket      `json:"sockets"`
	Support           bool          `json:"support"`
	TalismanTier      int64         `json:"talismanTier"`
	TypeLine          string        `json:"typeLine"`
	Verified          bool          `json:"verified"`
	Width             int64         `json:"w"`
	XPosition         int64         `json:"x"`
	YPosition         int64         `json:"y"`
}

Item represents an item listing in the stash tab API.

type Ladder

type Ladder struct {
	TotalEntries int           `json:"total" validate:"nonzero"`
	Title        string        `json:"title"`
	StartTime    int           `json:"startTime"`
	Entries      []LadderEntry `json:"entries"`
}

Ladder represents the leaderboard for a specific league.

type LadderEntry

type LadderEntry struct {
	Online        bool      `json:"bool"`
	Rank          int       `json:"rank"`
	LabyrinthTime int       `json:"time"`
	Character     Character `json:"character"`
	Account       Account   `json:"account"`
}

LadderEntry represents an entry on the ladder.

type League

type League struct {
	Name         string       `json:"id" validate:"nonzero"`
	Realm        string       `json:"realm"`
	Description  string       `json:"description"`
	LadderURL    string       `json:"url"`
	StartTime    time.Time    `json:"startAt"`
	EndTime      time.Time    `json:"endAt"`
	DelveEnabled bool         `json:"delveEvent"`
	Rules        []LeagueRule `json:"rules"`
}

League represents a permanent or challenge league.

type LeagueRule

type LeagueRule struct {
	ID          string `json:"id" validate:"nonzero"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

LeagueRule represents a modifier placed on a league.

type PVPMatch

type PVPMatch struct {
	ID            string    `json:"id"`
	Realm         string    `json:"realm"`
	StartTime     time.Time `json:"startAt"`
	EndTime       time.Time `json:"endAt"`
	LadderURL     string    `json:"url"`
	Description   string    `json:"description"`
	GlickoRatings bool      `json:"glickoRatings"`
	PVP           bool      `json:"pvp"`
	Style         string    `json:"style"`
	RegisterTime  time.Time `json:"registerAt"`
}

PVPMatch represents a PVP event type.

type Property

type Property struct {
	DisplayMode int64           `json:"displayMode"`
	Name        string          `json:"name"`
	Values      [][]interface{} `json:"values"`
}

Property represents a property of an Item.

type Requirement

type Requirement struct {
	DisplayMode int64           `json:"displayMode"`
	Name        string          `json:"name"`
	Values      [][]interface{} `json:"values"`
}

Requirement represents an attribute requirement on an Item, such as strength.

type Socket

type Socket struct {
	Attribute string `json:"attr"`
	Group     int64  `json:"group"`
}

Socket represents a socket on an item, including its color and links.

type Stash

type Stash struct {
	ID                string `json:"id"`
	AccountName       string `json:"accountName"`
	LastCharacterName string `json:"lastCharacterName"`
	Index             string `json:"stash"`
	Type              string `json:"stashType"`
	Items             []Item `json:"items"`
	Public            bool   `json:"public"`
}

Stash represents a single public stash tab.

type StashResponse

type StashResponse struct {
	NextChangeID string  `json:"next_change_id"`
	Stashes      []Stash `json:"stashes"`
}

StashResponse represents a response from the stash tab API which contains multiples stashes.

type TwitchInfo

type TwitchInfo struct {
	Username string `json:"name"`
}

TwitchInfo represents an account's linked Twitch user.

Directories

Path Synopsis
cmd
ratetest
ratetest attempts to reverse engineer the rate limits for the PoE API.
ratetest attempts to reverse engineer the rate limits for the PoE API.
examples
ladderstats
ladderstats prints the distribution of character classes in a ladder.
ladderstats prints the distribution of character classes in a ladder.
leaguetimer
leaguetimer prints the time remaining for the current challenge league.
leaguetimer prints the time remaining for the current challenge league.
listleaguerules
listleaguerules prints all league rules from the API.
listleaguerules prints all league rules from the API.
upcomingmatches
upcomingmatches prints the number of upcoming PVP events.
upcomingmatches prints the number of upcoming PVP events.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL