DEV Community

Cover image for To --api or not to --api?
Greg Arnold
Greg Arnold

Posted on

To --api or not to --api?

Getting started on setting up a Rails project from scratch and stumble on rails new my_api --api and wonder what exactly the --api flag does? This post will investigate the differences and summarize the main uses for including or not including this tag when starting a Rails project.

Including --api flag will:

  • Configure your application to start with a more limited set of middleware than normal. It will not include any middleware primarily useful for browser applications (like cookies support) by default.
  • Make ApplicationController inherit from ActionController::API instead of ActionController::Base. As with middleware, this will leave out any Action Controller modules that provide functionalities primarily used by browser applications.
  • Configure the generators to skip generating views, helpers, and assets when you generate a new resource.

Including this tag is ideal for API only applications. by default it omits features that are usually required for browser access; layouts and templates rendering, flash, assets, and more. If any of that functionality ends up being needed later on in the project, it can be added back in. This is done by simply changing ApplicationController to inherit from ActionController::Base instead of ActionController::API and then you can add in the desired middlewares. Vice versa can be done if you start without the -api tag and determine to only need API functions. For more options that can be useful with crating a new Rails API, run: rails new --help

Sources:
Rails API Docs
Rails Guides
Rails::API Github

Top comments (0)