Sometimes we need to create only an API, an application without a user interface, for example if you’ll have someone else built later a mobile client for that API, or even a full SPA web client, there are many reasons to build an API only app.
And since there are that many reasons, rails helps with that also, it has an option you can pass when creating a new application “–api” that will create an streamlined app to favor this kind of development.
Talking like that, it seems like a really big thing, but there aren’t that much differences.
But basically, the differences are:
- There wont be an app/assets directory, and no asset pipeline preconfigured.
- The rails frameworks will be expanded in the config/application.rb allowing you to comment anything you’ll not use
- There are less gems in Gemfile (mostly the JavascriptGems are removed)
- The ApplicationController descends from ActionController::API instead of ActionController::Base
The main difference in the controller is that it does not include by default some features like
- Layout
- Template rendering
- cookies
- sessions
Of course this will make the controller stack a lot slimmer, and faster, suitable for an API only App.
So, lets start with the command:
rails new myapissample --api
Then you can edit “config/application.rb” and maybe comment some features that you’ll not use, for example “ActionCable”
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" #require "action_view/railtie" #require "action_cable/engine" # require "sprockets/railtie" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Myapissample class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Only loads a smaller set of middleware suitable for API only apps. # Middleware like session, flash, cookies can be added back manually. # Skip views, helpers and assets when generating a new resource. config.api_only = true end end
After that you can just write your controllers as usual, access your models, …