Documentation
¶
Overview ¶
Package pokeapi provides an API client for [PokeAPI](https://pokeapi.co).
It includes supports rate limiting, iterators for pagination and resolution of Named API Resources.
Index ¶
- func GetNamedResource[T any](ctx context.Context, c *Client, nrsc *NamedResource[T]) (*T, error)
- type Ability
- type CallOption
- type Client
- func (c *Client) GetGeneration(ctx context.Context, idOrName string) (*Generation, error)
- func (c *Client) GetGenerations(ctx context.Context, opts ...CallOption) (iter.Seq2[*Generation, error], error)
- func (c *Client) GetPokemon(ctx context.Context, idOrName string) (*Pokemon, error)
- func (c *Client) GetPokemons(ctx context.Context, opts ...CallOption) (iter.Seq2[*Pokemon, error], error)
- type ClientOption
- type Description
- type Generation
- type GenerationGameIndex
- type Language
- type Location
- type Name
- type NamedResource
- type NamedResourceList
- type Pokedex
- type Pokemon
- type PokemonAbility
- type PokemonAbilityPast
- type PokemonCries
- type PokemonEntry
- type PokemonForm
- type PokemonFormSprites
- type PokemonFormType
- type PokemonHeldItem
- type PokemonHeldItemVersion
- type PokemonMove
- type PokemonMoveVersion
- type PokemonSprites
- type PokemonStat
- type PokemonType
- type PokemonTypePast
- type Region
- type TODO
- type URL
- type Version
- type VersionGameIndex
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetNamedResource ¶
GetNamedResource resolves a NamedResource. It calls the API to request the data for the named resource.
Example ¶
package main
import (
"context"
"fmt"
"git.sr.ht/~rf/pokeapi"
)
func main() {
// Some of the properties returned by the API are references called Named
// Resources. These point to other endpoints in the API. The client library
// exposes a function called GetNamedResource that accepts these, and
// resolves them by calling the API.
ctx := context.Background()
c, err := pokeapi.NewClient()
if err != nil {
panic(err)
}
generation, err := c.GetGeneration(ctx, "generation-iii")
if err != nil {
panic(err)
}
// The MainRegion property is a Named Resource, which can be resolved.
region, err := pokeapi.GetNamedResource(ctx, c, &generation.MainRegion)
if err != nil {
panic(err)
}
fmt.Println(region.Name)
}
Output: hoenn
Types ¶
type Ability ¶
type Ability struct {
// The identifier for this resource.
ID int `json:"id"`
// The name for this resource.
Name string `json:"name"`
// Whether or not this ability originated in the main series of the video
// games.
IsMainSeries bool `json:"is_main_series"`
// The generation this ability originated in.
Generation NamedResource[TODO] `json:"generation"`
// The name of this resource listed in different languages.
Names []Name `json:"names"`
// The effect of this ability listed in different languages.
EffectEntries []TODO `json:"effect_entries"`
// The list of previous effects this ability has had across version groups.
EffectChanges TODO `json:"effect_changes"`
// The flavor text of this ability listed in different languages.
FlavorTextEntries []TODO `json:"flavor_text_entries"`
// A list of Pokémon that could potentially have this ability.
Pokemon []TODO `json:"pokemon"`
}
type CallOption ¶
type CallOption func(*callOptions) error
CallOption are options for the endpoints.
func WithPageSize ¶
func WithPageSize(pageSize int) CallOption
WithPageSize sets the page size to retrieve when calling paginated endpoints.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client to interact with PokeAPI.
func NewClient ¶
func NewClient(opts ...ClientOption) (*Client, error)
NewClient instantiates a new Client.
func (*Client) GetGeneration ¶
GetGeneration returns a single Generation by ID or name.
func (*Client) GetGenerations ¶
func (c *Client) GetGenerations(ctx context.Context, opts ...CallOption) ( iter.Seq2[*Generation, error], error, )
GetGenerations returns an iterator that will yield all the Generations in the API.
Example ¶
package main
import (
"context"
"fmt"
"time"
"git.sr.ht/~rf/pokeapi"
)
func main() {
ctx := context.Background()
start := time.Now()
// The client can accept a rate limit, to be nice.
c, err := pokeapi.NewClient(pokeapi.WithRateLimiter(10))
if err != nil {
panic(err)
}
// GetGenerations (as well as any other paginated endpoints) returns an
// iterator that deals with pagination for you.
it, err := c.GetGenerations(ctx)
if err != nil {
panic(err)
}
// Since the iterator needs to do IO to retrieve all the pages, an error
// can happen while iterating, which has to be dealt with in the loop.
i := 0
for generation, err := range it {
i++
if i == 10 {
// The 10th generation is not out at the time of writing.
// Stop here so that the example doesn't break in the future.
break
}
if err != nil {
panic(err)
}
// Further calls can be made in this iterator to resolve Named
// Resources. The rate limit, if set, will be respected.
region, err := pokeapi.GetNamedResource(ctx, c, &generation.MainRegion)
if err != nil {
panic(err)
}
fmt.Printf("%s: %s\n", generation.Name, region.Name)
}
// This example requires 10 API calls. The rate limiter is set to 10 RPS.
// So this example should not run in less than one second.
elapsed := time.Since(start).Seconds()
if elapsed >= 1 {
fmt.Println("This example took at least one second to run.")
}
}
Output: generation-i: kanto generation-ii: johto generation-iii: hoenn generation-iv: sinnoh generation-v: unova generation-vi: kalos generation-vii: alola generation-viii: galar generation-ix: paldea This example took at least one second to run.
func (*Client) GetPokemon ¶
GetPokemon returns a single pokemon by ID or by name.
Example ¶
package main
import (
"context"
"fmt"
"git.sr.ht/~rf/pokeapi"
)
func main() {
ctx := context.Background()
c, err := pokeapi.NewClient()
if err != nil {
panic(err)
}
pokemon, err := c.GetPokemon(ctx, "pikachu")
if err != nil {
panic(err)
}
fmt.Println(pokemon.Name)
}
Output: pikachu
Example (Asciiart) ¶
package main
import (
"context"
"fmt"
"image"
"image/png"
"net/http"
"strings"
"github.com/qeesung/image2ascii/convert"
"git.sr.ht/~rf/pokeapi"
)
func main() {
ctx := context.Background()
c, err := pokeapi.NewClient()
if err != nil {
panic(err)
}
pokemon, err := c.GetPokemon(ctx, "pikachu")
if err != nil {
panic(err)
}
resp, err := http.Get(pokemon.Sprites.FrontDefault.String())
if err != nil {
panic(err)
}
defer resp.Body.Close()
img, err := png.Decode(resp.Body)
if err != nil {
panic(err)
}
img = img.(interface {
SubImage(image.Rectangle) image.Image
}).SubImage(image.Rect(30, 30, 70, 70))
opts := convert.DefaultOptions
opts.Ratio = float64(img.Bounds().Dx()) / float64(img.Bounds().Dy())
opts.FixedWidth = 35
opts.FixedHeight = 35
opts.Colored = false
out := strings.Split(strings.Join(
convert.NewImageConverter().Image2ASCIIMatrix(img, &opts), " "), "\n")
for i := range out {
fmt.Println(strings.TrimRight(out[i], " "))
}
}
Output: . : f i , , : . . t L L ; . , ; ; ; ; ; ; . ; i f L : . . . . . : t L 1 1 ; ; ; ; . , t L L ; , ; L L f f : , f L , C C L ; ; ; . 1 i t 1 C G ; ; : 1 C L 1 G C C , 1 ; , . : . , 1 L G ; f 0 0 G G 1 1 C C C G ; . . i C 1 . , f G G C C G G C : . L G L 1 : i C G G 1 . i ; t C G C C G i C , , G 1 i t G G C 1 f . , . f C C f L C G i , ; G , 1 . . 1 G C C C C 1 1 . ; f G 1 L G C C i : C L C L , i L C C C C C C 1 i ; f t C G f t L G G G G L t t f ; ; C G C C C C C C G f : i i G L i : t t 1 t C L i 1 ; t : ; C G C C C C C C C C 1 i . : t L f t f L f t f L L ; i ; f ; 1 i C C C C C C C C C G i . : t L L L L L L L L L L f ; 1 i : ; f L L C C C C C 1 C G : . . 1 L L L L L L L L L L L L f i : ; L L L L L L C 1 C C i i i L L L L L L L L L L L ; 1 . : f ; L L L ; ; t 1 1 i f L L L L L L L L L L f , : , f ; f ; t i t 1 L f L L L L L L L f L C 1 , , f i t 1 , G C L f L f L t L C C C 1 , , t f : , L 1 1 C C C C C f L C G C C 1 ; . t i ; i , C t C C C C G t C G C C C C C . . f L L f : i , C C i G C G 1 f G C G C L C G . ; t t f f ; : L G C i G C C t L G C C t L G i i : 1 : , . L G C L f G i t G G G t f G C L : i i , t t C C t t G f , L C 1 f G C L f L : ; . 1 , L 1 i f G C G f 1 i f G C C L L f : 1 , , i C 1 L L G C C C G L L G C C C f L L , : ; . , i L C G G C C C C C G G C L C C L f L t . , ; f L L C C C C C C L f L C L C L L L t 1 i L f L L L ; ; ; ; L f f L L L L ; , , i t i L f f 1 1 1 1 ; i ; L L L ; i . i t t 1 , ; 1 t t f t ; ; t f L ; . . . . i ; t : , , , ; , . t f L . . .
Example (Todo) ¶
package main
import (
"context"
"fmt"
"git.sr.ht/~rf/pokeapi"
)
func main() {
// Some of the structs in the API are not yet structured in the client. But
// the data is accessible:
ctx := context.Background()
c, err := pokeapi.NewClient()
if err != nil {
panic(err)
}
pokemon, err := c.GetPokemon(ctx, "articuno")
if err != nil {
panic(err)
}
// The MainRegion property is a Named Resource, which can be resolved.
species, err := pokeapi.GetNamedResource(ctx, c, &pokemon.Species)
if err != nil {
panic(err)
}
fmt.Println("capture_rate:", (*species)["capture_rate"])
fmt.Println("name:", (*species)["name"])
fmt.Println("is_legendary:", (*species)["is_legendary"])
}
Output: capture_rate: 3 name: articuno is_legendary: true
type ClientOption ¶
type ClientOption func(*clientOptions) error
func WithBaseURL ¶
func WithBaseURL(endpoint string) ClientOption
WithBaseURL sets the base URL of the API.
func WithDefaultPageSize ¶
func WithDefaultPageSize(pageSize int) ClientOption
WithDefaultPageSize sets the default page size for paginated endpoints.
func WithHTTPClient ¶
func WithHTTPClient(client *http.Client) ClientOption
WithHTTPClient sets the HTTP client to use.
func WithRateLimiter ¶
func WithRateLimiter(rps float64) ClientOption
WithRateLimiter enables a rate limiter.
type Description ¶
type Description struct {
// The localized description for an API resource in a specific language.
Description string
// The language this name is in.
Language NamedResource[Language]
}
type Generation ¶
type Generation struct {
// The identifier for this resource.
ID int `json:"id"`
// The name for this resource.
Name string `json:"name"`
// A list of abilities that were introduced in this generation.
Abilities []NamedResource[Ability] `json:"abilities"`
// The name of this resource listed in different languages.
Names []Name `json:"names"`
// The main region travelled in this generation.
MainRegion NamedResource[Region] `json:"main_region"`
// A list of moves that were introduced in this generation.
Moves []NamedResource[TODO] `json:"moves"`
// A list of Pokémon species that were introduced in this generation.
PokemonSpecies []NamedResource[TODO] `json:"pokemon_species"`
// A list of types that were introduced in this generation.
Types []NamedResource[TODO] `json:"types"`
// A list of version groups that were introduced in this generation.
VersionGroups []NamedResource[TODO] `json:"version_groups"`
}
A generation is a grouping of the Pokémon games that separates them based on the Pokémon they include. In each generation, a new set of Pokémon, Moves, Abilities and Types that did not exist in the previous generation are released.
type GenerationGameIndex ¶
type GenerationGameIndex struct {
// The internal id of an API resource within game data.
GameIndex int
// The generation relevant to this game index.
Generation NamedResource[Generation]
}
type Language ¶
type Language struct {
// The identifier for this resource.
ID int `json:"id"`
// The name for this resource.
Name string `json:"name"`
// Whether or not the games are published in this language.
Official bool `json:"official"`
// The two-letter code of the country where this language is spoken. Note
// that it is not unique.
ISO639 string `json:"iso_639"`
// The two-letter code of the language. Note that it is not unique.
ISO3166 string `json:"iso_3166"`
// The name of this resource listed in different languages.
Names []Name `json:"names"`
}
type Location ¶
type Location struct {
// The identifier for this resource.
ID int
// The name for this resource.
Name string
// The region this location can be found in.
Region NamedResource[Region]
// The name of this resource listed in different languages.
Names []Name
// A list of game indices relevant to this location by generation.
GameIndices []GenerationGameIndex
// Areas that can be found within this location.
Areas []NamedResource[TODO]
}
type Name ¶
type Name struct {
// The localized name for an API resource in a specific language.
Name string `json:"name"`
// The language this name is in.
Language NamedResource[TODO] `json:"language"`
}
type NamedResource ¶
NamedResource is a reference type returned by the API.
type NamedResourceList ¶
type NamedResourceList[T any] struct { // Total amount of items in this paginated list. Count int // Next points to the URL of the next page, if there's one. Next optional.T[*URL] // Previous points to the URL of the previous page, if there's one. Previous optional.T[*URL] // Results are the items in the page. Results []NamedResource[T] }
NamedResourceList is a paginated list of named resources.
type Pokedex ¶
type Pokedex struct {
// The identifier for this resource.
ID int
// The name for this resource.
Name string
// Whether or not this Pokédex originated in the main series of the video
// games.
IsMainSeries bool
// The description of this resource listed in different languages.
Descriptions []Description
// The name of this resource listed in different languages.
Names []Name
// A list of Pokémon catalogued in this Pokédex and their indexes.
PokemonEntries []PokemonEntry
// The region this Pokédex catalogues Pokémon for.
Region NamedResource[Region]
// A list of version groups this Pokédex is relevant to.
Version_groups []NamedResource[TODO]
}
type Pokemon ¶
type Pokemon struct {
// The identifier for this resource.
ID int `json:"id"`
// The name for this resource.
Name string `json:"name"`
// The base experience gained for defeating this Pokémon.
BaseExperience int `json:"base_experience"`
// The height of this Pokémon in decimetres.
Height int `json:"height"`
// Set for exactly one Pokémon used as the default for each species.
IsDefault bool `json:"is_default"`
// Order for sorting. Almost national order, except families are grouped
// together.
Order int `json:"order"`
// The weight of this Pokémon in hectograms.
Weight int `json:"weight"`
// A list of abilities this Pokémon could potentially have.
Abilities []PokemonAbility `json:"abilities"`
// A list of forms this Pokémon can take on.
Forms []NamedResource[PokemonForm] `json:"forms"`
// A list of game indices relevant to Pokémon item by generation.
GameIndices []VersionGameIndex `json:"game_indices"`
// A list of items this Pokémon may be holding when encountered.
HeldItems []PokemonHeldItem `json:"held_items"`
// A link to a list of location areas, as well as encounter details
// pertaining to specific versions.
LocationAreaEncounters URL `json:"location_area_encounters"`
// A list of moves along with learn methods and level details pertaining to
// specific version groups.
Moves []PokemonMove `json:"moves"`
// A list of details showing types this pokémon had in previous generations
PastTypes []PokemonTypePast `json:"past_types"`
// A list of details showing abilities this pokémon had in previous
// generations
PastAbilities []PokemonAbilityPast `json:"past_abilities"`
// A set of sprites used to depict this Pokémon in the game. A visual
// representation of the various sprites can be found at PokeAPI/sprites
Sprites PokemonSprites `json:"sprites"`
// A set of cries used to depict this Pokémon in the game. A visual
// representation of the various cries can be found at PokeAPI/cries
Cries PokemonCries `json:"cries"`
// The species this Pokémon belongs to.
Species NamedResource[TODO] `json:"species"`
// A list of base stat values for this Pokémon.
Stats []PokemonStat `json:"stats"`
// A list of details showing types this Pokémon has.
Types []PokemonType `json:"types"`
}
Pokémon are the creatures that inhabit the world of the Pokémon games. They can be caught using Pokéballs and trained by battling with other Pokémon. Each Pokémon belongs to a specific species but may take on a variant which makes it differ from other Pokémon of the same species, such as base stats, available abilities and typings. See Bulbapedia for greater detail.
type PokemonAbility ¶
type PokemonAbility struct {
// Whether or not this is a hidden ability.
IsHidden bool `json:"is_hidden"`
// The slot this ability occupies in this Pokémon species.
Slot int `json:"slot"`
// The ability the Pokémon may have.
Ability NamedResource[TODO] `json:"ability"`
}
type PokemonAbilityPast ¶
type PokemonAbilityPast struct {
// The last generation in which the referenced pokémon had the listed
// abilities.
Generation NamedResource[TODO] `json:"generation"`
// The abilities the referenced pokémon had up to and including the listed
// generation. If null, the slot was previously empty.
Abilities []PokemonAbility `json:"abilities"`
}
type PokemonCries ¶
type PokemonCries struct {
// The latest depiction of this Pokémon's cry.
Latest URL `json:"latest"`
// The legacy depiction of this Pokémon's cry.
Legacy URL `json:"legacy"`
}
A set of cries used to depict this Pokémon in the game.
type PokemonEntry ¶
type PokemonEntry struct {
// The index of this Pokémon species entry within the Pokédex.
EntryNumber int
// The Pokémon species being encountered.
PokemonSpecies NamedResource[TODO]
}
type PokemonForm ¶
type PokemonForm struct {
// The identifier for this resource.
ID int `json:"id"`
// The name for this resource.
Name string `json:"name"`
// The order in which forms should be sorted within all forms. Multiple
// forms may have equal order, in which case they should fall back on
// sorting by name.
Order int `json:"order"`
// The order in which forms should be sorted within a species' forms.
FormOrder int `json:"form_order"`
// True for exactly one form used as the default for each Pokémon.
IsDefault bool `json:"is_default"`
// Whether or not this form can only happen during battle.
IsBattleOnly bool `json:"is_battle_only"`
// Whether or not this form requires mega evolution.
IsMega bool `json:"is_mega"`
// The name of this form.
FormName string `json:"form_name"`
// The Pokémon that can take on this form.
Pokemon NamedResource[Pokemon] `json:"pokemon"`
// A list of details showing types this Pokémon form has.
Types []PokemonFormType `json:"types"`
// A set of sprites used to depict this Pokémon form in the game.
Sprites PokemonFormSprites `json:"sprites"`
// The version group this Pokémon form was introduced in.
VersionGroup NamedResource[TODO] `json:"version_group"`
// The form specific full name of this Pokémon form, or empty if the form
// does not have a specific name.
FormNames []Name `json:"form_names"`
// The form specific full name of this Pokémon form, or empty if the form
// does not have a specific name.
Names []Name `json:"names"`
}
Some Pokémon may appear in one of multiple, visually different forms. These differences are purely cosmetic. For variations within a Pokémon species, which do differ in more than just visuals, the 'Pokémon' entity is used to represent such a variety.
type PokemonFormSprites ¶
type PokemonFormSprites struct {
// The default depiction of this Pokémon form from the front in battle.
FrontDefault string `json:"front_default"`
// The shiny depiction of this Pokémon form from the front in battle.
FrontShiny string `json:"front_shiny"`
// The default depiction of this Pokémon form from the back in battle.
BackDefault string `json:"back_default"`
// The shiny depiction of this Pokémon form from the back in battle.
BackShiny string `json:"back_shiny"`
}
A set of sprites used to depict this Pokémon form in the game.
type PokemonFormType ¶
type PokemonFormType struct {
// The order the Pokémon's types are listed in.
Slot int `json:"slot"`
// The type the referenced Form has.
Type NamedResource[TODO] `json:"type"`
}
type PokemonHeldItem ¶
type PokemonHeldItem struct {
// The item the referenced Pokémon holds.
Item NamedResource[TODO] `json:"item"`
// The details of the different versions in which the item is held.
VersionDetails []PokemonHeldItemVersion `json:"version_details"`
}
type PokemonHeldItemVersion ¶
type PokemonHeldItemVersion struct {
// The version in which the item is held.
Version NamedResource[TODO] `json:"version"`
// How often the item is held.
Rarity int `json:"rarity"`
}
type PokemonMove ¶
type PokemonMove struct {
// The move the Pokémon can learn.
Move NamedResource[TODO] `json:"move"`
// The details of the version in which the Pokémon can learn the move.
VersionGroupDetails []PokemonMoveVersion `json:"version_group_details"`
}
type PokemonMoveVersion ¶
type PokemonMoveVersion struct {
// The method by which the move is learned.
MoveLearnMethod NamedResource[TODO] `json:"move_learn_method"`
// The version group in which the move is learned.
VersionGroup NamedResource[TODO] `json:"version_group"`
// The minimum level to learn the move.
LevelLearnedAt int `json:"level_learned_at"`
// Order by which the pokemon will learn the move. A newly learnt move will
// replace the move with lowest order.
Order int `json:"order"`
}
type PokemonSprites ¶
type PokemonSprites struct {
// The default depiction of this Pokémon from the front in battle.
FrontDefault URL `json:"front_default"`
// The shiny depiction of this Pokémon from the front in battle.
FrontShiny URL `json:"front_shiny"`
// The female depiction of this Pokémon from the front in battle.
FrontFemale URL `json:"front_female"`
// The shiny female depiction of this Pokémon from the front in battle.
FrontShinyFemale URL `json:"front_shiny_female"`
// The default depiction of this Pokémon from the back in battle.
BackDefault URL `json:"back_default"`
// The shiny depiction of this Pokémon from the back in battle.
BackShiny URL `json:"back_shiny"`
// The female depiction of this Pokémon from the back in battle.
BackFemale URL `json:"back_female"`
// The shiny female depiction of this Pokémon from the back in battle.
BackShinyFemale URL `json:"back_shiny_female"`
}
A set of sprites used to depict this Pokémon in the game.
type PokemonStat ¶
type PokemonStat struct {
// The stat the Pokémon has.
Stat NamedResource[TODO] `json:"stat"`
// The effort points (EV) the Pokémon has in the stat.
Effort int `json:"effort"`
// The base value of the stat.
BaseStat int `json:"base_stat"`
}
type PokemonType ¶
type PokemonType struct {
// The order the Pokémon's types are listed in.
Slot int `json:"slot"`
// The type the referenced Pokémon has.
Type NamedResource[TODO] `json:"type"`
}
type PokemonTypePast ¶
type PokemonTypePast struct {
// The last generation in which the referenced pokémon had the listed
// types.
Generation NamedResource[TODO] `json:"generation"`
// The types the referenced pokémon had up to and including the listed
// generation.
Types []PokemonType `json:"types"`
}
type Region ¶
type Region struct {
// The identifier for this resource.
ID int
// A list of locations that can be found in this region.
Locations []NamedResource[Location]
// The name for this resource.
Name string
// The name of this resource listed in different languages.
Names []Name
// The generation this region was introduced in.
MainGeneration NamedResource[Generation]
// A list of pokédexes that catalogue Pokémon in this region.
Pokedexes []NamedResource[Pokedex]
// A list of version groups where this region can be visited.
VersionGroups []NamedResource[TODO]
}
type TODO ¶
TODO is a placeholder type, indicating that a struct is not yet implemented. Patches welcome!
As it's just map[string]any, the data can still be read, it will just not be structured.
type Version ¶
type Version struct {
// The identifier for this resource.
ID int `json:"id"`
// The identifier for this resource.
Name string `json:"name"`
// The name of this resource listed in different languages.
Names []TODO `json:"names"`
// The version group this version belongs to.
VersionGroup NamedResource[TODO] `json:"version_group"`
}
type VersionGameIndex ¶
type VersionGameIndex struct {
// The internal id of an API resource within game data.
GameIndex int `json:"game_index"`
// The version relevant to this game index.
Version NamedResource[TODO] `json:"version"`
}