anagramasdk

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

README

Anagrama Go API Library

Go Reference

The Anagrama Go library provides convenient access to the Anagrama REST API from applications written in Go.

It is generated with Stainless.

Installation

import (
	"github.com/AnagramaGames/anagrama-go" // imported as anagramasdk
)

Or to pin the version:

go get -u 'github.com/AnagramaGames/anagrama-go@v0.7.0'

Requirements

This library requires Go 1.22+.

Usage

The full API of this library can be found in api.md.

package main

import (
	"context"
	"fmt"

	"github.com/AnagramaGames/anagrama-go"
	"github.com/AnagramaGames/anagrama-go/option"
)

func main() {
	client := anagramasdk.NewClient(
		option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("ANAGRAMA_API_KEY")
	)
	response, err := client.Words.GetRandom(context.TODO(), anagramasdk.WordGetRandomParams{
		Count: anagramasdk.Int(1),
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", response.Count)
}

Request fields

The anagramasdk library uses the omitzero semantics from the Go 1.24+ encoding/json release for request fields.

Required primitive fields (int64, string, etc.) feature the tag `json:"...,required"`. These fields are always serialized, even their zero values.

Optional primitive types are wrapped in a param.Opt[T]. These fields can be set with the provided constructors, anagramasdk.String(string), anagramasdk.Int(int64), etc.

Any param.Opt[T], map, slice, struct or string enum uses the tag `json:"...,omitzero"`. Its zero value is considered omitted.

The param.IsOmitted(any) function can confirm the presence of any omitzero field.

p := anagramasdk.ExampleParams{
	ID:   "id_xxx",                  // required property
	Name: anagramasdk.String("..."), // optional property

	Point: anagramasdk.Point{
		X: 0,                  // required field will serialize as 0
		Y: anagramasdk.Int(1), // optional field will serialize as 1
		// ... omitted non-required fields will not be serialized
	},

	Origin: anagramasdk.Origin{}, // the zero value of [Origin] is considered omitted
}

To send null instead of a param.Opt[T], use param.Null[T](). To send null instead of a struct T, use param.NullStruct[T]().

p.Name = param.Null[string]()       // 'null' instead of string
p.Point = param.NullStruct[Point]() // 'null' instead of struct

param.IsNull(p.Name)  // true
param.IsNull(p.Point) // true

Request structs contain a .SetExtraFields(map[string]any) method which can send non-conforming fields in the request body. Extra fields overwrite any struct fields with a matching key. For security reasons, only use SetExtraFields with trusted data.

To send a custom value instead of a struct, use param.Override[T](value).

// In cases where the API specifies a given type,
// but you want to send something else, use [SetExtraFields]:
p.SetExtraFields(map[string]any{
	"x": 0.01, // send "x" as a float instead of int
})

// Send a number instead of an object
custom := param.Override[anagramasdk.FooParams](12)
Request unions

Unions are represented as a struct with fields prefixed by "Of" for each of its variants, only one field can be non-zero. The non-zero field will be serialized.

Sub-properties of the union can be accessed via methods on the union struct. These methods return a mutable pointer to the underlying data, if present.

// Only one field can be non-zero, use param.IsOmitted() to check if a field is set
type AnimalUnionParam struct {
	OfCat *Cat `json:",omitzero,inline`
	OfDog *Dog `json:",omitzero,inline`
}

animal := AnimalUnionParam{
	OfCat: &Cat{
		Name: "Whiskers",
		Owner: PersonParam{
			Address: AddressParam{Street: "3333 Coyote Hill Rd", Zip: 0},
		},
	},
}

// Mutating a field
if address := animal.GetOwner().GetAddress(); address != nil {
	address.ZipCode = 94304
}
Response objects

All fields in response structs are ordinary value types (not pointers or wrappers). Response structs also include a special JSON field containing metadata about each property.

type Animal struct {
	Name   string `json:"name,nullable"`
	Owners int    `json:"owners"`
	Age    int    `json:"age"`
	JSON   struct {
		Name        respjson.Field
		Owner       respjson.Field
		Age         respjson.Field
		ExtraFields map[string]respjson.Field
	} `json:"-"`
}

To handle optional data, use the .Valid() method on the JSON field. .Valid() returns true if a field is not null, not present, or couldn't be marshaled.

If .Valid() is false, the corresponding field will simply be its zero value.

raw := `{"owners": 1, "name": null}`

var res Animal
json.Unmarshal([]byte(raw), &res)

// Accessing regular fields

res.Owners // 1
res.Name   // ""
res.Age    // 0

// Optional field checks

res.JSON.Owners.Valid() // true
res.JSON.Name.Valid()   // false
res.JSON.Age.Valid()    // false

// Raw JSON values

res.JSON.Owners.Raw()                  // "1"
res.JSON.Name.Raw() == "null"          // true
res.JSON.Name.Raw() == respjson.Null   // true
res.JSON.Age.Raw() == ""               // true
res.JSON.Age.Raw() == respjson.Omitted // true

These .JSON structs also include an ExtraFields map containing any properties in the json response that were not specified in the struct. This can be useful for API features not yet present in the SDK.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
Response Unions

In responses, unions are represented by a flattened struct containing all possible fields from each of the object variants. To convert it to a variant use the .AsFooVariant() method or the .AsAny() method if present.

If a response value union contains primitive values, primitive fields will be alongside the properties but prefixed with Of and feature the tag json:"...,inline".

type AnimalUnion struct {
	// From variants [Dog], [Cat]
	Owner Person `json:"owner"`
	// From variant [Dog]
	DogBreed string `json:"dog_breed"`
	// From variant [Cat]
	CatBreed string `json:"cat_breed"`
	// ...

	JSON struct {
		Owner respjson.Field
		// ...
	} `json:"-"`
}

// If animal variant
if animal.Owner.Address.ZipCode == "" {
	panic("missing zip code")
}

// Switch on the variant
switch variant := animal.AsAny().(type) {
case Dog:
case Cat:
default:
	panic("unexpected type")
}
RequestOptions

This library uses the functional options pattern. Functions defined in the option package return a RequestOption, which is a closure that mutates a RequestConfig. These options can be supplied to the client or at individual requests. For example:

client := anagramasdk.NewClient(
	// Adds a header to every request made by the client
	option.WithHeader("X-Some-Header", "custom_header_info"),
)

client.Words.GetRandom(context.TODO(), ...,
	// Override the header
	option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
	// Add an undocumented field to the request body, using sjson syntax
	option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)

The request option option.WithDebugLog(nil) may be helpful while debugging.

See the full list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use .ListAutoPaging() methods to iterate through items across all pages:

Or you can use simple .List() methods to fetch a single page and receive a standard response object with additional helper methods like .GetNextPage(), e.g.:

Errors

When the API returns a non-success status code, we return an error with type *anagramasdk.Error. This contains the StatusCode, *http.Request, and *http.Response values of the request, as well as the JSON of the error body (much like other response objects in the SDK).

To handle errors, we recommend that you use the errors.As pattern:

_, err := client.Words.GetRandom(context.TODO(), anagramasdk.WordGetRandomParams{
	Count: anagramasdk.Int(3),
})
if err != nil {
	var apierr *anagramasdk.Error
	if errors.As(err, &apierr) {
		println(string(apierr.DumpRequest(true)))  // Prints the serialized HTTP request
		println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
	}
	panic(err.Error()) // GET "/v1/words/random": 400 Bad Request { ... }
}

When other errors occur, they are returned unwrapped; for example, if HTTP transport fails, you might receive *url.Error wrapping *net.OpError.

Timeouts

Requests do not time out by default; use context to configure a timeout for a request lifecycle.

Note that if a request is retried, the context timeout does not start over. To set a per-retry timeout, use option.WithRequestTimeout().

// This sets the timeout for the request, including all the retries.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client.Words.GetRandom(
	ctx,
	anagramasdk.WordGetRandomParams{
		Count: anagramasdk.Int(3),
	},
	// This sets the per-retry timeout
	option.WithRequestTimeout(20*time.Second),
)
File uploads

Request parameters that correspond to file uploads in multipart requests are typed as io.Reader. The contents of the io.Reader will by default be sent as a multipart form part with the file name of "anonymous_file" and content-type of "application/octet-stream".

The file name and content-type can be customized by implementing Name() string or ContentType() string on the run-time type of io.Reader. Note that os.File implements Name() string, so a file returned by os.Open will be sent with the file name on disk.

We also provide a helper anagramasdk.File(reader io.Reader, filename string, contentType string) which can be used to wrap any io.Reader with the appropriate file name and content type.

Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff. We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors.

You can use the WithMaxRetries option to configure or disable this:

// Configure the default for all requests:
client := anagramasdk.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// Override per-request:
client.Words.GetRandom(
	context.TODO(),
	anagramasdk.WordGetRandomParams{
		Count: anagramasdk.Int(3),
	},
	option.WithMaxRetries(5),
)
Accessing raw response data (e.g. response headers)

You can access the raw HTTP response data by using the option.WithResponseInto() request option. This is useful when you need to examine response headers, status codes, or other details.

// Create a variable to store the HTTP response
var response *http.Response
response, err := client.Words.GetRandom(
	context.TODO(),
	anagramasdk.WordGetRandomParams{
		Count: anagramasdk.Int(3),
	},
	option.WithResponseInto(&response),
)
if err != nil {
	// handle error
}
fmt.Printf("%+v\n", response)

fmt.Printf("Status Code: %d\n", response.StatusCode)
fmt.Printf("Headers: %+#v\n", response.Header)
Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can use client.Get, client.Post, and other HTTP verbs. RequestOptions on the client, such as retries, will be respected when making these requests.

var (
    // params can be an io.Reader, a []byte, an encoding/json serializable object,
    // or a "…Params" struct defined in this library.
    params map[string]any

    // result can be an []byte, *http.Response, a encoding/json deserializable object,
    // or a model defined in this library.
    result *http.Response
)
err := client.Post(context.Background(), "/unspecified", params, &result)
if err != nil {
    …
}
Undocumented request params

To make requests using undocumented parameters, you may use either the option.WithQuerySet() or the option.WithJSONSet() methods.

params := FooNewParams{
    ID:   "id_xxxx",
    Data: FooNewParamsData{
        FirstName: anagramasdk.String("John"),
    },
}
client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))
Undocumented response properties

To access undocumented response properties, you may either access the raw JSON of the response as a string with result.JSON.RawJSON(), or get the raw JSON of a particular field on the result with result.JSON.Foo.Raw().

Any fields that are not present on the response struct will be saved and can be accessed by result.JSON.ExtraFields() which returns the extra fields as a map[string]Field.

Middleware

We provide option.WithMiddleware which applies the given middleware to requests.

func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {
	// Before the request
	start := time.Now()
	LogReq(req)

	// Forward the request to the next handler
	res, err = next(req)

	// Handle stuff after the request
	end := time.Now()
	LogRes(res, err, start - end)

    return res, err
}

client := anagramasdk.NewClient(
	option.WithMiddleware(Logger),
)

When multiple middlewares are provided as variadic arguments, the middlewares are applied left to right. If option.WithMiddleware is given multiple times, for example first in the client then the method, the middleware in the client will run first and the middleware given in the method will run next.

You may also replace the default http.Client with option.WithHTTPClient(client). Only one http client is accepted (this overwrites any previous client) and receives requests after any middleware has been applied.

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Contributing

See the contributing documentation.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) param.Opt[bool]

func BoolPtr

func BoolPtr(v bool) *bool

func DefaultClientOptions

func DefaultClientOptions() []option.RequestOption

DefaultClientOptions read from the environment (ANAGRAMA_API_KEY, ANAGRAMA_BASE_URL). This should be used to initialize new clients.

func File

func File(rdr io.Reader, filename string, contentType string) file

func Float

func Float(f float64) param.Opt[float64]

func FloatPtr

func FloatPtr(v float64) *float64

func Int

func Int(i int64) param.Opt[int64]

func IntPtr

func IntPtr(v int64) *int64

func Opt

func Opt[T comparable](v T) param.Opt[T]

func Ptr

func Ptr[T any](v T) *T

func String

