CrackedRuby CrackedRuby

Overview

API documentation describes the contracts, interfaces, methods, parameters, and behaviors that software components expose to external consumers. This documentation serves as the primary communication mechanism between API providers and developers who integrate with those APIs. The documentation specifies endpoints, request formats, response structures, authentication mechanisms, error handling, and usage examples.

API documentation exists in multiple forms depending on the interface type. REST APIs require documentation of HTTP endpoints, methods, headers, and JSON/XML payloads. Library APIs need documentation of classes, methods, parameters, return types, and exceptions. GraphQL APIs document schemas, queries, mutations, and type systems. Each form addresses different integration patterns but shares common goals of completeness, accuracy, and usability.

The quality of API documentation directly impacts adoption rates and integration success. Developers evaluate APIs based on documentation clarity before committing to integration work. Poor documentation increases support burden, generates incorrect implementations, and reduces API usage. Well-documented APIs reduce time-to-integration, minimize support requests, and enable self-service adoption.

Ruby API documentation spans gem libraries documented with YARD or RDoc, web service APIs built with Rails or Sinatra, and GraphQL schemas. Ruby's dynamic nature creates documentation challenges since type information exists at runtime rather than compile time. Tools compensate by parsing code comments, analyzing method signatures, and generating documentation from specification files.

# YARD documentation example
# @param user_id [Integer] the user identifier
# @param options [Hash] optional parameters
# @option options [Boolean] :include_deleted include deleted records
# @return [User, nil] the user object or nil if not found
# @raise [ArgumentError] if user_id is not an integer
def find_user(user_id, options = {})
  raise ArgumentError unless user_id.is_a?(Integer)
  User.find(user_id, options)
end

Key Principles

API documentation communicates contracts between providers and consumers. The contract specifies what requests the API accepts, what responses it returns, what errors it raises, and what side effects it produces. Documentation accuracy determines whether consumers can successfully integrate without trial-and-error experimentation or support intervention.

Completeness requires documenting every endpoint, method, parameter, response field, error code, and edge case. Incomplete documentation forces developers to reverse-engineer behavior through testing or source code inspection. Each documented element needs description, type information, constraints, default values, and examples. Optional parameters require clear indication of optionality and default behavior.

Accuracy means documentation matches actual implementation behavior. Divergence between documentation and implementation occurs through code changes without documentation updates, copy-paste errors, or assumptions about behavior. Automated tests that validate documentation against implementation detect accuracy drift. API specification formats like OpenAPI enable contract testing where documentation serves as executable specification.

Clarity determines how quickly developers understand API usage. Technical jargon, ambiguous descriptions, and complex sentence structures reduce clarity. Documentation uses consistent terminology, concrete examples, and progressive disclosure. Core concepts appear early with simple examples. Advanced scenarios, edge cases, and optimization techniques appear in dedicated sections.

Maintainability impacts long-term documentation quality. Documentation maintained separately from code diverges as code evolves. Generated documentation from code comments keeps documentation and implementation synchronized. Documentation-driven development writes documentation before implementation, using documentation as specification. Versioned documentation tracks API changes across releases.

Type Information specifies data types for parameters, responses, and fields. Statically-typed languages extract types from signatures. Ruby's dynamic typing requires explicit type documentation through comments or specification files. Type information includes primitive types (String, Integer, Boolean), complex types (Array, Hash), custom classes, and null handling.

# Type documentation with YARD tags
# @param filters [Hash<Symbol, Object>] filtering criteria
# @option filters [String] :name name pattern (supports wildcards)
# @option filters [Range<Date>] :created_at date range
# @option filters [Array<Symbol>] :status allowed status values
# @return [Array<Record>] matching records
def search(filters)
  # Implementation
end

Authentication and Authorization documentation describes how clients prove identity and what permissions they need. Authentication methods include API keys, OAuth tokens, JWT, basic auth, and session cookies. Documentation specifies where credentials appear (headers, query parameters, body), required scopes or permissions, token lifetime, and refresh procedures.

Error Handling documentation catalogs error conditions, error codes, error response formats, and recovery strategies. HTTP APIs document status codes (400, 401, 404, 500) and error payload structures. Library APIs document exception types and when they occur. Error documentation includes causes, messages, and corrective actions.

Rate Limiting documentation specifies request quotas, time windows, limit headers, and throttling behavior. APIs document requests per second, daily quotas, concurrent connection limits, and rate limit responses. Rate limit documentation enables clients to implement retry logic and respect API capacity.

Implementation Approaches

Manual Documentation involves writing documentation in markdown, HTML, or documentation platforms without code generation. Developers write and update documentation separately from code. This approach offers maximum flexibility in organization, narrative, and examples. Manual documentation suits APIs where code structure differs from ideal documentation structure or where extensive prose guides are needed.

Manual documentation requires discipline to maintain accuracy as code evolves. Documentation reviews during code review catch divergence. Dedicated documentation releases coordinate with API version releases. Manual documentation works well for conceptual guides, tutorials, and architecture overviews where code generation cannot produce appropriate content.

## User Authentication

### POST /api/auth/login

Authenticates a user and returns an access token.

**Request Body:**
- email (string, required): User email address
- password (string, required): User password
- remember_me (boolean, optional): Extend token lifetime

**Response (200 OK):**

Generated Documentation produces documentation from code structure, comments, and annotations. Tools parse source code to extract classes, methods, parameters, and return types. Inline comments provide descriptions. Generated documentation maintains synchronization between code and documentation since both share single source.

Ruby's YARD and RDoc generate documentation from specially formatted comments. YARD supports rich tags for parameters, return values, exceptions, examples, and deprecations. Generated documentation creates HTML websites, markdown files, or JSON metadata. Documentation generation integrates into build pipelines for automated updates.

class UserController
  # Authenticates user credentials and creates session
  #
  # @param email [String] user email address
  # @param password [String] user password
  # @param remember_me [Boolean] whether to extend session lifetime
  # @return [Hash] session token and user information
  # @raise [AuthenticationError] when credentials are invalid
  # @example Basic authentication
  #   authenticate('user@example.com', 'password123', false)
  #   # => { token: 'abc123', user: { id: 1, email: '...' } }
  def authenticate(email, password, remember_me = false)
    # Implementation
  end
end

Specification-Driven Documentation uses formal API specification formats like OpenAPI, API Blueprint, or RAML as documentation source. The specification describes endpoints, request/response schemas, and examples in structured format. Documentation tools render specifications as interactive HTML documentation. Code generation tools create server stubs or client libraries from specifications.

OpenAPI (formerly Swagger) specifications use YAML or JSON to describe REST APIs. The specification defines paths, operations, parameters, request bodies, responses, and schemas. OpenAPI specifications enable automated validation, mock servers, and code generation. Specification-first development writes OpenAPI specs before implementation.

paths:
  /api/users/{id}:
    get:
      summary: Get user by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: User found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          description: User not found

Hybrid Approaches combine generated and manual documentation. Core API reference generates from code or specifications. Conceptual guides, tutorials, and getting-started content are written manually. The hybrid approach automates reference accuracy while providing narrative context.

Rails API documentation commonly uses this approach. Controllers document endpoints with YARD or OpenAPI. Separate guides explain authentication flows, pagination, error handling, and integration patterns. The reference documentation stays synchronized through generation while guides provide context that code cannot express.

Tools & Ecosystem

YARD (Yet Another Ruby Documentation) generates documentation from Ruby code and comments. YARD supports rich tag syntax for parameters, return types, exceptions, examples, visibility, and deprecations. YARD generates HTML documentation sites, markdown files, and JSON metadata. YARD integrates with RubyGems to display documentation on documentation hosting platforms.

YARD tags use @tag_name syntax with parameters and descriptions. Tags document method signatures, class hierarchies, module inclusion, and code examples. YARD supports custom tags for application-specific documentation needs. YARD plugins extend functionality for frameworks like Rails, Grape, and RSpec.

