API Development Patterns
БесплатноБез исполняемых скриптовНе проверенComprehensive guide to building production-ready REST APIs in Rails with serialization, authentication, versioning, rate limiting, and testing. Trigger…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
API Development Patterns
Complete patterns and best practices for building production-grade REST APIs in Rails 7.x/8.x.
RESTful API Conventions
Resource-Oriented Design
Core Principles:
- Resources are nouns (not verbs):
/users,/posts, not/get_user - Use HTTP methods for actions: GET (read), POST (create), PATCH/PUT (update), DELETE (destroy)
- Nest resources for relationships, but limit nesting to 1-2 levels
- Use plural resource names:
/usersnot/user
Standard Resource Routes:
# config/routes.rb
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :posts do
resources :comments, only: [:index, :create] # Nested but limited
member do
post :publish
post :archive
end
collection do
get :trending
end
end
# Flat route for comments by ID (better than deep nesting)
resources :comments, only: [:show, :update, :destroy]
end
end
end
HTTP Methods & Status Codes
Standard API Actions:
| Method | Action | Success Status | Body |
|---|---|---|---|
| GET | Index/List | 200 OK | Resource array + pagination |
| GET | Show | 200 OK | Single resource |
| POST | Create | 201 Created | Created resource |
| PATCH/PUT | Update | 200 OK | Updated resource |
| DELETE | Destroy | 204 No Content | Empty |
Error Status Codes:
| Code | Meaning | When to Use |
|---|---|---|
| 400 | Bad Request | Invalid JSON, malformed request |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Authenticated but not authorized |
| 404 | Not Found | Resource doesn't exist |
| 422 | Unprocessable Entity | Validation errors |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server error |
| 503 | Service Unavailable | Maintenance mode, overloaded |
Controller Example:
# app/controllers/api/v1/posts_controller.rb
module Api
module V1
class PostsController < Api::BaseController
before_action :authenticate_api_user!
before_action :set_post, only: [:show, :update, :destroy]
def index
@posts = Post.published
.page(params[:page])
.per(params[:per_page] || 25)
render json: PostBlueprint.render(@posts, root: :posts), status: :ok
end
def show
render json: PostBlueprint.render(@post), status: :ok
end
def create
@post = Current.user.posts.build(post_params)
if @post.save
render json: PostBlueprint.render(@post), status: :created, location: api_v1_post_url(@post)
else
render json: { errors: @post.errors }, status: :unprocessable_entity
end
end
def update
if @post.update(post_params)
render json: PostBlueprint.render(@post), status: :ok
else
render json: { errors: @post.errors }, status: :unprocessable_entity
end
end
def destroy
@post.destroy
head :no_content
end
private
def set_post
@post = Post.find(params[:id])
rescue ActiveRecord::RecordNotFound
render json: { error: "Post not found" }, status: :not_found
end
def post_params
params.require(:post).permit(:title, :body, :published_at, tag_ids: [])
end
end
end
end
Serialization Patterns
Blueprinter (Recommended)
Installation:
# Gemfile
gem 'blueprinter'
gem 'oj' # Fast JSON parser
Basic Blueprint:
# app/blueprints/post_blueprint.rb
class PostBlueprint < Blueprinter::Base
identifier :id
fields :title, :body, :published_at, :created_at
field :slug do |post|
post.title.parameterize
end
association :author, blueprint: UserBlueprint, view: :compact
association :comments, blueprint: CommentBlueprint do |post, options|
post.comments.limit(options[:comment_limit] || 10)
end
view :compact do
fields :id, :title, :slug
end
view :extended do
include_view :default
fields :view_count, :like_count
association :tags, blueprint: TagBlueprint
end
end
Using Views:
# Compact view for lists
PostBlueprint.render(@posts, view: :compact, root: :posts)
# Extended view for show
PostBlueprint.render(@post, view: :extended)
# Pass options to associations
PostBlueprint.render(@post, comment_limit: 5)
JSONAPI::Serializer (Alternative)
For JSON:API Specification Compliance:
# Gemfile
gem 'jsonapi-serializer'
# app/serializers/post_serializer.rb
class PostSerializer
include JSONAPI::Serializer
attributes :title, :body, :published_at
belongs_to :author, serializer: UserSerializer
has_many :comments, serializer: CommentSerializer
attribute :slug do |post|
post.title.parameterize
end
link :self do |post|
Rails.application.routes.url_hel
Установить API Development Patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл API Development Patterns?
Comprehensive guide to building production-ready REST APIs in Rails with serialization, authentication, versioning, rate limiting, and testing. Trigger keywords: REST API, JSON, serialization, versioning, authentication, JWT, rate limiting, API controllers, request specs, API testing, endpoints, responses
Как установить скилл API Development Patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл API Development Patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic