🚂
Rails 7 API 모드 완전 정리
RailsAPI백엔드
Rails 7의 API 모드는 프론트엔드와 분리된 백엔드 API 서버를 구축할 때 최적화된 설정을 제공한다.
API 모드로 프로젝트 생성
rails new my_api --api --database=sqlite3이렇게 생성하면 뷰 관련 미들웨어와 gem이 제외되어 더 가벼운 애플리케이션이 만들어진다.
주요 차이점
| 항목 | 일반 모드 | API 모드 |
|---|---|---|
| ApplicationController 상속 | ActionController::Base | ActionController::API |
| 세션/쿠키 | 포함 | 제외 |
| CSRF 보호 | 포함 | 제외 |
| 뷰/레이아웃 | 포함 | 제외 |
| Asset Pipeline | 포함 | 제외 |
인증 구현
API 모드에서는 토큰 기반 인증을 사용한다.
class ApplicationController < ActionController::API
before_action :authenticate_request
private
def authenticate_request
token = request.headers["Authorization"]&.split(" ")&.last
@current_user = User.find_by_token(token)
render json: { error: "Unauthorized" }, status: :unauthorized unless @current_user
end
end주의 API 모드에서는 CSRF 토큰이 비활성화되므로, 반드시 Bearer 토큰 등 별도의 인증 메커니즘을 구현해야 한다.
JSON 직렬화
# app/controllers/api/v1/posts_controller.rb
class Api::V1::PostsController < ApplicationController
def index
posts = Post.includes(:author).page(params[:page])
render json: posts, each_serializer: PostSerializer
end
def show
post = Post.find(params[:id])
render json: post, serializer: PostDetailSerializer
end
endCORS 설정
# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "*"
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options]
end
end팁
프로덕션에서는 origins "*"를 실제 프론트엔드 도메인으로 제한해야 한다.
배포 체크리스트
- ✓ 환경변수 설정 (SECRET_KEY_BASE, DATABASE_URL)
- ✓ CORS origin 제한
- ✓ rate limiting 미들웨어 추가
- ✓ API 버저닝 (v1, v2)
- API 문서 자동 생성 (Swagger/OpenAPI)
결론 Rails API 모드는 풀스택 Rails의 장점을 유지하면서도 불필요한 오버헤드를 제거한 실용적인 선택이다. 특히 SQLite와 함께 사용하면 인프라 복잡도를 크게 줄일 수 있다.