# Finds records matching search criteria
#
# This method performs full-text search across multiple fields
# and returns paginated results. Search supports wildcards (*),
# phrase matching ("exact phrase"), and field-specific queries.
#
# @param query [String] search query string
# @param page [Integer] page number (1-indexed)
# @param per_page [Integer] records per page (max 100)
# @return [SearchResult] paginated search results
# @raise [InvalidQueryError] when query syntax is invalid
# @see SearchResult for result structure
# @example Basic search
#   search("ruby programming", 1, 20)
#   # => #<SearchResult total=45 results=[...]>
# @example Field-specific search
#   search("title:API author:Smith", 1, 20)
def search(query, page = 1, per_page = 20)
  # Implementation
end

RDoc is Ruby's original documentation tool, included in Ruby standard library. RDoc parses Ruby source files and generates HTML documentation. RDoc uses simpler markup than YARD with fewer tags. RDoc documentation appears on ruby-doc.org for standard library classes. Many Ruby projects have migrated to YARD for richer documentation features.

Grape-Swagger generates OpenAPI documentation from Grape API definitions. Grape is a Ruby framework for REST APIs. Grape-Swagger extracts endpoint definitions, parameters, and responses from Grape DSL. The tool produces OpenAPI specifications that render with Swagger UI or ReDoc.

module API
  class UsersAPI < Grape::API
    desc 'Returns user by ID',
      success: User::Entity,
      failure: [[404, 'User not found']],
      params: User::Entity.documentation
    params do
      requires :id, type: Integer, desc: 'User ID'
    end
    get ':id' do
      user = User.find(params[:id])
      present user, with: User::Entity
    end
  end
end

Rswag integrates RSpec tests with OpenAPI documentation for Rails applications. Rswag generates OpenAPI specifications from RSpec request specs. Test examples become documentation examples. This approach ensures documentation accuracy through executable tests. Rswag renders documentation with Swagger UI.

require 'swagger_helper'

RSpec.describe 'Users API', type: :request do
  path '/api/users/{id}' do
    parameter name: :id, in: :path, type: :integer

    get 'Retrieves a user' do
      tags 'Users'
      produces 'application/json'
      parameter name: :id, in: :path, type: :integer

      response '200', 'user found' do
        schema type: :object,
          properties: {
            id: { type: :integer },
            email: { type: :string },
            name: { type: :string }
          }

        let(:id) { User.create(email: 'test@example.com').id }
        run_test!
      end

      response '404', 'user not found' do
        let(:id) { 'invalid' }
        run_test!
      end
    end
  end
end

OpenAPI/Swagger specifications describe REST APIs in YAML or JSON format. OpenAPI 3.0 is the current standard version. Specifications define servers, paths, operations, parameters, request bodies, responses, schemas, security requirements, and examples. Swagger UI and ReDoc render OpenAPI specifications as interactive documentation with try-it-out functionality.

Postman is an API development platform with documentation features. Postman collections organize requests into folders with descriptions. Collections export to OpenAPI format. Postman generates public documentation websites from collections. Postman documentation includes request examples, response examples, and variable descriptions.

Slate creates static documentation sites from markdown with code examples in multiple languages. Slate uses three-column layout: content, code examples, and navigation. Slate suits REST API documentation with consistent structure. Slate markdown includes special syntax for parameter tables and multi-language code blocks.

GraphQL APIs self-document through introspection. GraphQL schemas define types, fields, queries, mutations, and descriptions. GraphQL Playground and GraphiQL provide interactive documentation browsers. Schema documentation describes each type, field arguments, return types, and deprecation status.

# GraphQL type documentation
module Types
  class UserType < Types::BaseObject
    description "A user account in the system"

    field :id, ID, null: false,
      description: "Unique user identifier"
    
    field :email, String, null: false,
      description: "User email address (unique)"
    
    field :posts, [Types::PostType], null: false,
      description: "Posts authored by this user"
    
    field :created_at, GraphQL::Types::ISO8601DateTime, null: false,
      description: "Account creation timestamp"
  end
end

Practical Examples

REST API Endpoint Documentation describes HTTP endpoints with methods, paths, parameters, request bodies, and responses. Comprehensive endpoint documentation includes authentication requirements, rate limits, pagination, and error scenarios.

# Rails controller with YARD documentation
class API::V1::PostsController < ApplicationController
  # Lists all posts with optional filtering
  #
  # Returns paginated posts with optional filters for status,
  # author, and date range. Results are sorted by creation date
  # in descending order by default.
  #
  # Authentication: Required (API key in Authorization header)
  # Rate limit: 100 requests per minute
  #
  # @param status [String] filter by status (draft, published, archived)
  # @param author_id [Integer] filter by author ID
  # @param since [ISO8601 String] include posts created after this date
  # @param page [Integer] page number (default: 1)
  # @param per_page [Integer] items per page (default: 20, max: 100)
  #
  # @return [Hash] paginated posts with metadata
  # @return [Array<Post>] :data array of post objects
  # @return [Hash] :meta pagination metadata
  # @return [Integer] :meta.total_count total matching posts
  # @return [Integer] :meta.page current page number
  # @return [Integer] :meta.per_page items per page
  #
  # @raise [AuthenticationError] when API key is missing or invalid
  # @raise [RateLimitError] when rate limit exceeded
  # @raise [ValidationError] when parameters are invalid
  #
  # @example Fetch published posts
  #   GET /api/v1/posts?status=published&page=1&per_page=20
  #   Response: {
  #     "data": [
  #       { "id": 1, "title": "...", "status": "published" }
  #     ],
  #     "meta": { "total_count": 45, "page": 1, "per_page": 20 }
  #   }
  #
  # @example Filter by author and date
  #   GET /api/v1/posts?author_id=5&since=2025-01-01T00:00:00Z
  def index
    posts = Post.where(filter_params)
                .page(params[:page])
                .per(params[:per_page] || 20)
    
    render json: {
      data: posts,
      meta: pagination_meta(posts)
    }
  end
end

Ruby Gem API Documentation documents classes, modules, methods, and usage patterns for library consumers. Gem documentation includes installation instructions, configuration, basic usage, and advanced scenarios.

# Gem: payment_processor
# Version: 2.1.0

# Main payment processing interface
#
# PaymentProcessor handles credit card transactions including
# authorization, capture, refund, and void operations. Configure
# the processor with merchant credentials before use.
#
# @example Basic configuration and payment
#   processor = PaymentProcessor.new(
#     merchant_id: 'merchant_123',
#     api_key: 'sk_live_abc123'
#   )
#   
#   result = processor.charge(
#     amount: 1999,
#     currency: 'USD',
#     card_token: 'tok_visa_4242'
#   )
#   
#   if result.success?
#     puts "Payment successful: #{result.transaction_id}"
#   else
#     puts "Payment failed: #{result.error_message}"
#   end
#
# @see TransactionResult
# @see CardToken
class PaymentProcessor
  # Initializes payment processor with merchant credentials
  #
  # @param merchant_id [String] merchant account identifier
  # @param api_key [String] API secret key (starts with sk_)
  # @param options [Hash] optional configuration
  # @option options [Symbol] :environment (:production) :sandbox or :production
  # @option options [Integer] :timeout (30) request timeout in seconds
  # @option options [Boolean] :retry (true) retry failed requests
  #
  # @raise [ArgumentError] when credentials are invalid format
  # @raise [ConfigurationError] when environment is invalid
  def initialize(merchant_id:, api_key:, **options)
    # Implementation
  end

  # Charges a payment method
  #
  # Authorizes and captures payment in single operation. For separate
  # authorization and capture, use #authorize followed by #capture.
  #
  # @param amount [Integer] amount in cents (e.g., 1999 for $19.99)
  # @param currency [String] three-letter ISO 4217 code (e.g., 'USD')
  # @param card_token [String] tokenized card from tokenization service
  # @param metadata [Hash] optional metadata attached to transaction
  #
  # @return [TransactionResult] transaction result with status
  # @raise [InvalidAmountError] when amount is negative or zero
  # @raise [InvalidCurrencyError] when currency code is invalid
  # @raise [CardDeclinedError] when card issuer declines transaction
  # @raise [NetworkError] when payment network is unavailable
  #
  # @example Successful charge
  #   result = processor.charge(
  #     amount: 5000,
  #     currency: 'USD',
  #     card_token: 'tok_visa',
  #     metadata: { order_id: '12345' }
  #   )
  #   result.success? # => true
  #   result.transaction_id # => 'txn_abc123'
  #
  # @example Declined charge
  #   result = processor.charge(amount: 5000, currency: 'USD', card_token: 'tok_declined')
  #   result.success? # => false
  #   result.error_code # => 'card_declined'
  #   result.error_message # => 'Insufficient funds'
  def charge(amount:, currency:, card_token:, metadata: {})
    # Implementation
  end
end

GraphQL Schema Documentation describes types, queries, mutations, and relationships. GraphQL schemas are self-documenting through field and argument descriptions.

module Types
  class QueryType < Types::BaseObject
    description "The query root of the schema"

    field :user, Types::UserType, null: true do
      description "Find user by ID"
      argument :id, ID, required: true,
        description: "User unique identifier"
    end

    field :posts, [Types::PostType], null: false do
      description "List posts with optional filtering and pagination"
      
      argument :status, Types::PostStatusEnum, required: false,
        description: "Filter by publication status"
      
      argument :author_id, ID, required: false,
        description: "Filter by author ID"
      
      argument :first, Integer, required: false,
        description: "Number of items to return (max: 100)"
      
      argument :after, String, required: false,
        description: "Cursor for pagination"
    end
  end

  class MutationType < Types::BaseObject
    field :create_post, mutation: Mutations::CreatePost do
      description "Creates a new post"
    end
  end

  module Mutations
    class CreatePost < BaseMutation
      description "Creates a new post with title and content"

      argument :title, String, required: true,
        description: "Post title (3-200 characters)"
      
      argument :content, String, required: true,
        description: "Post content in markdown format"
      
      argument :status, Types::PostStatusEnum, required: false,
        description: "Initial publication status (default: draft)"

      field :post, Types::PostType, null: true,
        description: "Created post object"
      
      field :errors, [String], null: false,
        description: "Validation errors if creation failed"

      def resolve(title:, content:, status: 'draft')
        # Implementation
      end
    end
  end
end

Common Patterns

Reference Documentation Structure organizes API documentation into consistent sections. Each endpoint or method follows standard format: overview, authentication, parameters, request format, response format, error codes, examples. Consistent structure enables developers to scan documentation efficiently.

Resource-based organization groups endpoints by resource type (users, posts, comments). Each resource section includes CRUD operations, relationships, and resource-specific concepts. RESTful APIs naturally align with resource organization. Operation-based organization groups by operation type (read operations, write operations, admin operations) when resource organization is unclear.

Authentication Documentation Pattern describes authentication early in documentation since developers cannot use API without authentication. Authentication documentation includes credential acquisition, credential storage, request authentication, token refresh, and logout. Code examples demonstrate adding authentication headers or parameters.

# Authentication documentation pattern

## Authentication

All API requests require authentication using API keys passed in
the Authorization header with Bearer scheme.

### Obtaining API Key

API keys are generated in account settings dashboard. Each key
has permissions scope controlling accessible resources.

### Using API Key in Requests

Include API key in Authorization header:

Authorization: Bearer sk_live_abc123xyz


### Error Responses

Requests without authentication return 401 Unauthorized.
Requests with invalid credentials return 403 Forbidden.
Expired tokens return 401 with token_expired error code.

Error Response Pattern standardizes error response format across all endpoints. Consistent error format includes error code, error message, detailed description, field-specific errors, and correlation ID for support. Error documentation catalogs all possible error codes with causes and resolution steps.

# Standard error response
{
  "error": {
    "code": "validation_error",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "code": "invalid_format",
        "message": "Email address format is invalid"
      },
      {
        "field": "age",
        "code": "out_of_range",
        "message": "Age must be between 18 and 120"
      }
    ],
    "request_id": "req_abc123"
  }
}

Pagination Documentation Pattern explains pagination approach with examples. Cursor-based pagination documentation describes cursor format, page size limits, navigation links, and total count availability. Offset-based pagination documents page numbers, per-page limits, and total pages.

# Cursor-based pagination pattern
# @param after [String] cursor pointing to start position
# @param first [Integer] number of items to return (max: 100)
# @return [Hash] paginated response with edges and page info
# @return [Array<Hash>] :edges array of nodes with cursors
# @return [Hash] :page_info pagination metadata
# @return [String] :page_info.end_cursor cursor for next page
# @return [Boolean] :page_info.has_next_page whether more pages exist
#
# @example Fetch first page
#   list_items(first: 20)
#   # => {
#   #   edges: [
#   #     { node: {...}, cursor: "cursor1" },
#   #     { node: {...}, cursor: "cursor2" }
#   #   ],
#   #   page_info: {
#   #     end_cursor: "cursor20",
#   #     has_next_page: true
#   #   }
#   # }
#
# @example Fetch next page
#   list_items(after: "cursor20", first: 20)
def list_items(after: nil, first: 20)
  # Implementation
end

Versioning Documentation Pattern documents API version strategy, version deprecation timeline, and migration guides. URL versioning includes version in path (/api/v1/users). Header versioning uses custom header (API-Version: 2.0). Documentation maintains separate sections for each supported version with clear indication of current and deprecated versions.

Code Example Pattern includes complete, runnable examples demonstrating common use cases. Examples show request and response with realistic data. Multi-language examples demonstrate API usage in different programming languages. Examples progress from simple cases to complex scenarios with error handling.

Common Pitfalls

Outdated Documentation results from code changes without corresponding documentation updates. Developers modify implementations, add parameters, change response formats, or deprecate endpoints without updating documentation. Outdated documentation leads to integration failures, incorrect implementations, and support burden.

Automated documentation generation from code or specifications reduces staleness. Documentation tests validate examples against actual API behavior. Documentation review requirements in pull request process catch documentation drift. Versioned documentation maintains accuracy per API version.

Missing Error Scenarios documentation omits error conditions, error codes, and error response formats. Developers encounter undocumented errors during integration and cannot handle errors appropriately. Comprehensive error documentation catalogs validation errors, authentication errors, authorization errors, rate limit errors, server errors, and third-party service errors.

# Incomplete error documentation - BAD
# @raise [Error] when something goes wrong

# Complete error documentation - GOOD
# @raise [ValidationError] when parameters fail validation
# @raise [AuthenticationError] when API key is missing or invalid
# @raise [AuthorizationError] when user lacks permission
# @raise [ResourceNotFoundError] when requested resource does not exist
# @raise [RateLimitError] when rate limit exceeded (retry after header indicates wait time)
# @raise [ServerError] when internal error occurs (includes request_id for support)

Incomplete Examples show partial code that cannot run without additional context. Examples omit imports, initialization, error handling, or required configuration. Complete examples include setup, execution, response handling, and error handling. Examples use realistic data rather than placeholder values.

Assumed Knowledge documentation assumes readers understand concepts, protocols, or domain knowledge. API documentation should define domain-specific terms, explain authentication schemes, describe data formats, and clarify business logic. Glossary sections define terminology. Conceptual guides explain foundational concepts.

Poor Organization creates navigation difficulty when documentation lacks structure, consistent formatting, or clear hierarchy. Developers cannot find specific information quickly. Effective organization uses consistent resource grouping, clear section headers, comprehensive navigation, search functionality, and cross-references between related concepts.

Over-Documentation includes excessive detail that obscures important information. Verbose descriptions, redundant explanations, and obvious statements reduce documentation usability. Concise documentation states necessary information without unnecessary elaboration. Examples demonstrate usage without extensive commentary.

Missing Authentication Details documents authentication existence without explaining credential acquisition, credential format, request authentication mechanism, or token management. Developers cannot authenticate requests without complete authentication documentation including examples.

Inconsistent Terminology uses different terms for same concept across documentation. Parameter called "user_id" in one endpoint becomes "userId" in another. Response field "created_at" appears as "createdAt" elsewhere. Consistent terminology throughout documentation reduces confusion. Style guides enforce naming conventions.

Missing Rate Limit Information omits rate limit thresholds, time windows, limit headers, and throttling behavior. Developers cannot implement appropriate retry logic or request distribution. Rate limit documentation specifies requests per time period, concurrent connection limits, rate limit response codes, and retry-after headers.

Inadequate Type Information lacks precision about parameter types, response field types, null handling, and enum values. Ruby's dynamic typing makes explicit type documentation critical. Documentation specifies whether fields can be null, what values enums accept, and what hash keys are required versus optional.

Reference

Documentation Sections Checklist

Section Required Content Notes
Overview API purpose, capabilities, use cases Entry point for new users
Authentication Credential types, usage, lifecycle Block before other content
Base URL Production and sandbox endpoints Include protocol and versioning
Rate Limits Thresholds, headers, errors Prevent integration issues
Errors Codes, formats, resolution Comprehensive catalog
Pagination Strategy, parameters, navigation When returning lists
Versioning Current version, deprecation policy For evolving APIs
Endpoints Methods, paths, parameters, responses Core reference content

YARD Tag Reference

Tag Purpose Example
@param Document method parameter @param user_id [Integer] user ID
@option Document hash option @option opts [String] :format format type
@return Document return value @return [Array] user list
@raise Document exception @raise [NotFoundError] when missing
@example Provide usage example @example Basic usage
@see Reference related item @see OtherClass for details
@deprecated Mark as deprecated @deprecated Use new_method instead
@since Indicate version added @since 2.0.0
@note Add important note @note Requires authentication

HTTP Status Code Reference

Code Meaning API Usage
200 OK Successful GET, PUT, PATCH
201 Created Successful POST creating resource
204 No Content Successful DELETE
400 Bad Request Invalid request parameters
401 Unauthorized Missing or invalid authentication
403 Forbidden Insufficient permissions
404 Not Found Resource does not exist
422 Unprocessable Entity Validation failed
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error occurred
503 Service Unavailable Temporary unavailability

OpenAPI Schema Types

Type Format Ruby Equivalent Description
string - String Text data
string date-time Time, DateTime ISO 8601 timestamp
string email String Email address
string uri URI, String URI reference
integer int32 Integer 32-bit integer
integer int64 Integer 64-bit integer
number float Float Floating point
number double Float Double precision
boolean - TrueClass, FalseClass Boolean value
array - Array Ordered collection
object - Hash Key-value pairs

Request Documentation Template

### [METHOD] [PATH]

[Brief description of what this endpoint does]

**Authentication:** [Required/Optional] [Type]

**Rate Limit:** [Limit specification]

**Parameters:**

Path Parameters:
- parameter_name (type, required/optional): Description

Query Parameters:
- parameter_name (type, required/optional): Description
- Default: [default_value]
- Constraints: [constraints]

Request Body:
- field_name (type, required/optional): Description

**Response:**

Success Response (status_code):
- field_name (type): Description

Error Responses:
- status_code: Condition causing error

**Example Request:**

[Code block showing request]

**Example Response:**

[Code block showing response]

GraphQL Type Documentation Template

Type TypeName
  Description of what this type represents

  Field field_name: ReturnType
    Description of field
    
    Arguments:
      argument_name (Type, required/optional): Description
      
    Returns: Description of return value
    
    Errors:
      - ErrorType: When this error occurs

Common Error Response Format

{
  "error": {
    "code": "error_code",
    "message": "Human-readable error message",
    "details": [
      {
        "field": "field_name",
        "code": "field_error_code",
        "message": "Field-specific error message"
      }
    ],
    "request_id": "unique_request_identifier",
    "documentation_url": "https://docs.example.com/errors/error_code"
  }
}