Skip to content
Alex Woods edited this page Apr 11, 2024 · 12 revisions

The Client class is the public interface used for interacting with the service. The Client has methods for each operation defined by the API. Clients have a 1:1 mapping with a Smithy service shape and its public methods have a 1:1 mapping with Smithy operation shapes.

@railsJson
@title("High Score Sample Rails Service")
service HighScoreService {
    version: "2021-02-15",
    resources: [HighScore]
}

resource HighScore {
    identifiers: { id: String },
    read: GetHighScore,
    create: CreateHighScore,
    update: UpdateHighScore,
    delete: DeleteHighScore,
    list: ListHighScores
}

Initialization

The initialize method takes a hash of config options and creates a new Client instance. Config options are validated using the Config class.

client = HighScoreService::Client.new(endpoint: 'http://127.0.0.1:3000')
# => #<HighScoreService::Client ... >

client.config
# => #<struct HighScoreService::Config ... >

client = HighScoreService::Client.new(unknown: 'foo')
# raises ArgumentError, unknown keywords: unknown

Operation Methods

Each Smithy operation shape maps to one operation method in the Client. These operation methods are implemented using a static Middleware stack. The middleware stack handles building the request and returning the response data or an error.

Operation methods take two positional hash parameters, one for API parameters (params) and the other for operation config overrides (options). Params may also be passed as the operation's input type (e.g. an instance of Types::Input) allowing users to build input using structured classes instead.

client.create_high_score(high_score: { game: 'Frogger', score: 9001 })
# => #<Hearth::Output @data=... >

# Optional, preference
create_high_score_input = HighScoreService::Types::CreateHighScoreInput.new(
  high_score: HighScoreService::Types::HighScoreParams.new(
    game: 'Frogger',
    score: 9001
  )
)
client.create_high_score(create_high_score_input)
# => #<Hearth::Output @data=... >

# Overriding client options
client.create_high_score(
  { high_score: { game: 'Frogger', score: 9001 } },
  { endpoint: 'http://127.0.0.1:8080' }
)
# <uses new endpoint>
# => #<Hearth::Output @data=... >

Streaming operations can take a block or an IO passed to the :output_stream option for which the Hearth::Response object will be written to.

# BlockIO stream option
client.streaming_operation(param: 'param') do |chunk|
 # chunk is a string from the response.
end

# Output stream option
file = File.new('my-file')
client.streaming_operation(
  { param: 'param' },
  { output_stream: file }
)
file.rewind
file.read
# => 'output'