func String(s string) param.Opt[string]

func StringPtr

func StringPtr(v string) *string

func Time

func Time(t time.Time) param.Opt[time.Time]

func TimePtr

func TimePtr(v time.Time) *time.Time

Types

type CliAuthCompleteParams

type CliAuthCompleteParams struct {
	// The device code from the authentication session.
	DeviceCode param.Opt[string] `json:"device_code,omitzero"`
	// The user code from the authentication session.
	UserCode param.Opt[string] `json:"user_code,omitzero"`
	// contains filtered or unexported fields
}

func (CliAuthCompleteParams) MarshalJSON

func (r CliAuthCompleteParams) MarshalJSON() (data []byte, err error)

func (*CliAuthCompleteParams) UnmarshalJSON

func (r *CliAuthCompleteParams) UnmarshalJSON(data []byte) error

type CliAuthCompleteResponse

type CliAuthCompleteResponse struct {
	// Always `true` on success.
	Ok bool `json:"ok,required"`
	// The resulting session status.
	Status constant.Approved `json:"status,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Ok          respjson.Field
		Status      respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CliAuthCompleteResponse) RawJSON

func (r CliAuthCompleteResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CliAuthCompleteResponse) UnmarshalJSON

func (r *CliAuthCompleteResponse) UnmarshalJSON(data []byte) error

type CliAuthPollParams

type CliAuthPollParams struct {
	// The device code returned from `/cli/auth/start`.
	DeviceCode param.Opt[string] `json:"device_code,omitzero"`
	// The user code returned from `/cli/auth/start`.
	UserCode param.Opt[string] `json:"user_code,omitzero"`
	// contains filtered or unexported fields
}

func (CliAuthPollParams) MarshalJSON

func (r CliAuthPollParams) MarshalJSON() (data []byte, err error)

func (*CliAuthPollParams) UnmarshalJSON

func (r *CliAuthPollParams) UnmarshalJSON(data []byte) error

type CliAuthPollResponse

type CliAuthPollResponse struct {
	// The API token (prefixed with `cli_`). Store this securely and use it as a Bearer
	// token for authenticated API calls.
	Token string `json:"token,required"`
	// The session status. Always `"approved"` for a 200 response.
	Status constant.Approved `json:"status,required"`
	// Basic profile information for the authenticated user.
	User CliAuthPollResponseUser `json:"user,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Token       respjson.Field
		Status      respjson.Field
		User        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CliAuthPollResponse) RawJSON

func (r CliAuthPollResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CliAuthPollResponse) UnmarshalJSON

func (r *CliAuthPollResponse) UnmarshalJSON(data []byte) error

type CliAuthPollResponseUser

type CliAuthPollResponseUser struct {
	// The user's display name. Falls back to username, first name, last name, or
	// "Player".
	DisplayName string `json:"displayName,required"`
	// The user's unique identifier.
	UserID string `json:"userId,required"`
	// The user's username, or null if not set.
	Username string `json:"username,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DisplayName respjson.Field
		UserID      respjson.Field
		Username    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Basic profile information for the authenticated user.

func (CliAuthPollResponseUser) RawJSON

func (r CliAuthPollResponseUser) RawJSON() string

Returns the unmodified JSON received from the API

func (*CliAuthPollResponseUser) UnmarshalJSON

func (r *CliAuthPollResponseUser) UnmarshalJSON(data []byte) error

type CliAuthService

type CliAuthService struct {
	Options []option.RequestOption
}

CliAuthService contains methods and other services that help with interacting with the anagrama API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCliAuthService method instead.

func NewCliAuthService

func NewCliAuthService(opts ...option.RequestOption) (r CliAuthService)

NewCliAuthService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CliAuthService) Complete

Called by the web application after the user approves the CLI authentication request. This endpoint requires a valid Anagrama web session (browser cookie-based auth) and is not intended for direct SDK use.

Approves the pending session identified by `deviceCode` or `userCode`, generates an API token, and stores it. The CLI can then retrieve the token by polling `/cli/auth/poll`.

func (*CliAuthService) Poll

Polls the status of a device-flow authentication session. The CLI should call this endpoint at the interval specified in the `/cli/auth/start` response until it receives a status of `"approved"` with a token.

The token is returned exactly once -- if the session has already been consumed by a previous successful poll, a `409` status is returned.

Rate limited to 30 requests per minute per IP address.

func (*CliAuthService) Start

Initiates a device-flow authentication session. Returns a device code, a human-readable user code, and a verification URL. The CLI should display the verification URL and user code to the user, then poll `/cli/auth/poll` until the session is approved.

Rate limited to 10 requests per minute per IP address.

type CliAuthStartParams

type CliAuthStartParams struct {
	// The name of the CLI client application (e.g., "anagrama-cli").
	ClientName param.Opt[string] `json:"clientName,omitzero"`
	// A human-readable label for this token (e.g., "My Laptop"). HTML special
	// characters are stripped. Truncated to 100 characters.
	Label param.Opt[string] `json:"label,omitzero"`
	// contains filtered or unexported fields
}

func (CliAuthStartParams) MarshalJSON

func (r CliAuthStartParams) MarshalJSON() (data []byte, err error)

func (*CliAuthStartParams) UnmarshalJSON

func (r *CliAuthStartParams) UnmarshalJSON(data []byte) error

type CliAuthStartResponse

type CliAuthStartResponse struct {
	// Unique device code for this authentication session. Used when polling for
	// approval.
	DeviceCode string `json:"device_code,required"`
	// Number of seconds until this authentication session expires. Default is 900 (15
	// minutes).
	ExpiresIn int64 `json:"expires_in,required"`
	// Minimum number of seconds the CLI should wait between poll requests. Default
	// is 3.
	Interval int64 `json:"interval,required"`
	// A short, human-readable code displayed to the user for verification.
	UserCode string `json:"user_code,required"`
	// The full URL the user should visit to authorize the CLI. Includes the
	// device_code and user_code as query parameters.
	VerificationURL string `json:"verification_url,required" format:"uri"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DeviceCode      respjson.Field
		ExpiresIn       respjson.Field
		Interval        respjson.Field
		UserCode        respjson.Field
		VerificationURL respjson.Field
		ExtraFields     map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CliAuthStartResponse) RawJSON

