Installation
This guide covers installing Apiwork in a Rails application. After setup, the application has the directory structure for API definitions, contracts, and representations, and generators for scaffolding new resources.
Requirements
- Ruby 3.2 or higher
- Rails 8.0 or higher
Add to Gemfile
gem 'apiwork'Then run:
bundle installSetup
The install generator creates the directory structure and mounts Apiwork in the routes:
rails generate apiwork:installThis creates:
app/
├── contracts/
│ └── application_contract.rb
└── representations/
└── application_representation.rb
config/
└── apis/These sit alongside the existing app/controllers/ and app/models/. Contracts and representations inherit from these application-level base classes, just like controllers inherit from ApplicationController.
The generator also adds the following to config/routes.rb:
mount Apiwork => '/'The final URL combines the mount point with each API's path — mounting at / with an API defined at /api/v1 creates routes at /api/v1/posts.
Generators
Apiwork provides generators for common files.
apiwork:api
Creates an API definition in config/apis/:
rails generate apiwork:api api/v1This generates:
# config/apis/api_v1.rb
Apiwork::API.define '/api/v1' do
endThe base path /api/v1 determines both the mount point and the namespace. Apiwork expects:
- Controllers in
Api::V1::(e.g.Api::V1::PostsController) - Contracts in
Api::V1::(e.g.Api::V1::PostContract) - Representations in
Api::V1::(e.g.Api::V1::PostRepresentation)
TIP
For a root-level API with no base path prefix, use rails generate apiwork:api /. This creates config/apis/root.rb.
apiwork:contract
Creates a contract for a resource:
rails generate apiwork:contract api/v1/invoiceThis generates:
# app/contracts/api/v1/invoice_contract.rb
module Api
module V1
class InvoiceContract < ApplicationContract
end
end
endapiwork:representation
Creates a representation for a resource:
rails generate apiwork:representation api/v1/invoiceThis generates:
# app/representations/api/v1/invoice_representation.rb
module Api
module V1
class InvoiceRepresentation < ApplicationRepresentation
end
end
endINFO
Contracts and representations follow the same namespace structure as controllers. If the controller is Api::V1::InvoicesController, the contract is Api::V1::InvoiceContract and the representation is Api::V1::InvoiceRepresentation.