Skip to content

Rails JSON Protocol

Matt Muller edited this page Dec 10, 2021 · 4 revisions

Rails-JSON Protocol

Rails JSON is a protocol implementation for smithy-ruby-rails-codegen that (mostly) matches default Rails API behavior.

@railsJson trait

When the @railsJson trait is applied to a service shape, smithy-ruby-rails-codegen will generate an SDK that can communicate with Rails APIs over JSON. The full definition can be found here.

errorLocation property

By default, error codes are determined by inspecting the HTTP status code. For example, when the SDK encounters a 404 response, it will raise a NotFoundError. For APIs with multiple error codes that share an HTTP status code, the errorLocation property should be set to header. Generated SDKs will instead look for the error code in the x-smithy-rails-error header value.

@railsJson(errorLocation: 'header')
service MyService {}

@nestedAttributes trait

The @nestedAttributes trait is used to support Rails' accepts_nested_attributes_for. When applied to a member of an input structure, the code generator will append _attributes to the serialized JSON name. For example, if avatar is a nested model, the serialized JSON request will contain avatar_attributes.

Modeled errors

Some errors returned by a Rails API are intended to have extra data. For example, an UnprocessableEntityError may contain a parsed map of validation errors when the model fails to save. It is recommended that implementations use modeled errors. Some of these errors are defined alongside @railsJson for convenience and can be imported and used.

// Smithy requires "use" statement for every imported shape
use smithy.ruby.protocols#UnprocessableEntityError

...

operation CreateHighScore {
    ...
    errors: [UnprocessableEntityError] // declare modeled error
}

If this modeled error is not used, an UnprocessableEntityError is still raised as a generic ApiClientError, but it will not provide information to the Client why the operation failed.

Other behaviors

Time

The default time format is Date Time (eg: “2000-01-02T20:34:56.000Z”).

Serialization (Builder) Behavior

Member names are snake cased in the produced json (unless other traits define a name). For example, HighScore becomes high_score in serialized JSON.

Deserialization (Parser) Behavior

The parser assumes that member names are snake cased in the response JSON (unless other traits define a name). For example, HighScore becomes high_score in deserialized JSON.

Mapping of Rails action to Smithy Resource

The translation of a Rails controller action to Smithy Resource is roughly:

  • #indexlist
  • #showread
  • #createcreate
    • put in Smithy is an idempotent create - this does not work similarly in Rails by default.
  • #updateupdate
  • #destroydelete