Tutorial
Step 0: Bootstrapping
Let’s start by creating a new Rails project. For help with an existing project, check out Installation: From Scratch.
We’ll use the -m
option to install from a template, which will add a few gems and apply some setup boilerplate. Accept all the default options.
$ rails new employee_directory --api -m https://www.graphiti.dev/template
$ cd employee_directory
Note: if a network issue prevents you from pointing to this URL directly, you can download the file and and run this command as
-m /path/to/template
Feel free to run git diff
to see what the generator did, otherwise commit the result. You can now head to Step 1: Basic Resource, or continue reading to better understand the code.
Digging Deeper 🧐
You’ll see some boilerplate in config/routes.rb
:
scope path: ApplicationResource.endpoint_namespace, defaults: { format: :jsonapi } do
# your routes go here
end
This tells Rails that our API routes will be be prefixed - /api/v1
by default. It also
says that if no extension is in the URL (.json
, .xml
, etc), default
to the JSONAPI Specification.
Let’s look at the above ApplicationResource
:
class ApplicationResource < Graphiti::Resource
self.abstract_class = true
# We'll be using ActiveRecord
self.adapter = Graphiti::Adapters::ActiveRecord
# Links are generated from base_url + endpoint_namespace
self.base_url = Rails.application.routes
.default_url_options[:host]
self.endpoint_namespace = '/api/v1'
end
This should be pretty self-explanatory except for
self.base_url = Rails.application.routes
.default_url_options[:host]
This is configured in config/application.rb
:
module EmployeeDirectory
class Application < Rails::Application
routes.default_url_options[:host] = ENV.fetch('HOST', 'http://localhost:3000')
# ... code ...
end
end
When deriving and validating Links, we’ll use the HOST
variable if
present, falling back to the Rails development default of
http://localhost:3000
. This means our Links will look like:
"#{ENV['HOST']}/#{ApplicationRecord.endpoint_namespace}/#{Resource.type}"
For example:
http://my-website.com/api/v1/employees
Read more in the Links Guide.
Finally, there’s some boilerplate in ApplicationController
:
class ApplicationController < ActionController::API
# Support JSON, XML, JSON:API
include Graphiti::Rails::Responders
end
This gets respond_with
working, via the Responders gem. To render simple nested JSON like default Rails, we’ll only need to add .json
to the URL.
That’s it for basic setup!