# Rails API Development: REST, Authentication, Versioning and Tests That Hold Up

> Rails API development that holds up: REST design, JWT/OAuth2, serializers, versioning, rate limiting, background jobs and the tests that catch real breakage.

- URL: https://railsdev.io/blog/rails-api-development
- Published: 2026-11-11
- Author: Hendra Nicholas (Rails Full-Stack Developer & AI Engineer)

---

Rails API development is building a JSON backend that other applications — your mobile app, a partner integration, your own React frontend — can depend on without you being in the room for every question. Rails does this well (see the [Rails API-only applications guide](https://guides.rubyonrails.org/api_app.html)) because the boring parts (authentication, serializers, pagination, background jobs) are solved and the conventions are real.

This is how I build production APIs, including the parts that age badly when skipped.

## Decide the shape before the endpoints

Three viable shapes in a Rails API:

- **Plain JSON endpoints** (`render json:`): simplest, fine for small surfaces.
- **Serialized responses** with `ActiveModel::Serializers` or `blueprinter`/`alba`: stable contracts, explicit field whitelists — my default for public APIs.
- **JSON:API or OpenAPI-documented**: when partners integrate, write the OpenAPI spec; it doubles as the contract for generated clients and request tests.

Keep URLs noun-based and status codes honest (`201` for created, `204` for no-content, `422` for validation). Error bodies stay consistent everywhere:

```json
{ "error": { "code": "validation_failed", "message": "...", "fields": { "email": ["can't be blank"] } } }
```

## Authentication: JWT, OAuth2 or sessions

- **First-party SPA/mobile against your own Rails app**: same-origin session cookies (Devise/Rodauth + CSRF) beat tokens — simpler, safer, revocable.
- **Third-party or multi-tenant APIs**: OAuth2. Issue tokens via `doorkeeper`, keep scopes coarse (`read:orders`, `write:orders`), and expire access tokens quickly with refresh tokens.
- **Service-to-service**: short-lived JWTs signed with a rotating key, or plain HMAC-signed requests if you control both sides.
- **User-facing bearer flows**: `jwt` gem or Devise+JWT; validate audience and issuer, and always check revocation for high-risk scopes.

```ruby
# app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < ActionController::API
  before_action :authenticate_token!

  private

  def authenticate_token!
    token = request.headers["Authorization"]&.delete_prefix("Bearer ")
    @current_client = OauthAccessToken.active.find_by(token: token)
    render json: { error: { code: "unauthorized" } }, status: :unauthorized unless @current_client
  end
end
```

## Versioning without pain

`Api::V1::OrdersController`, mounted at `/api/v1/...`. Rules that keep versioning sane:

- **Never remove a field** in a version — add fields, or ship `v2`.
- **Deprecate with headers and dates** (`Deprecation: 2026-12-31`), log usage, and email integrators before sunset.
- **Share behavior in concerns/services** so v1 and v2 differ only in the contract, not the logic.

## The production checklist that matters

- [ ] **Rate limiting** (`rack-attack`): per-token and per-IP buckets, with `429` and `Retry-After`.
- [ ] **Idempotency keys** on mutating endpoints that charge or provision.
- [ ] **Background jobs** for anything slow (Solid Queue handles this in Rails 8) — return `202 Accepted` and a status URL instead of holding connections.
- [ ] **Strong params and schema-validated input**; reject unknown fields rather than coercing them.
- [ ] **N+1 hygiene**: `bullet` in test, query objects or scopes for API list endpoints.
- [ ] **Observability**: request id in logs, error tracking, latency histogram per endpoint.
- [ ] **Pagination everywhere**: cursor-based for feeds, page/limit for admin; never an unbounded `includes`.
- [ ] **Audit log** for writes: who, what, when — before you need it.

## Testing that catches real breakage

```ruby
# spec/requests/api/v1/orders_spec.rb
RSpec.describe "POST /api/v1/orders", type: :request do
  it "creates an order with a valid token" do
    post api_v1_orders_path, params: { order: { sku: "A-1", qty: 2 } }.to_json,
         headers: auth_headers, as: :json
    expect(response).to have_http_status(:created)
    expect(response.parsed_body["order"]["sku"]).to eq("A-1")
  end

  it "returns 422 with field errors" do
    post api_v1_orders_path, params: { order: { qty: -1 } }.to_json,
         headers: auth_headers, as: :json
    expect(response).to have_http_status(:unprocessable_entity)
    expect(response.parsed_body.dig("error", "fields", "qty")).to be_present
  end
end
```

Add contract tests against your OpenAPI spec if you publish one — they're the cheapest way to stop drift between docs and behavior.

## Deploying it

Same shape as every Rails app: Docker + Kamal, a managed Postgres, and one rule — the API deploys independently of any frontend, with the frontend told which API version to talk to. My [Kamal guide](/blog/kamal-rails) covers the deploy mechanics.

## Where this shows up for you

I build APIs like this routinely — public partner APIs, mobile backends, internal service APIs — inside my [Ruby on Rails development service](/services/ruby-on-rails-development). If you're deciding between an API-first SPA and Hotwire, my [Hotwire vs React](/blog/hotwire-vs-react) comparison is the place to start. And if you want the endpoints scoped, versioned and tested rather than improvised, [send me a short brief](/#contact).

## Conclusion

An API is a contract that outlives teams: namespaced versions, honest errors, rate limits, jobs for slow work and tests that enforce the contract. If yours is still improvised, [send me a short brief and book a discovery call](/#contact).

## Frequently asked questions

### Should a Rails API use JWT or sessions?

Sessions for first-party web apps; tokens (OAuth2 or JWT) for mobile, partners and multi-tenant access. Mixing both on one surface is where auth bugs come from.

### How do I handle API versioning in Rails?

Namespaced controllers (`/api/v1`), no field removals within a version, deprecation headers with real dates, and shared service objects so versions don't fork logic.

### Is Rails fast enough for an API?

Yes, with N+1s eliminated and slow work pushed to jobs. Rails API performance is dominated by database time; fit indexes first.

### How do I prevent abuse?

`rack-attack` at the edge (Cloudflare + app), per-token quotas, idempotency keys, and queues that shed load instead of growing without bound.

### Do I need OpenAPI?

If external teams integrate, yes — their tooling (and your request tests) both benefit. For internal-only APIs, documented serializers and a README are enough.

### What does an API engagement look like?

Usually two to six weeks: auth, resources, serializers, tests, deploy, and handover docs. Larger surfaces split by domain into phases.
