### Customizing API Example Data Structure Source: https://github.com/apipie/apipie-rails/blob/master/README.md An example YAML structure demonstrating how to customize API documentation examples, including adding titles, specifying HTTP verbs, paths, versions, and controlling visibility with `show_in_doc`. ```yaml --- !omap - announcements#index: - !omap - title: This is a custom title for this example - verb: :GET - path: /api/blabla/1 - versions: - '1.0' - query: - request_data: - response_data: ... - code: 200 - show_in_doc: 1 # If 1, show. If 0, do not show. - recorded: true ``` -------------------------------- ### Install Dependencies and Run Tests (Shell) Source: https://github.com/apipie/apipie-rails/blob/master/README.md This snippet shows the commands to install project dependencies using Bundler and then run the test suite with RSpec. These are common steps for contributing to the project. ```shell > bundle install > bundle exec rspec ``` -------------------------------- ### Install Apipie-Rails Gem Source: https://github.com/apipie/apipie-rails/blob/master/README.md This snippet demonstrates the steps to install the apipie-rails gem using Bundler and generate its initial configuration files within a Rails application. ```shell echo "gem 'apipie-rails'" >> Gemfile bundle install rails g apipie:install ``` -------------------------------- ### Record API Examples with Rails Server Source: https://github.com/apipie/apipie-rails/blob/master/README.md Run your Rails server with the `APIPIE_RECORD=examples` environment variable to generate up-to-date examples for your API documentation by recording data from tests run against a live server. ```bash APIPIE_RECORD=examples rails server ``` -------------------------------- ### Record API Examples with Rake Source: https://github.com/apipie/apipie-rails/blob/master/README.md Utilize the `APIPIE_RECORD=examples` environment variable with the `rake test:functionals` task to generate up-to-date examples for your API documentation by recording data from functional tests. ```bash APIPIE_RECORD=examples rake test:functionals ``` -------------------------------- ### Marking RSpec Examples for API Documentation Source: https://github.com/apipie/apipie-rails/blob/master/README.md This RSpec code demonstrates how to mark specific examples with the `:show_in_doc` metadata to indicate they should be used as API documentation examples when running in recording mode. ```ruby describe "This is the correct path" do it "some test", :show_in_doc do .... end end context "These are edge cases" do it "Can't authenticate" do .... end it "record not found" do .... end end ``` -------------------------------- ### Integrate Apipie with RSpec for Example Recording Source: https://context7.com/apipie/apipie-rails/llms.txt Configures RSpec to work with apipie for recording real API request/response examples. It includes necessary require statements and environment variable checks for recording. The examples demonstrate how to make requests and assert responses, automatically validating them against the documented API specifications. ```ruby # spec/spec_helper.rb or spec/rails_helper.rb require 'apipie/rspec/response_validation_helper' RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.filter_run show_in_doc: true if ENV['APIPIE_RECORD'] end # spec/requests/users_spec.rb require 'rails_helper' RSpec.describe 'Users API', type: :request do describe 'GET /api/users/:id' do it 'returns user profile', show_in_doc: true do user = create(:user, username: 'john_doe', email: 'john@example.com') get "/api/users/#{user.id}", headers: { 'Authorization' => "Bearer #{auth_token}" } expect(response).to have_http_status(200) expect(JSON.parse(response.body)).to include( 'id' => user.id, 'username' => 'john_doe', 'email' => 'john@example.com' ) # Automatically validates response matches documentation expect(response).to match_declared_responses end it 'returns 404 for missing user', show_in_doc: true do get '/api/users/99999', headers: { 'Authorization' => "Bearer #{auth_token}" } expect(response).to have_http_status(404) expect(response).to match_declared_responses end end end # Run tests with recording enabled: # APIPIE_RECORD=examples bundle exec rspec # This generates doc/apipie_examples.yml with captured requests/responses ``` -------------------------------- ### HashValidator Example Source: https://github.com/apipie/apipie-rails/blob/master/README.md Shows how to define detailed validation rules for hash parameters, including nested parameters and their types and requirements. ```APIDOC ## HashValidator You can describe hash parameters in depth if you provide a block with a description of nested values. ### Example ```ruby param :user, Hash, :desc => "User info" do param :username, String, :desc => "Username for login", :required => true param :password, String, :desc => "Password for login", :required => true param :membership, ["standard","premium"], :desc => "User membership" end ``` ``` -------------------------------- ### Describe Nested Parameters with Validation (Ruby) Source: https://github.com/apipie/apipie-rails/blob/master/README.md This example demonstrates how to define nested parameters within a parent hash parameter using Apipie-Rails. It shows how to specify validators, set parameters as required, provide examples, and define custom messages for missing parameters. It also illustrates how to hide parameters from documentation and use metadata. ```ruby param :user, Hash, :desc => "User info" do param :username, String, :desc => "Username for login", :required => true, :example => 'John' param :password, String, :desc => "Password for login", :required => true, :example => '1234567' param :membership, ["standard","premium"], :desc => "User membership" param :admin_override, String, :desc => "Not shown in documentation", :show => false param :ip_address, String, :desc => "IP address", :required => true, :missing_message => lambda { I18n.t("ip_address.required") } end def create #... end ``` -------------------------------- ### Configure Apipie Rails Initializer (Ruby) Source: https://context7.com/apipie/apipie-rails/llms.txt Provides a comprehensive example of configuring Apipie-Rails within a Rails initializer file (`config/initializers/apipie.rb`). It covers setting the application name, API base URL, documentation base URL, default version, and enabling/configuring parameter validation. It also demonstrates how to specify controller locations, enable controller reloading, define application information per version, set up authentication for documentation access, choose a markup language, and configure caching. ```ruby # config/initializers/apipie.rb Apipie.configure do |config| config.app_name = 'MyApp API' config.api_base_url = '/api/v1' config.doc_base_url = '/apidoc' config.default_version = '1.0' # Enable automatic parameter validation config.validate = :implicitly config.validate_value = true config.validate_presence = true config.validate_key = false # Specify where API controllers are located config.api_controllers_matcher = File.join(Rails.root, 'app', 'controllers', 'api', '**', '*.rb') # Enable controller reloading in development config.reload_controllers = Rails.env.development? # Application description per version config.app_info['1.0'] = 'MyApp REST API v1.0 - Comprehensive documentation' # Setup authentication for documentation access config.authenticate = Proc.new do authenticate_or_request_with_http_basic do |username, password| username == ENV['DOC_USER'] && password == ENV['DOC_PASSWORD'] end end # Use Markdown for descriptions config.markup = Apipie::Markup::Markdown.new # Enable cache in production config.use_cache = Rails.env.production? config.cache_dir = File.join(Rails.root, 'public', 'apipie-cache') end ``` -------------------------------- ### ArrayValidator Examples Source: https://github.com/apipie/apipie-rails/blob/master/README.md Illustrates various uses of the ArrayValidator, including specifying item types, valid item values, and using lambdas for deferred value retrieval. ```APIDOC ## ArrayValidator Check if the parameter is an array Additional options `of` Specify the type of items. If not given it accepts an array of any item type `in` Specify an array of valid item values. ### Examples Assert `things` is an array of any items ```ruby param :things, Array ``` Assert `hits` must be an array of integer values ```ruby param :hits, Array, of: Integer ``` Assert `colors` must be an array of valid string values ```ruby param :colors, Array, in: ["red", "green", "blue"] ``` The retrieving of valid items can be deferred until needed using a lambda. It is evaluated only once ```ruby param :colors, Array, in: -> { Color.all.pluck(:name) } ``` ``` -------------------------------- ### Set API Documentation Locale Source: https://github.com/apipie/apipie-rails/blob/master/README.md This code example shows how to configure the locale setting for Apipie-Rails documentation generation. It uses a lambda to dynamically set the locale using `FastGettext`. ```ruby config.locale = lambda { |loc| loc ? FastGettext.set_locale(loc) : FastGettext.locale } ``` -------------------------------- ### GET /pets/:id/extra_info - Describing Multiple Return Codes Source: https://github.com/apipie/apipie-rails/blob/master/README.md Demonstrates how to use the `:returns` keyword multiple times to describe different possible return codes and their associated response formats for an API endpoint. ```APIDOC ## GET /pets/:id/extra_info ### Description Get extra information about a pet, with specific handling for different return scenarios. ### Method GET ### Endpoint /pets/:id/extra_info ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the pet. ### Response #### Success Response (200) - **desc**: Found a pet - **pet_history**: Hash - Contains pet history details. #### Error Response (422 Unprocessable Entity) - **code**: :unprocessable_entity - **desc**: Fleas were discovered on the pet - **num_fleas**: Integer - Number of fleas on this pet. ### Response Example ```json { "pet": { "id": 1, "name": "Buddy" }, "pet_history": { "last_walk": "2023-10-27T10:00:00Z" } } ``` ### Error Response Example (422) ```json { "pet": { "id": 1, "name": "Buddy" }, "num_fleas": 5 } ``` ``` -------------------------------- ### Apipie DSL: Using `returns` with type identifier Source: https://github.com/apipie/apipie-rails/blob/master/PROPOSAL_FOR_RESPONSE_DESCRIPTIONS.md Shows an example of the proposed `returns` keyword usage in Apipie DSL, where a type identifier is provided. If the code is not specified, it defaults to 200. ```ruby api :GET, "/users/:id", "Show user profile" error :code => 401, :desc => "Unauthorized" returns :SomeTypeIdentifier # :code is not specified, so it is assumed to be 200 ``` -------------------------------- ### DecimalValidator Example Source: https://github.com/apipie/apipie-rails/blob/master/README.md Describes the DecimalValidator for validating parameters as decimal numbers. ```APIDOC ## DecimalValidator Check if the parameter is a decimal number ### Examples ```ruby param :latitude, :decimal, :desc => "Geographic latitude", :required => true param :longitude, :decimal, :desc => "Geographic longitude", :required => true ``` ``` -------------------------------- ### NilValidator Example Source: https://github.com/apipie/apipie-rails/blob/master/README.md Explains that setting a parameter to nil can override resource-level parameter definitions, effectively making the parameter optional or unsetting it. ```APIDOC ## NilValidator In fact there isn't any NilValidator, but setting it to nil can be used to override parameters described on the resource level. ### Example ```ruby param :user, nil def destroy #... end ``` ``` -------------------------------- ### Configuring RSpec for API Documentation Recording Source: https://github.com/apipie/apipie-rails/blob/master/README.md Configure RSpec to interpret symbols as metadata keys and to filter examples based on the `show_in_doc` metadata when the `APIPIE_RECORD` environment variable is set. ```ruby RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.filter_run :show_in_doc => true if ENV['APIPIE_RECORD'] end ``` -------------------------------- ### GET /api/products/search Source: https://context7.com/apipie/apipie-rails/llms.txt Allows searching for products using various query parameters. This endpoint leverages reusable search parameters defined in the Api::Searchable concern. ```APIDOC ## GET /api/products/search ### Description Searches for products based on the provided query parameters. Supports filtering, pagination, and sorting. ### Method GET ### Endpoint /api/products/search ### Parameters #### Query Parameters - **q** (String) - Required - The search query string. - **page** (Integer) - Optional - The page number for pagination. Defaults to 1. - **per_page** (Integer) - Optional - The number of results per page. Defaults to 20. - **sort_by** (Enum: 'relevance', 'created_at', 'updated_at') - Optional - The field to sort the results by. Defaults to 'relevance'. - **order** (Enum: 'asc', 'desc') - Optional - The order of sorting. Defaults to 'desc'. ### Request Example ```json { "q": "example product", "page": 1, "per_page": 10, "sort_by": "created_at", "order": "asc" } ``` ### Response #### Success Response (200) - **results** (Array) - An array of product search results. - **total** (Integer) - The total number of matching results. - **page** (Integer) - The current page number. - **per_page** (Integer) - The number of results per page. #### Response Example ```json { "results": [ { "id": 1, "name": "Example Product 1", "description": "This is the first example product." }, { "id": 2, "name": "Example Product 2", "description": "This is the second example product." } ], "total": 50, "page": 1, "per_page": 10 } ``` ``` -------------------------------- ### ProcValidator Example Source: https://github.com/apipie/apipie-rails/blob/master/README.md Demonstrates how to use a Proc or lambda for custom, non-reusable parameter validation. The Proc should return true for valid values or an error message string. ```APIDOC ## ProcValidator If you need more complex validation and you know you won't reuse it, you can use the Proc/lambda validator. Provide your own Proc, taking the value of the parameter as the only argument. Return true if value passes validation or return some text about what is wrong otherwise. Don't use the keyword *return* if you provide an instance of Proc (with lambda it is ok), just use the last statement return property of ruby. ### Example ```ruby param :proc_param, lambda { |val| val == "param value" ? true : "The only good value is 'param value'." }, :desc => "proc validator" ``` ``` -------------------------------- ### Define and Use Parameter Groups for DRY Code (Ruby) Source: https://github.com/apipie/apipie-rails/blob/master/README.md This example shows how to define reusable parameter groups using `def_param_group` and then include them in API definitions with `param_group`. This promotes DRY principles by avoiding repeated parameter definitions across multiple actions like `create` and `update`. It also demonstrates referencing parameter groups from other controllers. ```ruby # v1/users_controller.rb def_param_group :address do param :street, String param :number, Integer param :zip, String end def_param_group :user do param :user, Hash do param :name, String, "Name of the user" param_group :address end end api :POST, "/users", "Create a user" param_group :user def create # ... end api :PUT, "/users/:id", "Update a user" param_group :user def update # ... end # v2/users_controller.rb api :POST, "/users", "Create a user" param_group :user, V1::UsersController def create # ... end ``` -------------------------------- ### Document API Endpoint with Parameters and Responses (Ruby) Source: https://context7.com/apipie/apipie-rails/llms.txt Demonstrates how to document a GET API endpoint for retrieving a user profile by ID using Apipie's DSL. It specifies the HTTP method, path, description, required parameters, error codes, and the structure of the successful response. This snippet requires a Rails controller and ActiveRecord model. ```ruby class UsersController < ApplicationController api :GET, '/users/:id', 'Retrieve user profile by ID' param :id, Integer, desc: 'User ID', required: true error code: 404, desc: 'User not found' error code: 401, desc: 'Unauthorized access' returns code: 200, desc: 'User profile data' do property :id, Integer, desc: 'User ID' property :username, String, desc: 'Username' property :email, String, desc: 'Email address' property :created_at, String, desc: 'Account creation timestamp' end def show user = User.find(params[:id]) render json: { id: user.id, username: user.username, email: user.email, created_at: user.created_at } rescue ActiveRecord::RecordNotFound render json: { error: 'User not found' }, status: 404 end end ``` -------------------------------- ### Document API Endpoint with Apipie-Rails DSL Source: https://github.com/apipie/apipie-rails/blob/master/README.md This Ruby code snippet illustrates how to use Apipie-rails' DSL to document a GET request for a specific user endpoint. It defines the HTTP method, the endpoint path, and a parameter with its description. ```ruby api :GET, '/users/:id' param :id, :number, desc: 'id of the requested user' def show # ... end ``` -------------------------------- ### Customizing Rails Route Formatting Source: https://github.com/apipie/apipie-rails/blob/master/README.md This example demonstrates how to create a custom Apipie Rails route formatter to modify how API paths are displayed. It shows how to inherit from `Apipie::RoutesFormatter` and override the `format_path` method to remove implicit parameters and extra slashes from route paths. ```ruby class MyFormatter < Apipie::RoutesFormatter def format_path(route) super.gsub(/(.*?)/, '').gsub('//','') # hide all implicit parameters end end Apipie.configure do |config| ... config.routes_formatter = MyFormatter.new ... end ``` -------------------------------- ### Define API Endpoint with Parameters and Responses (Ruby) Source: https://github.com/apipie/apipie-rails/blob/master/README.md This snippet shows how to define a GET API endpoint for user profiles using Apipie-Rails. It includes parameter definitions with different validators (String, Regex, Array, Boolean, Proc), error codes, and structured response properties. The `param` and `property` keywords are used to detail request and response structures. ```ruby api :GET, "/users/:id", "Show user profile" show false error :code => 401, :desc => "Unauthorized" error :code => 404, :desc => "Not Found", :meta => {:anything => "you can think of"} param :session, String, :desc => "user is logged in", :required => true param :regexp_param, /^[0-9]* years/, :desc => "regexp param" param :array_param, [100, "one", "two", 1, 2], :desc => "array validator" param :boolean_param, [true, false], :desc => "array validator with boolean" param :proc_param, lambda { |val| val == "param value" ? true : "The only good value is 'param value'." }, :desc => "proc validator" param :param_with_metadata, String, :desc => "", :meta => [:your, :custom, :metadata] returns :code => 200, :desc => "a successful response" do property :value1, String, :desc => "A string value" property :value2, Integer, :desc => "An integer value" property :value3, Hash, :desc => "An object" do property :enum1, ['v1', 'v2'], :desc => "One of 2 possible string values" end end tags %w[profiles logins] tags 'more', 'related', 'resources' description "method description" formats ['json', 'jsonp', 'xml'] meta :message => "Some very important info" example " 'user': {...} " see "users#showme", "link description" see :link => "users#update", :desc => "another link description" def show #... end ``` -------------------------------- ### Automated Response Validation with Apipie-Rails Source: https://github.com/apipie/apipie-rails/blob/master/README.md This snippet illustrates the automated response validation mechanism provided by Apipie-Rails. By calling `auto_validate_rendered_views`, RSpec tests are automatically injected into HTTP operations like 'get' and 'post'. If a response does not match the swagger definitions, an error is raised. This example shows its usage within controller specs. ```ruby require 'apipie/rspec/response_validation_helper' RSpec.describe MyController, :type => :controller, :show_in_doc => true do describe "GET stuff with response validation" do render_views auto_validate_rendered_views it "does something" do get :index, {format: :json} end it "does something else" do get :another_index, {format: :json} end end describe "GET stuff without response validation" do it "does something" do get :index, {format: :json} end it "does something else" do get :another_index, {format: :json} end end end ``` -------------------------------- ### Record API Documentation Parameters with Rails Server Source: https://github.com/apipie/apipie-rails/blob/master/README.md Run your Rails server with the `APIPIE_RECORD=params` environment variable to bootstrap API documentation by recording request/response data from tests run against a live server. ```bash APIPIE_RECORD=params rails server ``` -------------------------------- ### Describe Multiple API Return Codes in Ruby Source: https://github.com/apipie/apipie-rails/blob/master/README.md Demonstrates how to use repeated `:returns` keywords to define multiple possible API return codes, each with potentially different response formats. This allows for detailed documentation of various API outcomes. ```ruby api :GET, "/pets/:id/extra_info", "Get extra information about a pet" returns :desc => "Found a pet" do param_group :pet property 'pet_history', Hash do param_group :pet_history end end returns :code => :unprocessable_entity, :desc => "Fleas were discovered on the pet" do param_group :pet property :num_fleas, Integer, :desc => "Number of fleas on this pet" end def show_extra_info # ... implementation here end ``` -------------------------------- ### GET /api/users/:id - Get User with Enhanced Data Source: https://context7.com/apipie/apipie-rails/llms.txt Retrieves detailed user information, including profile data. Supports API versions 2.0 and 3.0. ```APIDOC ## GET /api/users/:id ### Description Get user with enhanced data. Supports API versions 2.0 and 3.0. ### Method GET ### Endpoint /api/users/:id ### Parameters #### Path Parameters - **id** (Integer) - Required - The ID of the user to retrieve. #### Query Parameters - **include_roles** (Boolean) - Optional - Whether to include user roles in the response. ### Request Example ```json { "include_roles": true } ``` ### Response #### Success Response (200) - **id** (Integer) - The user's unique identifier. - **username** (String) - The user's username. - **profile** (Hash) - An object containing user profile information. - **avatar_url** (String) - The URL of the user's avatar. - **bio** (String) - The user's biography. #### Response Example ```json { "id": 1, "username": "john_doe", "profile": { "avatar_url": "http://example.com/avatars/john.png", "bio": "Software engineer and tech enthusiast." } } ``` ``` -------------------------------- ### Specifying Response Headers with `header` (Ruby) Source: https://github.com/apipie/apipie-rails/blob/master/README.md Demonstrates how to document response headers within the `returns` block using the `header` keyword. This allows specifying the header name, type, description, and whether it's required, enhancing the API documentation with details about the response metadata. ```ruby api :GET, "/pets/:id/with-extra-details", "Get a detailed pet record" returns code: 200, desc: "Detailed info about the pet" do param_group :pet property :num_legs, Integer, :desc => "How many legs the pet has" header 'Link', String, 'Relative links' header 'Current-Page', Integer, 'The current page', required: true end def show render JSON({ :pet_name => "Barkie", :animal_type => "iguana", :legs => 4 }) end ``` -------------------------------- ### Describe API Method using `api!` in Ruby Source: https://github.com/apipie/apipie-rails/blob/master/README.md This Ruby code demonstrates the simplest way to describe an API method using apipie-rails. The `api!` macro is used to automatically load API paths from the `routes.rb` file, with a short description for the method. ```ruby # The simplest case: just load the paths from routes.rb api! def index end ``` -------------------------------- ### NumberValidator Example Source: https://github.com/apipie/apipie-rails/blob/master/README.md Documents the NumberValidator, used to ensure a parameter is a positive integer or zero. ```APIDOC ## NumberValidator Check if the parameter is a positive integer number or zero ### Examples ```ruby param :product_id, :number, :desc => "Identifier of the product", :required => true param :quantity, :number, :desc => "Number of products to order", :required => true ``` ``` -------------------------------- ### NestedValidator Example Source: https://github.com/apipie/apipie-rails/blob/master/README.md Demonstrates how to use NestedValidator within an ArrayValidator to define the structure and validation rules for elements within an array. ```APIDOC ### NestedValidator You can describe nested parameters in depth if you provide a block with a description of nested values. ### Example ```ruby param :comments, Array, :desc => "User comments" do param :name, String, :desc => "Name of the comment", :required => true param :comment, String, :desc => "Full comment", :required => true end ``` ``` -------------------------------- ### Apipie DSL: Proposed `returns` keyword syntax Source: https://github.com/apipie/apipie-rails/blob/master/PROPOSAL_FOR_RESPONSE_DESCRIPTIONS.md Illustrates the proposed syntax for the `returns` keyword in the Apipie DSL. This keyword allows API authors to specify return types, optionally including HTTP status codes and descriptions. ```ruby returns [, :code => ] [, :desc => ] ``` -------------------------------- ### Configure Apipie-Rails Application Settings Source: https://github.com/apipie/apipie-rails/blob/master/README.md This snippet demonstrates how to configure essential Apipie-Rails settings within an initializer file. It covers setting the application name, copyright information, documentation base URL, API base URL, and disabling validation. ```ruby Apipie.configure do |config| config.app_name = "Test app" config.copyright = "© 2012 Pavel Pokorny" config.doc_base_url = "/apidoc" config.api_base_url = "/api" config.validate = false end ``` -------------------------------- ### Documenting API Responses with `returns` (Ruby) Source: https://github.com/apipie/apipie-rails/blob/master/README.md Illustrates different ways to document API responses using the `returns` statement in Apipie-Rails. This includes referencing predefined parameter groups, defining responses inline, and documenting array-of-objects responses. The `:code` option specifies the HTTP status code, and `:desc` provides a human-readable description. Uses `property` keyword for response-only fields. ```ruby # format #1: reference to a param-group returns [, :code => |] [, :desc => ] # format #2: inline response definition returns :code => | [, :desc => ] do # property ... # property ... # param_group ... end # format #3: describing an array-of-objects response returns :array_of => [, :code => |] [, :desc => ] ``` ```ruby # Example of format #1 (reference to param-group): def_param_group :pet do property :pet_name, String, :desc => "Name of pet" property :animal_type, ['dog','cat','iguana','kangaroo'], :desc => "Type of pet" end api :GET, "/pets/:id", "Get a pet record" returns :pet, :desc => "The pet" def show_detailed render JSON({:pet_name => "Skippie", :animal_type => "kangaroo"}) end ``` ```ruby # Example of format #2 (inline): api :GET, "/pets/:id/with-extra-details", "Get a detailed pet record" returns :code => 200, :desc => "Detailed info about the pet" do param_group :pet property :num_legs, Integer, :desc => "How many legs the pet has" end def show render JSON({:pet_name => "Barkie", :animal_type => "iguana", :legs => 4}) end ``` ```ruby # Example of format #3 (array response): api :GET, "/pets", "Get all pet records" returns :array_of => :pet, :code => 200, :desc => "All pets" def index render JSON([ {:pet_name => "Skippie", :animal_type => "kangaroo"}, {:pet_name => "Woofie", :animal_type => "cat"} ]) end ``` -------------------------------- ### Configure Localization with FastGettext Source: https://github.com/apipie/apipie-rails/blob/master/README.md Integrate API documentation localization using FastGettext. This involves setting supported languages, the default locale, and defining lambdas for locale setting and string translation. API strings intended for translation should be marked with `N_()`. ```ruby Apipie.configure do |config| ... config.languages = ['en', 'cs'] config.default_locale = 'en' config.locale = lambda { |loc| loc ? FastGettext.set_locale(loc) : FastGettext.locale } config.translate = lambda do |str, loc| old_loc = FastGettext.locale FastGettext.set_locale(loc) trans = _(str) FastGettext.set_locale(old_loc) trans end end api :GET, "/users/:id", N_("Show user profile") param :session, String, :desc => N_("user is logged in"), :required => true ``` -------------------------------- ### API Versioning - GET /api/v1/users/:id Source: https://context7.com/apipie/apipie-rails/llms.txt Retrieves user information for API version 1.0. This endpoint is deprecated. ```APIDOC ## GET /api/v1/users/:id ### Description Get user (v1 - deprecated). ### Method GET ### Endpoint /api/v1/users/:id ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) (Response structure depends on V1::UserSerializer) #### Response Example ```json { "user_data_v1": "..." } ``` ``` -------------------------------- ### Adding Custom Validator Source: https://github.com/apipie/apipie-rails/blob/master/README.md Provides a guide on how to create and register custom validators by subclassing `Apipie::Validator::BaseValidator` and implementing the `validate` and `build` methods. ```APIDOC ## Adding custom validator Only basic validators are included but it is really easy to add your own. Create a new initializer with a subclass of Apipie::Validator::BaseValidator. Two methods are required to implement this - instance method `validate(value)` and class method `build(param_description, argument, options, block)`. When searching for the validator +build+ method, every subclass of Apipie::Validator::BaseValidator is called. The first one that returns the constructed validator object is used. Example: Adding IntegerValidator We want to check if the parameter value is an integer like this: ```ruby param :id, Integer, :desc => "Company ID" ``` So we create apipie_validators.rb initializer with this content: ```ruby class IntegerValidator < Apipie::Validator::BaseValidator def initialize(param_description, argument) super(param_description) @type = argument end def validate(value) return false if value.nil? !!(value.to_s =~ /^[-+]?[0-9]+$/) end def self.build(param_description, argument, options, block) if argument == Integer self.new(param_description, argument) end end def description "Must be #{@type}." end def expected_type 'numeric' end end ``` Parameters of the build method: `param_description` Instance of Apipie::ParamDescription contains all given information about the validated parameter. `argument` Specified validator; in our example it is +Integer+ `options` Hash with specified options, for us just `{:desc => "Company ID"}` `block` Block converted into Proc, use it as you desire. In this example nil. If your validator includes valid values that respond true to `.blank?`, you should also define: ```ruby def ignore_allow_blank? true end ``` so that the validation does not fail for valid values. ``` -------------------------------- ### Action-Aware Parameters in Ruby Source: https://github.com/apipie/apipie-rails/blob/master/README.md Demonstrates how to define parameter groups that adapt their requirements based on the API action (create or update). This allows for reusable parameter definitions that are only required for specific actions, improving code organization. It uses `action_aware: true` and the `:as` option. ```ruby def_param_group :user do param :user, Hash, :action_aware => true do param :name, String, :required => true param :description, String end end api :POST, "/users", "Create a user" param_group :user def create # ... end api :PUT, "/users/admin", "Create an admin" param_group :user, :as => :create def create_admin # ... end api :PUT, "/users/:id", "Update a user" param_group :user def update # ... end ``` -------------------------------- ### Configure Localization with I18n Source: https://github.com/apipie/apipie-rails/blob/master/README.md Set up API documentation localization using the standard I18n gem. This configuration involves specifying languages, the default locale, and lambdas for locale management and translation, using translation keys directly in API documentation strings. ```ruby Apipie.configure do |config| ... config.languages = ['en', 'cs'] config.default_locale = 'en' config.locale = lambda { |loc| loc ? I18n.locale = loc : I18n.locale } config.translate = lambda do |str, loc| return '' if str.blank? I18n.t str, locale: loc, scope: 'doc' end end api :GET, "/users/:id", "show_user_profile" param :session, String, :desc => "user_is_logged_in", :required => true ``` -------------------------------- ### GET /index - Embedded Response Descriptions with Self-Describing Classes Source: https://github.com/apipie/apipie-rails/blob/master/README.md Shows how to use a 'self-describing-class' (like `Pet`) to define response properties externally, making the API endpoint definition cleaner. ```APIDOC ## GET /index ### Description Get all pets. Response properties are described by the `Pet` class itself. ### Method GET ### Endpoint /index ### Response #### Success Response (200) - **pet_name** (String) - Name of pet. - **animal_type** (String) - Type of pet (values: "dog", "cat", "iguana", "kangaroo"). ### Response Example ```json [ { "pet_name": "Buddy", "animal_type": "dog" }, { "pet_name": "Whiskers", "animal_type": "cat" } ] ``` ``` -------------------------------- ### GET /api/articles/search Source: https://context7.com/apipie/apipie-rails/llms.txt Allows searching for articles using various query parameters. This endpoint leverages reusable search parameters defined in the Api::Searchable concern. ```APIDOC ## GET /api/articles/search ### Description Searches for articles based on the provided query parameters. Supports filtering, pagination, and sorting. ### Method GET ### Endpoint /api/articles/search ### Parameters #### Query Parameters - **q** (String) - Required - The search query string. - **page** (Integer) - Optional - The page number for pagination. Defaults to 1. - **per_page** (Integer) - Optional - The number of results per page. Defaults to 20. - **sort_by** (Enum: 'relevance', 'created_at', 'updated_at') - Optional - The field to sort the results by. Defaults to 'relevance'. - **order** (Enum: 'asc', 'desc') - Optional - The order of sorting. Defaults to 'desc'. ### Request Example ```json { "q": "example article", "page": 1, "per_page": 10, "sort_by": "created_at", "order": "asc" } ``` ### Response #### Success Response (200) - **results** (Array) - An array of article search results. - **total** (Integer) - The total number of matching results. - **page** (Integer) - The current page number. - **per_page** (Integer) - The number of results per page. #### Response Example ```json { "results": [ { "id": 1, "title": "Example Article 1", "content": "This is the content of the first example article." }, { "id": 2, "title": "Example Article 2", "content": "This is the content of the second example article." } ], "total": 50, "page": 1, "per_page": 10 } ``` ``` -------------------------------- ### Record API Documentation Parameters with Rake Source: https://github.com/apipie/apipie-rails/blob/master/README.md Use the `APIPIE_RECORD=params` environment variable with the `rake test:functionals` task to bootstrap API documentation by recording request/response data from functional tests. ```bash APIPIE_RECORD=params rake test:functionals ``` -------------------------------- ### Describe API Resources with Shared Parameters and Metadata (Ruby) Source: https://context7.com/apipie/apipie-rails/llms.txt Document entire API resources using `resource_description` to define shared parameters, metadata, and descriptions. This includes specifying formats, API versions, common errors, and global parameters applicable to all actions within the resource. It also allows for a detailed markdown description of the resource. ```ruby class Api::V1::ProductsController < ApplicationController resource_description do short 'Product catalog management' formats ['json'] api_version '1.0' error code: 401, desc: 'Authentication required' error code: 403, desc: 'Insufficient permissions' param :api_key, String, desc: 'API authentication key', required: true description <<-DESC ## Product Management API This resource provides complete CRUD operations for product catalog management. All endpoints require valid API key authentication via the api_key parameter. Products support categories, tags, pricing, inventory tracking, and image management. DESC end api :GET, '/products', 'List all products with pagination' param :page, Integer, desc: 'Page number', default_value: 1 param :per_page, Integer, desc: 'Items per page', default_value: 25 param :category, String, desc: 'Filter by category' returns :array_of => :product, code: 200 def index products = Product.page(params[:page]).per(params[:per_page]) render json: products end end ``` -------------------------------- ### Configure Apipie-Rails Settings Source: https://github.com/apipie/apipie-rails/blob/master/README.md This snippet shows common configuration options for Apipie-Rails, including setting the markup language, reload behavior, API controller and action matchers, API routes, application information, and authentication/authorization callbacks. ```ruby Apipie.configure do |config| config.markup = Apipie::Markup::Markdown.new config.reload_controllers = Rails.env.development? config.api_controllers_matcher = File.join(Rails.root, "app", "controllers", "**","*.rb") config.api_action_matcher = proc { |controller| controller.params[:action] } config.api_routes = Rails.application.routes config.app_info["1.0"] = " This is where you can inform user about your application and API in general. " config.authenticate = Proc.new do authenticate_or_request_with_http_basic do |username, password| username == "test" && password == "supersecretpassword" end end config.authorize = Proc.new do |controller, method, doc| !method # show all controller doc, but no method docs. end end ``` -------------------------------- ### GET /users/:id - Retrieve user profile by ID Source: https://context7.com/apipie/apipie-rails/llms.txt This endpoint retrieves a user's profile information based on their unique ID. It handles cases where the user is not found or access is unauthorized. ```APIDOC ## GET /users/:id ### Description Retrieve user profile by ID. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (Integer) - Required - User ID #### Query Parameters *None* #### Request Body *None* ### Request Example *Not Applicable* ### Response #### Success Response (200) - **id** (Integer) - User ID - **username** (String) - Username - **email** (String) - Email address - **created_at** (String) - Account creation timestamp #### Response Example ```json { "id": 1, "username": "johndoe", "email": "johndoe@example.com", "created_at": "2023-10-27T10:00:00Z" } ``` #### Error Responses - **404** - User not found - **401** - Unauthorized access ``` -------------------------------- ### Tag and Build Gem (Bash) Source: https://github.com/apipie/apipie-rails/blob/master/rel-eng/gem_release.ipynb Tags the current commit with the new version number using `git tag`. It then builds the gem package using `bundle exec rake build`, creating a `.gem` file in the `pkg/` directory. ```bash ! git tag {NEW_VERSION} ``` ```bash ! BUNDLE_GEMFILE=gemfiles/{GEMFILE} bundle exec rake build ``` -------------------------------- ### Generate GitHub Release Information (Python) Source: https://github.com/apipie/apipie-rails/blob/master/rel-eng/gem_release.ipynb Prints the formatted changelog entries and a URL for creating a new GitHub release. This helps in manually creating the release on GitHub by providing the necessary title and description content. ```python print('\n') print('\n'.join(change_log)) print('\n\nhttps://github.com/Apipie/apipie-rails/releases/new?tag=%s' % NEW_VERSION) ``` -------------------------------- ### Define API Parameter with Type Validation (String, Hash) Source: https://github.com/apipie/apipie-rails/blob/master/README.md Shows how to define API parameters using the `param` helper with type validation. This example defines a required string parameter `session` and an optional hash parameter `facts`. ```ruby param :session, String, :desc => "user is logged in", :required => true param :facts, Hash, :desc => "Additional optional facts about the user" ``` -------------------------------- ### Product Management API Source: https://context7.com/apipie/apipie-rails/llms.txt Provides complete CRUD operations for product catalog management. All endpoints require valid API key authentication. ```APIDOC ## GET /products ### Description List all products with pagination. ### Method GET ### Endpoint /products ### Parameters #### Query Parameters - **page** (Integer) - Optional - Page number, defaults to 1 - **per_page** (Integer) - Optional - Items per page, defaults to 25 - **category** (String) - Optional - Filter by category ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **array_of_product** (array) - Description of the product array #### Response Example ```json { "example": "[ { \"id\": 1, \"name\": \"Example Product\", \"price\": 100.00 } ]" } ``` ``` -------------------------------- ### Extend API Documentation with Apipie::DSL::Concern Source: https://github.com/apipie/apipie-rails/blob/master/README.md Demonstrates using `Apipie::DSL::Concern` to modularize API documentation across different controllers. It shows how to define API routes, parameters, and descriptions within a module and include them in controllers, with support for substitutions. ```ruby # users_module.rb module UsersModule extend Apipie::DSL::Concern api :GET, '/:controller_path', 'List :resource_id' def index # ... end api! 'Show a :resource' def show # ... end api :POST, '/:resource_id', "Create a :resource" param :concern, Hash, :required => true param :name, String, 'Name of a :resource' param :resource_type, ['standard','vip'] end def create # ... end api :GET, '/:resource_id/:custom_subst' def custom # ... end end # users_controller.rb class UsersController < ApplicationController resource_description { resource_id 'customers' } apipie_concern_subst(:custom_subst => 'custom', :resource => 'customer') include UsersModule # the following paths are documented # api :GET, '/users' # api :GET, '/customers/:id', 'Show a customer' # api :POST, '/customers', 'Create a customer' # param :customer, :required => true do # param :name, String, 'Name of a customer' # param :customer_type, ['standard', 'vip'] # end # api :GET, '/customers/:custom' end ```