Routing
Define API routes with resources, nested resources, and custom actions
Routing
API definitions describe where your endpoints live. They map contracts to HTTP routes.
Defining an API
Zodra.api "/api/v1" do
resources :products
resources :customers
resources :orders, only: %i[index show create]
resource :settings, only: %i[show update]
endLoading routes
Add the zodra_routes helper to your routes file:
Rails.application.routes.draw do
zodra_routes
endThis loads all API definitions from config/apis/*.rb and registers the routes.
Resources
resources creates standard RESTful routes for a collection:
resources :productsGenerates:
| HTTP Method | Path | Action |
|---|---|---|
| GET | /api/v1/products | index |
| GET | /api/v1/products/:id | show |
| POST | /api/v1/products | create |
| PATCH | /api/v1/products/:id | update |
| DELETE | /api/v1/products/:id | destroy |
Limiting actions
resources :orders, only: %i[index show create]
resources :logs, except: %i[update destroy]Options
contract:— contract name (defaults to resource name)controller:— controller nameonly:— whitelist of actionsexcept:— blacklist of actions
resources :invoices, contract: :billing, controller: :billing_invoicesSingular resource
resource creates routes for a singleton (no index, no :id in paths):
resource :settings, only: %i[show update]| HTTP Method | Path | Action |
|---|---|---|
| GET | /api/v1/settings | show |
| PATCH | /api/v1/settings | update |
Custom actions
Member actions
Actions on a specific resource (require :id):
resources :orders do
member do
patch :confirm # PATCH /api/v1/orders/:id/confirm
patch :cancel # PATCH /api/v1/orders/:id/cancel
get :preview # GET /api/v1/orders/:id/preview
end
endAvailable HTTP methods: get, post, patch, put, delete.
Collection actions
Actions on the collection (no :id):
resources :orders do
collection do
get :search # GET /api/v1/orders/search
post :export # POST /api/v1/orders/export
end
endNested resources
resources :orders do
resources :items # /api/v1/orders/:order_id/items
resource :metadata, only: %i[show] # /api/v1/orders/:order_id/metadata
endFull example
Zodra.api "/api/v1" do
resources :products
resources :customers
resources :orders, only: %i[index show create] do
member do
patch :confirm
patch :cancel
end
collection do
get :search
end
end
resource :settings, only: %i[show update]
end