Rails APIs
Why Use Rails for JSON APIs?
The first question a lot of people have when thinking about building a JSON API using Rails is: “isn’t using Rails to spit out some JSON overkill? Shouldn’t I just use something like Sinatra?”. [Or Express.js?]
For very simple APIs, this may be true. However, even in very HTML-heavy applications, most of an application’s logic lives outside of the view layer.
The reason most people use Rails is that it provides a set of defaults that allows developers to get up and running quickly, without having to make a lot of trivial decisions.
Tools
- apiup - Rails project template to create an API pre-configured for JSON:API and OAuth 2 authentication
Sample APIs
- How to JSON:API Sandbox—a JSON:API compliant web service with OAuth2 authentication. Try the app hosted or download it locally.
Resources
- Rails: The Easiest Way to Create a Web Service—two-part blog series
- Building a JSON:API Backend with Rails and JSONAPI::Resources
- Books
- Build APIs You Won’t Hate—guidelines on API design practices
- Programming Ruby, aka “The Pickaxe Book”—a popular introduction to the Ruby language
- Effective Testing with RSpec 3—features and practices for testing with RSpec
- Practical Object-Oriented Design — a guide to writing changeable and maintainable code, written in Ruby
- Blog posts
- Talks
- In Relentless Pursuit of REST - RailsConf 2017 talk by Derek Prior showing how the constaints of REST help lead to simpler code and a better domain model
Rails Guides
The following pages in the Guides are relevant to API development:
- Active Record—all the sections are useful; the first is Active Record Basics
- Action Controller —especially check out the “Rendering XML and JSON Data” section
- Routing—especially check out the “Resource Routing” section
- Securing Rails Applications
- Command Line
- API-Only Applications—how to disable Rails server-rendered mode to simplify your API app
- Supplemental APIs
- Action Mailer—sending email
- Active Job—background workers
- Active Storage—file uploads
Gems
- rspec-rails—a popular Rails testing library. For APIs, especially check out request specs
- Active Model Serializers—centralizes your logic to serialize models to JSON
- Doorkeeper—authenticate users with the OAuth2 standard
- Pundit—authorize users’ access to read and write records
- JSONAPI::Resources—helps creating an API following the JSON:API spec. Maintained by the creators of JSON:API.
- jsonapi-rails—alternate JSON:API gem
- GraphQL—gem for creating GraphQL APIs
Deployment
- Heroku—”platform as a service” with great Rails support
- Docker—deploy apps in containers to isolate them
- Capistrano—automate deploying Rails to servers
- Digital Ocean—easy cloud server platform