A JSON-API based API for AlchemyCMS
Add this line to your application's Gemfile:
gem 'alchemy-json_api'
And then execute:
$ bundle
Or install it yourself as:
$ gem install alchemy-json_api
Run this in your application:
npm install @alchemy_cms/json_api --save
or with the package manager of your choice
Mount the engine in your Alchemy Rails app like this:
# config/routes.rb
mount Alchemy::JsonApi::Engine => "/jsonapi/"
NOTE Pick any path you like. This will be the prefix of your API URLs
This repo provides an NPM package with deserializers to help you convert the response into JS objects.
import { deserializePages } from "@alchemy_cms/json_api"
const response = await fetch("/jsonapi/pages.json")
const data = await response.json()
const pages = deserializePages(data)
console.log(pages[0].name) // => Homepage
Alchemy::JsonApi allows for caching API responses. It respects the caching configuration of your Rails app and of your Alchemy configuration and settings in the pages page layout configuration. Restricted pages are never cached.
By default it sets the max-age
Cache-Control
header to 10 minutes (600
seconds). You can change this by configuring the Alchemy::JsonApi.page_cache_max_age
setting. It is recommended to set this via an environment variable like this:
# config/initializers/alchemy_json_api.rb
Alchemy::JsonApi.page_cache_max_age = ENV.fetch("ALCHEMY_JSON_API_CACHE_DURATION", 600).to_i
Alchemy sets the must-revalidate
directive if caching is enabled. If your CDN supports it, you can change that to use the much more efficient stale-while-revalidate
directive by changing the Alchemy::JsonApi.page_caching_options
setting to any integer value.
# config/initializers/alchemy_json_api.rb
Alchemy::JsonApi.page_caching_options = {
stale_while_revalidate: ENV.fetch("ALCHEMY_JSON_API_CACHE_STALE_WHILE_REVALIDATE", 60).to_i
}
Tip
You can set any caching option that ActionController::ConditionalGet#expires_in
supports, like stale_if_error
, public
or immutable
.
If you ever want to change how Alchemy serializes attributes you can set
# config/initializers/alchemy_json_api.rb
Alchemy::JsonApi.key_transform = :camel_lower
It defaults to :underscore
.
Contribution directions go here.
The gem is available as open source under the terms of the BSD-3-Clause license.