func (r CliAuthStartResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CliAuthStartResponse) UnmarshalJSON

func (r *CliAuthStartResponse) UnmarshalJSON(data []byte) error

type CliService

type CliService struct {
	Options []option.RequestOption
	Auth    CliAuthService
}

CliService contains methods and other services that help with interacting with the anagrama API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCliService method instead.

func NewCliService

func NewCliService(opts ...option.RequestOption) (r CliService)

NewCliService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

type Client

type Client struct {
	Options    []option.RequestOption
	Words      WordService
	Puzzles    PuzzleService
	Dictionary DictionaryService
	Wordsets   WordsetService
	Cli        CliService
}

Client creates a struct with services and top level methods that help with interacting with the anagrama API. You should not instantiate this client directly, and instead use the NewClient method instead.

func NewClient

func NewClient(opts ...option.RequestOption) (r Client)

NewClient generates a new client with the default option read from the environment (ANAGRAMA_API_KEY, ANAGRAMA_BASE_URL). The option passed in as arguments are applied after these default arguments, and all option will be passed down to the services and requests that this client makes.

func (*Client) Delete

func (r *Client) Delete(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Delete makes a DELETE request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Execute

func (r *Client) Execute(ctx context.Context, method string, path string, params any, res any, opts ...option.RequestOption) error

Execute makes a request with the given context, method, URL, request params, response, and request options. This is useful for hitting undocumented endpoints while retaining the base URL, auth, retries, and other options from the client.

If a byte slice or an io.Reader is supplied to params, it will be used as-is for the request body.

The params is by default serialized into the body using encoding/json. If your type implements a MarshalJSON function, it will be used instead to serialize the request. If a URLQuery method is implemented, the returned url.Values will be used as query strings to the url.

If your params struct uses param.Field, you must provide either [MarshalJSON], [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a struct uses param.Field without specifying how it is serialized.

Any "…Params" object defined in this library can be used as the request argument. Note that 'path' arguments will not be forwarded into the url.

The response body will be deserialized into the res variable, depending on its type:

  • A pointer to a *http.Response is populated by the raw response.
  • A pointer to a byte array will be populated with the contents of the request body.
  • A pointer to any other type uses this library's default JSON decoding, which respects UnmarshalJSON if it is defined on the type.
  • A nil value will not read the response body.

For even greater flexibility, see option.WithResponseInto and option.WithResponseBodyInto.

func (*Client) Get

func (r *Client) Get(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Get makes a GET request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Patch

func (r *Client) Patch(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Patch makes a PATCH request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Post

func (r *Client) Post(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Post makes a POST request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Put

func (r *Client) Put(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Put makes a PUT request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

type DictionaryDefinition added in v0.5.0

type DictionaryDefinition struct {
	// The definition text.
	Gloss string `json:"gloss,required"`
	// An example sentence demonstrating usage.
	Example string `json:"example"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Gloss       respjson.Field
		Example     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A single definition of a word with an optional usage example.

func (DictionaryDefinition) RawJSON added in v0.5.0

func (r DictionaryDefinition) RawJSON() string

Returns the unmodified JSON received from the API

func (*DictionaryDefinition) UnmarshalJSON added in v0.5.0

func (r *DictionaryDefinition) UnmarshalJSON(data []byte) error

type DictionaryEntry added in v0.5.0

type DictionaryEntry struct {
	// Part of speech (e.g., "noun", "verb", "adjective").
	Pos string `json:"pos,required"`
	// Words with opposite meaning.
	Antonyms []string `json:"antonyms"`
	// Definitions for this part of speech.
	Definitions []DictionaryDefinition `json:"definitions"`
	// Words derived from this word.
	Derived []string `json:"derived"`
	// The etymology (origin) of the word.
	Etymology string `json:"etymology"`
	// Inflected forms of the word (e.g., plural, past tense).
	Forms []string `json:"forms"`
	// More general terms (e.g., "animal" is a hypernym of "dog").
	Hypernyms []string `json:"hypernyms"`
	// More specific terms (e.g., "poodle" is a hyponym of "dog").
	Hyponyms []string `json:"hyponyms"`
	// Semantically related words.
	Related []string `json:"related"`
	// Words with similar meaning.
	Synonyms []string `json:"synonyms"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Pos         respjson.Field
		Antonyms    respjson.Field
		Definitions respjson.Field
		Derived     respjson.Field
		Etymology   respjson.Field
		Forms       respjson.Field
		Hypernyms   respjson.Field
		Hyponyms    respjson.Field
		Related     respjson.Field
		Synonyms    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A dictionary entry for a specific part of speech, including definitions, etymology, and related words.

func (DictionaryEntry) RawJSON added in v0.5.0

func (r DictionaryEntry) RawJSON() string

Returns the unmodified JSON received from the API

func (*DictionaryEntry) UnmarshalJSON added in v0.5.0

func (r *DictionaryEntry) UnmarshalJSON(data []byte) error

type DictionaryLanguagesResponse added in v0.5.0

type DictionaryLanguagesResponse struct {
	// Total number of available languages.
	Count int64 `json:"count,required"`
	// Array of available languages with entry counts.
	Languages []LanguageInfo `json:"languages,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Languages   respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (DictionaryLanguagesResponse) RawJSON added in v0.5.0

func (r DictionaryLanguagesResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*DictionaryLanguagesResponse) UnmarshalJSON added in v0.5.0

func (r *DictionaryLanguagesResponse) UnmarshalJSON(data []byte) error

type DictionaryLookupParams added in v0.5.0

type DictionaryLookupParams struct {
	// Maximum number of definitions to return per entry. Clamped to [0, 50].
	Definitions param.Opt[int64] `query:"definitions,omitzero" json:"-"`
	// Comma-separated list of fields to include in the response (e.g.,
	// "definitions,etymology,synonyms"). When omitted, all fields are returned.
	Fields param.Opt[string] `query:"fields,omitzero" json:"-"`
	// ISO 639-1 language code. Defaults to "en" (English).
	Lang param.Opt[string] `query:"lang,omitzero" json:"-"`
	// Maximum number of results to return for fuzzy searches. Clamped to [1, 20].
	// Ignored for exact lookups.
	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
	// Filter results by part of speech (e.g., "noun", "verb", "adjective").
	Pos param.Opt[string] `query:"pos,omitzero" json:"-"`
	// When `"true"`, performs an exact lookup. When `"false"`, performs a fuzzy search
	// returning similar words.
	//
	// Any of "true", "false".
	Exact DictionaryLookupParamsExact `query:"exact,omitzero" json:"-"`
	// When `"true"`, includes usage examples in definitions.
	//
	// Any of "true", "false".
	Examples DictionaryLookupParamsExamples `query:"examples,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (DictionaryLookupParams) URLQuery added in v0.5.0

func (r DictionaryLookupParams) URLQuery() (v url.Values, err error)

URLQuery serializes DictionaryLookupParams's query parameters as `url.Values`.

type DictionaryLookupParamsExact added in v0.5.0

type DictionaryLookupParamsExact string

When `"true"`, performs an exact lookup. When `"false"`, performs a fuzzy search returning similar words.

const (
	DictionaryLookupParamsExactTrue  DictionaryLookupParamsExact = "true"
	DictionaryLookupParamsExactFalse DictionaryLookupParamsExact = "false"
)

type DictionaryLookupParamsExamples added in v0.5.0

type DictionaryLookupParamsExamples string

When `"true"`, includes usage examples in definitions.

const (
	DictionaryLookupParamsExamplesTrue  DictionaryLookupParamsExamples = "true"
	DictionaryLookupParamsExamplesFalse DictionaryLookupParamsExamples = "false"
)

type DictionaryLookupResponse added in v0.5.0

type DictionaryLookupResponse struct {
	// The language code used for the lookup.
	Lang string `json:"lang,required"`
	// Dictionary entries for the word, one per part of speech.
	Results []DictionaryEntry `json:"results,required"`
	// The word that was looked up.
	Word string `json:"word,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Lang        respjson.Field
		Results     respjson.Field
		Word        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Response for an exact dictionary word lookup.

func (DictionaryLookupResponse) RawJSON added in v0.5.0

func (r DictionaryLookupResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*DictionaryLookupResponse) UnmarshalJSON added in v0.5.0

func (r *DictionaryLookupResponse) UnmarshalJSON(data []byte) error

type DictionaryService added in v0.5.0

type DictionaryService struct {
	Options []option.RequestOption
}

DictionaryService contains methods and other services that help with interacting with the anagrama API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewDictionaryService method instead.

func NewDictionaryService added in v0.5.0

func NewDictionaryService(opts ...option.RequestOption) (r DictionaryService)

NewDictionaryService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*DictionaryService) Languages added in v0.5.0

Returns a list of all languages available in the Anagrama dictionary, along with the number of entries for each language. Requires a valid API key as a Bearer token.

func (*DictionaryService) Lookup added in v0.5.0

Retrieves detailed dictionary entries for a word, including definitions, etymology, part of speech, synonyms, antonyms, and related words. When `exact` is set to `false`, performs a fuzzy search and returns matching candidates. Requires a valid API key as a Bearer token.

type Error

type Error = apierror.Error

type LanguageInfo added in v0.5.0

type LanguageInfo struct {
	// ISO 639-1 language code (e.g., "en", "es", "fr").
	Code string `json:"code,required"`
	// Number of dictionary entries available for this language.
	Entries int64 `json:"entries,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Code        respjson.Field
		Entries     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Information about a supported dictionary language.

func (LanguageInfo) RawJSON added in v0.5.0

func (r LanguageInfo) RawJSON() string

Returns the unmodified JSON received from the API

func (*LanguageInfo) UnmarshalJSON added in v0.5.0

func (r *LanguageInfo) UnmarshalJSON(data []byte) error

type PuzzleGenerateParams added in v0.5.0

type PuzzleGenerateParams struct {
	// Optional seed string for deterministic puzzle generation. The same seed and
	// difficulty always produce the same puzzle.
	Seed param.Opt[string] `query:"seed,omitzero" json:"-"`
	// Puzzle difficulty level. Controls word length, number of hints, and attempts
	// allowed.
	//
	// Any of "easy", "medium", "hard".
	Difficulty PuzzleGenerateParamsDifficulty `query:"difficulty,omitzero" json:"-"`
	// When `"true"`, reduces hints and attempts for an extra challenge.
	//
	// Any of "true", "false".
	HardMode PuzzleGenerateParamsHardMode `query:"hardMode,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (PuzzleGenerateParams) URLQuery added in v0.5.0

func (r PuzzleGenerateParams) URLQuery() (v url.Values, err error)

URLQuery serializes PuzzleGenerateParams's query parameters as `url.Values`.

type PuzzleGenerateParamsDifficulty added in v0.5.0

type PuzzleGenerateParamsDifficulty string

Puzzle difficulty level. Controls word length, number of hints, and attempts allowed.

const (
	PuzzleGenerateParamsDifficultyEasy   PuzzleGenerateParamsDifficulty = "easy"
	PuzzleGenerateParamsDifficultyMedium PuzzleGenerateParamsDifficulty = "medium"
	PuzzleGenerateParamsDifficultyHard   PuzzleGenerateParamsDifficulty = "hard"
)

type PuzzleGenerateParamsHardMode added in v0.5.0

type PuzzleGenerateParamsHardMode string

When `"true"`, reduces hints and attempts for an extra challenge.

const (
	PuzzleGenerateParamsHardModeTrue  PuzzleGenerateParamsHardMode = "true"
	PuzzleGenerateParamsHardModeFalse PuzzleGenerateParamsHardMode = "false"
)

type PuzzleHint added in v0.5.0

type PuzzleHint struct {
	// The letter revealed by this hint.
	Letter string `json:"letter,required"`
	// The order in which this hint should be revealed (0-based).
	Order int64 `json:"order,required"`
	// The zero-based index of the letter in the target word.
	Position int64 `json:"position,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Letter      respjson.Field
		Order       respjson.Field
		Position    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A positional hint revealing one letter of the target word.

func (PuzzleHint) RawJSON added in v0.5.0

func (r PuzzleHint) RawJSON() string

Returns the unmodified JSON received from the API

func (*PuzzleHint) UnmarshalJSON added in v0.5.0

func (r *PuzzleHint) UnmarshalJSON(data []byte) error

type PuzzleMetadata added in v0.5.0

type PuzzleMetadata struct {
	// Number of alternative valid solutions.
	AltCount int64 `json:"altCount,required"`
	// Whether the target word contains repeated letters.
	HasRepeats bool `json:"hasRepeats,required"`
	// Number of unique letters in the letter pool.
	PoolSize int64 `json:"poolSize,required"`
	// Number of vowels in the target word.
	VowelCount int64 `json:"vowelCount,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		AltCount    respjson.Field
		HasRepeats  respjson.Field
		PoolSize    respjson.Field
		VowelCount  respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

Metadata about the generated puzzle for analytics and difficulty calibration.

func (PuzzleMetadata) RawJSON added in v0.5.0

func (r PuzzleMetadata) RawJSON() string

Returns the unmodified JSON received from the API

func (*PuzzleMetadata) UnmarshalJSON added in v0.5.0

func (r *PuzzleMetadata) UnmarshalJSON(data []byte) error

type PuzzleResponse added in v0.5.0

type PuzzleResponse struct {
	// Alternative valid anagram solutions.
	Alts []string `json:"alts,required"`
	// Definitions for the target word and alternatives. Keys are words, values are
	// definition strings or null if no definition is available.
	Definitions map[string]string `json:"definitions,required"`
	// The difficulty level of the puzzle.
	//
	// Any of "easy", "medium", "hard".
	Difficulty PuzzleResponseDifficulty `json:"difficulty,required"`
	// The feedback mode for guesses (e.g., "exact", "positional").
	FeedbackMode string `json:"feedbackMode,required"`
	// Pre-generated hints revealing individual letters.
	Hints []PuzzleHint `json:"hints,required"`
	// Maximum number of attempts allowed.
	MaxAttempts int64 `json:"maxAttempts,required"`
	// Maximum number of hints available.
	MaxHints int64 `json:"maxHints,required"`
	// Metadata about the generated puzzle for analytics and difficulty calibration.
	Metadata PuzzleMetadata `json:"metadata,required"`
	// The sorted pool of available letters.
	Pool string `json:"pool,required"`
	// The scrambled version of the target word.
	Scramble string `json:"scramble,required"`
	// The seed used for puzzle generation. Can be passed back to reproduce this exact
	// puzzle.
	Seed string `json:"seed,required"`
	// The target word the player must unscramble.
	Target string `json:"target,required"`
	// The length of the target word.
	WordLength int64 `json:"wordLength,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Alts         respjson.Field
		Definitions  respjson.Field
		Difficulty   respjson.Field
		FeedbackMode respjson.Field
		Hints        respjson.Field
		MaxAttempts  respjson.Field
		MaxHints     respjson.Field
		Metadata     respjson.Field
		Pool         respjson.Field
		Scramble     respjson.Field
		Seed         respjson.Field
		Target       respjson.Field
		WordLength   respjson.Field
		ExtraFields  map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A generated anagram puzzle with target word, scrambled letters, hints, and metadata.

func (PuzzleResponse) RawJSON added in v0.5.0

func (r PuzzleResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*PuzzleResponse) UnmarshalJSON added in v0.5.0

func (r *PuzzleResponse) UnmarshalJSON(data []byte) error

type PuzzleResponseDifficulty added in v0.5.0

type PuzzleResponseDifficulty string

The difficulty level of the puzzle.

const (
	PuzzleResponseDifficultyEasy   PuzzleResponseDifficulty = "easy"
	PuzzleResponseDifficultyMedium PuzzleResponseDifficulty = "medium"
	PuzzleResponseDifficultyHard   PuzzleResponseDifficulty = "hard"
)

type PuzzleService added in v0.5.0

type PuzzleService struct {
	Options []option.RequestOption
}

PuzzleService contains methods and other services that help with interacting with the anagrama API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewPuzzleService method instead.

func NewPuzzleService added in v0.5.0

func NewPuzzleService(opts ...option.RequestOption) (r PuzzleService)

NewPuzzleService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*PuzzleService) Generate added in v0.5.0

func (r *PuzzleService) Generate(ctx context.Context, query PuzzleGenerateParams, opts ...option.RequestOption) (res *PuzzleResponse, err error)

Generates a new anagram puzzle with a target word, scrambled letters, hints, alternative solutions, and metadata. Difficulty controls word length and hint availability. An optional seed allows reproducible puzzle generation. Requires a valid API key as a Bearer token.

type WordDailyParams added in v0.5.0

type WordDailyParams struct {
	// IANA timezone identifier used to resolve the current calendar date (e.g.,
	// "America/New_York", "Europe/London"). Defaults to "UTC".
	Tz param.Opt[string] `query:"tz,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WordDailyParams) URLQuery added in v0.5.0

func (r WordDailyParams) URLQuery() (v url.Values, err error)

URLQuery serializes WordDailyParams's query parameters as `url.Values`.

type WordDailyResponse added in v0.6.0

type WordDailyResponse struct {
	// The date (YYYY-MM-DD) for which this word was selected, resolved in the
	// requested timezone.
	Date time.Time `json:"date,required" format:"date"`
	// The IANA timezone used to resolve the date.
	Timezone string `json:"timezone,required"`
	// The daily word. Always 5-6 characters long.
	Word string `json:"word,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Date        respjson.Field
		Timezone    respjson.Field
		Word        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WordDailyResponse) RawJSON added in v0.6.0

func (r WordDailyResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WordDailyResponse) UnmarshalJSON added in v0.6.0

func (r *WordDailyResponse) UnmarshalJSON(data []byte) error

type WordGetDailyParams added in v0.5.0

type WordGetDailyParams struct {
	// IANA timezone identifier used to resolve the current calendar date (e.g.,
	// "America/New_York", "Europe/London"). Defaults to "UTC".
	Tz param.Opt[string] `query:"tz,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WordGetDailyParams) URLQuery added in v0.5.0

func (r WordGetDailyParams) URLQuery() (v url.Values, err error)

URLQuery serializes WordGetDailyParams's query parameters as `url.Values`.

type WordGetDailyResponse

type WordGetDailyResponse struct {
	// The date (YYYY-MM-DD) for which this word was selected, resolved in the
	// requested timezone.
	Date time.Time `json:"date,required" format:"date"`
	// The IANA timezone used to resolve the date.
	Timezone string `json:"timezone,required"`
	// The daily word. Always 5-6 characters long.
	Word string `json:"word,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Date        respjson.Field
		Timezone    respjson.Field
		Word        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WordGetDailyResponse) RawJSON

func (r WordGetDailyResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WordGetDailyResponse) UnmarshalJSON

func (r *WordGetDailyResponse) UnmarshalJSON(data []byte) error

type WordGetRandomParams

type WordGetRandomParams struct {
	// Number of random words to return. Clamped to the range [1, 10]. Defaults to 1.
	Count param.Opt[int64] `query:"count,omitzero" json:"-"`
	// Maximum word length (inclusive). Clamped to the range [3, 15]. Defaults to 15.
	// If minLength > maxLength, they are swapped automatically.
	MaxLength param.Opt[int64] `query:"maxLength,omitzero" json:"-"`
	// Minimum word length (inclusive). Clamped to the range [3, 15]. Defaults to 3.
	MinLength param.Opt[int64] `query:"minLength,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WordGetRandomParams) URLQuery

func (r WordGetRandomParams) URLQuery() (v url.Values, err error)

URLQuery serializes WordGetRandomParams's query parameters as `url.Values`.

type WordGetRandomResponse

type WordGetRandomResponse struct {
	// The number of words returned. May be 0 if no words match the length criteria.
	Count int64 `json:"count,required"`
	// Array of random words matching the length criteria.
	Words []string `json:"words,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Words       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WordGetRandomResponse) RawJSON

func (r WordGetRandomResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WordGetRandomResponse) UnmarshalJSON

func (r *WordGetRandomResponse) UnmarshalJSON(data []byte) error

type WordRandomParams added in v0.5.0

type WordRandomParams struct {
	// Number of random words to return. Clamped to the range [1, 10]. Defaults to 1.
	Count param.Opt[int64] `query:"count,omitzero" json:"-"`
	// Maximum word length (inclusive). Clamped to the range [3, 15]. Defaults to 15.
	// If minLength > maxLength, they are swapped automatically.
	MaxLength param.Opt[int64] `query:"maxLength,omitzero" json:"-"`
	// Minimum word length (inclusive). Clamped to the range [3, 15]. Defaults to 3.
	MinLength param.Opt[int64] `query:"minLength,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WordRandomParams) URLQuery added in v0.5.0

func (r WordRandomParams) URLQuery() (v url.Values, err error)

URLQuery serializes WordRandomParams's query parameters as `url.Values`.

type WordRandomResponse added in v0.6.0

type WordRandomResponse struct {
	// The number of words returned. May be 0 if no words match the length criteria.
	Count int64 `json:"count,required"`
	// Array of random words matching the length criteria.
	Words []string `json:"words,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Count       respjson.Field
		Words       respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WordRandomResponse) RawJSON added in v0.6.0

func (r WordRandomResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WordRandomResponse) UnmarshalJSON added in v0.6.0

func (r *WordRandomResponse) UnmarshalJSON(data []byte) error

type WordService

type WordService struct {
	Options []option.RequestOption
}

WordService contains methods and other services that help with interacting with the anagrama API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWordService method instead.

func NewWordService

func NewWordService(opts ...option.RequestOption) (r WordService)

NewWordService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*WordService) Daily added in v0.5.0

func (r *WordService) Daily(ctx context.Context, query WordDailyParams, opts ...option.RequestOption) (res *WordDailyResponse, err error)

Returns a deterministic daily word that is the same for all users on a given calendar date. The word is selected from puzzle-quality words of 5-6 characters in length using a seeded random algorithm. An optional timezone parameter allows the date to be resolved in the caller's local timezone instead of UTC. Requires a valid API key as a Bearer token. Subject to daily rate limiting (1,000 requests/day).

func (*WordService) GetDaily

func (r *WordService) GetDaily(ctx context.Context, query WordGetDailyParams, opts ...option.RequestOption) (res *WordGetDailyResponse, err error)

Returns a deterministic daily word that is the same for all users on a given calendar date. The word is selected from puzzle-quality words of 5-6 characters in length using a seeded random algorithm. An optional timezone parameter allows the date to be resolved in the caller's local timezone instead of UTC. Requires a valid API key as a Bearer token. Subject to daily rate limiting (1,000 requests/day).

func (*WordService) GetRandom

func (r *WordService) GetRandom(ctx context.Context, query WordGetRandomParams, opts ...option.RequestOption) (res *WordGetRandomResponse, err error)

Returns one or more random words from the Anagrama word pool. Words can be filtered by length. Requires a valid API key as a Bearer token. Subject to daily rate limiting (1,000 requests/day).

func (*WordService) Random added in v0.5.0

func (r *WordService) Random(ctx context.Context, query WordRandomParams, opts ...option.RequestOption) (res *WordRandomResponse, err error)

Returns one or more random words from the Anagrama word pool. Words can be filtered by length. Requires a valid API key as a Bearer token. Subject to daily rate limiting (1,000 requests/day).

func (*WordService) Validate added in v0.5.0

func (r *WordService) Validate(ctx context.Context, query WordValidateParams, opts ...option.RequestOption) (res *WordValidateResponse, err error)

Checks whether a given word exists in the Anagrama dictionary for the specified language. Returns validation status and optional part-of-speech information. Requires a valid API key as a Bearer token.

type WordValidateParams added in v0.5.0

type WordValidateParams struct {
	// The word to validate. Case-insensitive. Must be 1-100 characters.
	Word string `query:"word,required" json:"-"`
	// ISO 639-1 language code to validate against. Defaults to "en" (English).
	Lang param.Opt[string] `query:"lang,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WordValidateParams) URLQuery added in v0.5.0

func (r WordValidateParams) URLQuery() (v url.Values, err error)

URLQuery serializes WordValidateParams's query parameters as `url.Values`.

type WordValidateResponse added in v0.5.0

type WordValidateResponse struct {
	// The language code used for validation.
	Lang string `json:"lang,required"`
	// Whether the word exists in the dictionary for the specified language.
	Valid bool `json:"valid,required"`
	// The word that was validated (lowercased).
	Word string `json:"word,required"`
	// The primary part of speech for the word, if found (e.g., "noun", "verb",
	// "adjective").
	Pos string `json:"pos"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Lang        respjson.Field
		Valid       respjson.Field
		Word        respjson.Field
		Pos         respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (WordValidateResponse) RawJSON added in v0.5.0

func (r WordValidateResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WordValidateResponse) UnmarshalJSON added in v0.5.0

func (r *WordValidateResponse) UnmarshalJSON(data []byte) error

type WordsetGetParams

type WordsetGetParams struct {
	// Filter words by category (case-insensitive match). Only words with a matching
	// `category` field are returned.
	Category param.Opt[string] `query:"category,omitzero" json:"-"`
	// Maximum number of words to return. Applied after filtering and optional
	// shuffling.
	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
	// Filter words to only include those with at most this many characters.
	MaxLength param.Opt[int64] `query:"maxLength,omitzero" json:"-"`
	// Filter words to only include those with at least this many characters.
	MinLength param.Opt[int64] `query:"minLength,omitzero" json:"-"`
	// When set to `"true"`, shuffles the word list into a random order before applying
	// the limit.
	//
	// Any of "true", "false".
	Random WordsetGetParamsRandom `query:"random,omitzero" json:"-"`
	// When set to `"true"`, scrambles the letters of each word in the response
	// (Fisher-Yates shuffle on characters). Useful for building anagram puzzles.
	//
	// Any of "true", "false".
	Scramble WordsetGetParamsScramble `query:"scramble,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (WordsetGetParams) URLQuery

func (r WordsetGetParams) URLQuery() (v url.Values, err error)

URLQuery serializes WordsetGetParams's query parameters as `url.Values`.

type WordsetGetParamsRandom

type WordsetGetParamsRandom string

When set to `"true"`, shuffles the word list into a random order before applying the limit.

const (
	WordsetGetParamsRandomTrue  WordsetGetParamsRandom = "true"
	WordsetGetParamsRandomFalse WordsetGetParamsRandom = "false"
)

type WordsetGetParamsScramble

type WordsetGetParamsScramble string

When set to `"true"`, scrambles the letters of each word in the response (Fisher-Yates shuffle on characters). Useful for building anagram puzzles.

const (
	WordsetGetParamsScrambleTrue  WordsetGetParamsScramble = "true"
	WordsetGetParamsScrambleFalse WordsetGetParamsScramble = "false"
)

type WordsetResponse

type WordsetResponse struct {
	// ISO 8601 timestamp of when the wordset was created.
	CreatedAt time.Time `json:"createdAt,required" format:"date-time"`
	// A description of the wordset.
	Description string `json:"description,required"`
	// Whether the wordset is publicly accessible.
	IsPublic bool `json:"isPublic,required"`
	// The name of the wordset.
	Name string `json:"name,required"`
	// The total number of words in the wordset (before filtering).
	TotalWordCount int64 `json:"totalWordCount,required"`
	// The number of words in the `words` array (after filtering).
	WordCount int64 `json:"wordCount,required"`
	// The list of words in the wordset, after applying any query filters (minLength,
	// maxLength, category, random, limit, scramble).
	Words []WordsetWord `json:"words,required"`
	// The unique wordset identifier.
	WordsetID string `json:"wordsetId,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		CreatedAt      respjson.Field
		Description    respjson.Field
		IsPublic       respjson.Field
		Name           respjson.Field
		TotalWordCount respjson.Field
		WordCount      respjson.Field
		Words          respjson.Field
		WordsetID      respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A wordset with its words, optionally filtered and/or scrambled.

func (WordsetResponse) RawJSON

func (r WordsetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*WordsetResponse) UnmarshalJSON

func (r *WordsetResponse) UnmarshalJSON(data []byte) error

type WordsetService

type WordsetService struct {
	Options []option.RequestOption
}

WordsetService contains methods and other services that help with interacting with the anagrama API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWordsetService method instead.

func NewWordsetService

func NewWordsetService(opts ...option.RequestOption) (r WordsetService)

NewWordsetService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*WordsetService) Get

func (r *WordsetService) Get(ctx context.Context, wordsetID string, query WordsetGetParams, opts ...option.RequestOption) (res *WordsetResponse, err error)

Retrieves a user-created wordset by its ID. Public wordsets (`isPublic: true`) can be accessed without authentication. Private wordsets require the creator's API key passed as a Bearer token.

Words in the response can be filtered, shuffled, limited, and optionally scrambled using query parameters. Each request increments the wordset's hit counter for analytics.

type WordsetWord

type WordsetWord struct {
	// The word string. If `scramble=true` was requested, the letters are shuffled.
	Word string `json:"word,required"`
	// An optional category label for the word (e.g., "animals", "food").
	Category string `json:"category"`
	// An optional hint or clue for the word.
	Hint string `json:"hint"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Word        respjson.Field
		Category    respjson.Field
		Hint        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

A word entry in a wordset.

func (WordsetWord) RawJSON

func (r WordsetWord) RawJSON() string

Returns the unmodified JSON received from the API

func (*WordsetWord) UnmarshalJSON

func (r *WordsetWord) UnmarshalJSON(data []byte) error

Directories

Path Synopsis
encoding/json
Package json implements encoding and decoding of JSON as defined in RFC 7159.
Package json implements encoding and decoding of JSON as defined in RFC 7159.
encoding/json/shims
This package provides shims over Go 1.2{2,3} APIs which are missing from Go 1.22, and used by the Go 1.24 encoding/json package.
This package provides shims over Go 1.2{2,3} APIs which are missing from Go 1.22, and used by the Go 1.24 encoding/json package.
packages
shared

Jump to

Keyboard shortcuts

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