Declaration
Attributes are declared with type information that Apiwork auto-detects from the database.
Basic Declaration
ruby
class InvoiceRepresentation < Apiwork::Representation::Base
attribute :number
attribute :status
attribute :issued_on
attribute :total
endAuto-Detection
Apiwork automatically detects from the database and model:
| Property | Source |
|---|---|
type | Column type (string, integer, boolean, datetime, etc.) |
nullable | Column NULL constraint |
optional | Column allows NULL or has default value |
enum | Rails enum definition |
ruby
# These are equivalent:
attribute :title
attribute :title, type: :string, nullable: false
# Enum auto-detection
attribute :status # Detects Rails enum values automaticallyTypes, nullability, and enums are detected from the database and models.
Options Reference
| Option | Type | Default | Description |
|---|---|---|---|
type | symbol | auto | Data type |
nullable | bool | auto | Allow null values |
optional | bool | auto | Optional in requests |
writable | bool / symbol | false | Allow in create/update requests (details) |
filterable | bool | false | Mark as filterable (adapter-dependent) |
sortable | bool | false | Mark as sortable (adapter-dependent) |
preload | symbol / array / hash | nil | Associations to eager load (details) |
encode | callable | nil | Transform on response (details) |
decode | callable | nil | Transform on request (details) |
enum | array | auto | Enum values (details) |
empty | bool | false | Convert nil to empty string (details) |
format | symbol | nil | Format hint (details) |
min / max | integer | nil | Value/length constraints |
description | string | nil | API documentation (details) |
example | any | nil | Example value (details) |
deprecated | bool | false | Mark as deprecated (details) |
filterable and sortable are declarations — the adapter interprets them at runtime. See the adapter documentation for query syntax and supported operators.
TIP
The Standard Adapter supports filtering and sorting on marked attributes.
Batch Configuration
with_options applies options to multiple attributes:
ruby
class ScheduleRepresentation < Apiwork::Representation::Base
with_options filterable: true, sortable: true do
attribute :id
attribute :status
attribute :created_at
attribute :updated_at
with_options writable: true do
attribute :name
attribute :starts_on
attribute :ends_on
end
end
attribute :archived_at
endNested blocks inherit and merge options. In the example above:
id,status,created_at,updated_atare filterable + sortablename,starts_on,ends_onare filterable + sortable + writablearchived_athas no options
TIP
with_options is provided by ActiveSupport and works with any method that accepts keyword arguments.