{"id":23712279,"url":"https://github.com/powermobileweb/apipie-rails","last_synced_at":"2025-07-07T16:32:08.272Z","repository":{"id":269077675,"uuid":"168812941","full_name":"powermobileweb/apipie-rails","owner":"powermobileweb","description":"Ruby on Rails API documentation tool","archived":false,"fork":false,"pushed_at":"2019-03-07T22:45:43.000Z","size":385,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-04T19:22:22.026Z","etag":null,"topics":["apipie","ruby","ruby-on-rails"],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/powermobileweb.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-02T08:52:52.000Z","updated_at":"2021-08-30T13:43:12.000Z","dependencies_parsed_at":"2024-12-20T18:54:22.841Z","dependency_job_id":"357693ca-8ed0-4e0e-9f69-82902794f7ef","html_url":"https://github.com/powermobileweb/apipie-rails","commit_stats":null,"previous_names":["powermobileweb/apipie-rails"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/powermobileweb/apipie-rails","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/powermobileweb%2Fapipie-rails","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/powermobileweb%2Fapipie-rails/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/powermobileweb%2Fapipie-rails/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/powermobileweb%2Fapipie-rails/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/powermobileweb","download_url":"https://codeload.github.com/powermobileweb/apipie-rails/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/powermobileweb%2Fapipie-rails/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":264113255,"owners_count":23559337,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apipie","ruby","ruby-on-rails"],"created_at":"2024-12-30T19:58:13.129Z","updated_at":"2025-07-07T16:32:08.117Z","avatar_url":"https://github.com/powermobileweb.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"========================\n API Documentation Tool\n========================\n\n.. image:: https://travis-ci.org/Apipie/apipie-rails.svg?branch=master\n    :target: https://travis-ci.org/Apipie/apipie-rails\n.. image:: https://codeclimate.com/github/Apipie/apipie-rails.svg\n    :target: https://codeclimate.com/github/Apipie/apipie-rails\n.. image:: https://badges.gitter.im/Apipie/apipie-rails.svg\n   :alt: Join the chat at https://gitter.im/Apipie/apipie-rails\n   :target: https://gitter.im/Apipie/apipie-rails?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge\n.. image:: https://img.shields.io/gem/v/apipie-rails.svg\n   :alt: Latest release\n   :target: https://rubygems.org/gems/apipie-rails\n\nApipie-rails is a DSL and Rails engine for documenting your RESTful\nAPI. Instead of traditional use of ``#comments``, Apipie lets you\ndescribe the code, through the code. This brings advantages like:\n\n* No need to learn yet another syntax, you already know Ruby, right?\n* Possibility of reusing the docs for other purposes (such as validation)\n* Easier to extend and maintain (no string parsing involved)\n* Possibility of reusing other sources for documentation purposes (such as\n  routes etc.)\n\nThe documentation is available from within your app (by default under the\n``/apipie`` path.) In development mode, you can see the changes as you\ngo. It's markup language agnostic, and even provides an API for reusing\nthe documentation data in JSON.\n\nGetting started\n---------------\n\nThe easiest way to get Apipie up and running with your app is:\n\n.. code:: sh\n\n   echo \"gem 'apipie-rails'\" \u003e\u003e Gemfile\n   bundle install\n   rails g apipie:install\n\nNow you can start documenting your resources and actions (see\n`DSL Reference`_ for more info):\n\n.. code:: ruby\n\n   api :GET, '/users/:id'\n   param :id, :number, desc: 'id of the requested user'\n   def show\n     # ...\n   end\n\n\nRun your application and see the result at\n``http://localhost:3000/apipie``. For further processing, you can\nuse ``http://localhost:3000/apipie.json``.\n\nFor a more comprehensive getting started guide, see\n`this demo \u003chttps://github.com/iNecas/apipie-demo\u003e`_, which includes\nfeatures such as generating documentation from tests, recording examples etc.\n\nScreenshots\n-----------\n\n.. image:: https://github.com/Apipie/apipie-rails/blob/master/images/screenshot-1.png\n.. image:: https://github.com/Apipie/apipie-rails/blob/master/images/screenshot-2.png\n\nAuthors\n-------\n\n`Pajk \u003chttps://github.com/Pajk\u003e`_ and `iNecas \u003chttps://github.com/iNecas\u003e`_\n\nContributors\n------------\n\nSee `Contributors page  \u003chttps://github.com/Apipie/apipie-rails/graphs/contributors\u003e`_. Special thanks to all of them!\n\nLicense\n-------\n\nApipie-rails is released under the `MIT License \u003chttp://opensource.org/licenses/MIT\u003e`_\n\n===============\n Documentation\n===============\n\n.. contents:: `Table Of Contents`\n  :depth: 2\n\n===============\n DSL Reference\n===============\n\nResource Description\n--------------------\n\nYou can describe a resource on the controller level. The description is introduced by calling\n``resource_description do ... end``.\n\nInheritance is supported, so you can specify common params for group of controllers in their parent\nclass.\n\nThe following keywords are available (all are optional):\n\nresource_id\n  How the resource will be referenced in Apipie (paths, ``see`` command etc.); by default `controller_name.downcase` is used.\n\nname\n  Human readable name of resource. By default ``class.name.humanize`` is used.\n\nshort (also short_description)\n  Short description of the resource (it's shown on both the list of resources, and resource details)\n\ndesc (also description and full_description)\n  Full description of the resource (shown only in resource details)\n\nparam\n  Common params for all methods defined in controller/child controllers.\n\nreturns\n  Common responses for all methods defined in controller/child controllers.\n\napi_base_url\n  What URL is the resource available under.\n\napi_versions (also api_version)\n  What versions does the controller define the resource. (See `Versioning`_ for details.)\n\nformats\n  Request / response formats.\n\nerror\n  Describe every possible error that can happen when calling all\n  methods defined in controller. HTTP response code and description can be provided.\n\napp_info\n  In case of versioning, this sets app info description on a per_version basis.\n\nmeta\n  Hash or array with custom metadata.\n\ndeprecated\n  Boolean value indicating if the resource is marked as deprecated. (Default false)\n\nExample:\n~~~~~~~~\n\n.. code:: ruby\n\n   resource_description do\n     short 'Site members'\n     formats ['json']\n     param :id, Fixnum, :desc =\u003e \"User ID\", :required =\u003e false\n     param :resource_param, Hash, :desc =\u003e 'Param description for all methods' do\n       param :ausername, String, :desc =\u003e \"Username for login\", :required =\u003e true\n       param :apassword, String, :desc =\u003e \"Password for login\", :required =\u003e true\n     end\n     api_version \"development\"\n     error 404, \"Missing\"\n     error 500, \"Server crashed for some \u003c%= reason %\u003e\", :meta =\u003e {:anything =\u003e \"you can think of\"}\n     error :unprocessable_entity, \"Could not save the entity.\"\n     returns :code =\u003e 403 do\n        property :reason, String, :desc =\u003e \"Why this was forbidden\"\n     end\n     meta :author =\u003e {:name =\u003e 'John', :surname =\u003e 'Doe'}\n     deprecated false\n     description \u003c\u003c-EOS\n       == Long description\n        Example resource for rest api documentation\n        These can now be accessed in \u003ctt\u003eshared/header\u003c/tt\u003e with:\n          Headline: \u003c%= headline %\u003e\n          First name: \u003c%= person.first_name %\u003e\n\n        If you need to find out whether a certain local variable has been\n        assigned a value in a particular render call, you need to use the\n        following pattern:\n\n        \u003c% if local_assigns.has_key? :headline %\u003e\n           Headline: \u003c%= headline %\u003e\n        \u003c% end %\u003e\n\n       Testing using \u003ctt\u003edefined? headline\u003c/tt\u003e will not work. This is an\n       implementation restriction.\n\n       === Template caching\n\n       By default, Rails will compile each template to a method in order\n       to render it. When you alter a template, Rails will check the\n       file's modification time and recompile it in development mode.\n     EOS\n   end\n\n\nMethod Description\n------------------\n\nThen describe methods available to your API.\n\napi\n  Describe how this method is exposed, and provide a short description.\n  The first parameter is HTTP method (one of :GET/:POST/:PUT/:DELETE).\n  The second parameter is the relative URL path which is mapped to this\n  method. The last parameter is the methods short description.\n  You can use this +api+ method more than once per method. It could\n  be useful when there are more routes mapped to it.\n\n  When providing just one argument (description), or no argument at all,\n  the paths will be loaded from the routes.rb file.\n\napi!\n  Provide a short description and additional option.\n  The last parameter is the methods short description.\n  The paths will be loaded from routes.rb file. See\n  `Rails Routes Integration`_ for more details.\n\napi_versions (also api_version)\n  What version(s) does the action belong to. (See `Versioning`_ for details.)\n\nparam\n  Look at `Parameter description`_ section for details.\n\nreturns\n  Look at `Response description`_ section for details.\n\ntags\n  Adds tags for grouping operations together in Swagger outputs. See `swagger`_\n  for more details. You can also provide tags in the `Resource Description`_\n  block so that they are automatically prepended to all action tags in the\n  controller.\n\nformats\n  Method level request / response formats.\n\nerror\n  Describe each possible error that can happen while calling this\n  method. HTTP response code and description can be provided.\n\ndescription\n  Full method description, which will be converted into HTML by the\n  chosen markup language processor.\n\nexample\n  Provide an example of the server response; whole communication or response type.\n  It will be formatted as code.\n\nsee\n  Provide reference to another method, this has to be a string with\n  controller_name#method_name.\n\nmeta\n  Hash or array with custom metadata.\n\nshow\n  Resource is hidden from documentation when set to false (true by default)\n\nExample:\n~~~~~~~~\n\n.. code:: ruby\n\n   # The simplest case: just load the paths from routes.rb\n   api!\n   def index\n   end\n\n   # More complex example\n   api :GET, \"/users/:id\", \"Show user profile\"\n   show false\n   error :code =\u003e 401, :desc =\u003e \"Unauthorized\"\n   error :code =\u003e 404, :desc =\u003e \"Not Found\", :meta =\u003e {:anything =\u003e \"you can think of\"}\n   param :session, String, :desc =\u003e \"user is logged in\", :required =\u003e true\n   param :regexp_param, /^[0-9]* years/, :desc =\u003e \"regexp param\"\n   param :array_param, [100, \"one\", \"two\", 1, 2], :desc =\u003e \"array validator\"\n   param :boolean_param, [true, false], :desc =\u003e \"array validator with boolean\"\n   param :proc_param, lambda { |val|\n     val == \"param value\" ? true : \"The only good value is 'param value'.\"\n   }, :desc =\u003e \"proc validator\"\n   param :param_with_metadata, String, :desc =\u003e \"\", :meta =\u003e [:your, :custom, :metadata]\n   returns :code =\u003e 200, :desc =\u003e \"a successful response\" do\n      property :value1, String, :desc =\u003e \"A string value\"\n      property :value2, Integer, :desc =\u003e \"An integer value\"\n      property :value3, Hash, :desc =\u003e \"An object\" do\n        property :enum1, ['v1', 'v2'], :desc =\u003e \"One of 2 possible string values\"\n      end\n   end\n   tags %w[profiles logins]\n   tags 'more', 'related', 'resources'\n   description \"method description\"\n   formats ['json', 'jsonp', 'xml']\n   meta :message =\u003e \"Some very important info\"\n   example \" 'user': {...} \"\n   see \"users#showme\", \"link description\"\n   see :link =\u003e \"users#update\", :desc =\u003e \"another link description\"\n   def show\n     #...\n   end\n\nParameter Description\n---------------------\n\nUse ``param`` to describe every possible parameter. You can use the Hash validator\nin conjunction with a block given to the param method to describe nested parameters.\n\nname\n  The first argument is the parameter name as a symbol.\n\nvalidator\n  Second parameter is the parameter validator, choose one from section `Validators`_\n\ndesc\n  Parameter description.\n\nrequired\n  Set this true/false to make it required/optional. Default is optional\n\nallow_nil\n  Setting this to true means that ``nil`` can be passed.\n\nallow_blank\n  Like ``allow_nil``, but for blank values. ``false``, ``\"\"``, ``' '``, ``nil``, ``[]``, and ``{}`` are all blank.\n\nas\n  Used by the processing functionality to change the name of a key params.\n\nmeta\n  Hash or array with custom metadata.\n\nshow\n  Parameter is hidden from documentation when set to false (true by default)\n\nmissing_message\n  Specify the message to be returned if the parameter is missing as a string or Proc.\n  Defaults to ``Missing parameter #{name}`` if not specified.\n\nonly_in\n   This can be set to ``:request`` or ``:response``.\n   Setting to ``:response`` causes the param to be ignored when used as part of a request description.\n   Setting to ``:request`` causes this param to be ignored when used as part of a response description.\n   If ``only_in`` is not specified, the param definition is used for both requests and responses.\n   (Note that the keyword ``property`` is similar to ``param``, but it has a ``:only_in =\u003e :response`` default).\n\nExample:\n~~~~~~~~\n\n.. code:: ruby\n\n   param :user, Hash, :desc =\u003e \"User info\" do\n     param :username, String, :desc =\u003e \"Username for login\", :required =\u003e true\n     param :password, String, :desc =\u003e \"Password for login\", :required =\u003e true\n     param :membership, [\"standard\",\"premium\"], :desc =\u003e \"User membership\"\n     param :admin_override, String, :desc =\u003e \"Not shown in documentation\", :show =\u003e false\n     param :ip_address, String, :desc =\u003e \"IP address\", :required =\u003e true, :missing_message =\u003e lambda { I18n.t(\"ip_address.required\") }\n   end\n   def create\n     #...\n   end\n\nDRY with param_group\n--------------------\n\nOften, params occur together in more actions. Typically, most of the\nparams for ``create`` and ``update`` actions are shared between them.\n\nThese params can be extracted with ``def_param_group`` and\n``param_group`` keywords.\n\nThe definition is looked up in the scope of the controller. If the\ngroup is defined in a different controller, it might be referenced by\nspecifying the second argument.\n\nExample:\n~~~~~~~~\n\n.. code:: ruby\n\n   # v1/users_controller.rb\n   def_param_group :address do\n     param :street, String\n     param :number, Integer\n     param :zip, String\n   end\n\n   def_param_group :user do\n     param :user, Hash do\n       param :name, String, \"Name of the user\"\n       param_group :address\n     end\n   end\n\n   api :POST, \"/users\", \"Create an user\"\n   param_group :user\n   def create\n     # ...\n   end\n\n   api :PUT, \"/users/:id\", \"Update an user\"\n   param_group :user\n   def update\n     # ...\n   end\n\n   # v2/users_controller.rb\n   api :POST, \"/users\", \"Create an user\"\n   param_group :user, V1::UsersController\n   def create\n     # ...\n   end\n\nAction Aware params\n-------------------\n\nIn CRUD operations, this pattern occurs quite often - params that need\nto be set are:\n\n* for create action: ``required =\u003e true`` and ``allow_nil =\u003e false``\n* for update action: ``required =\u003e false`` and ``allow_nil =\u003e false``\n\nThis makes it hard to share the param definitions across theses\nactions. Therefore, you can make the description a bit smarter by\nsetting ``:action_aware =\u003e true``.\n\nYou can specify explicitly how the param group should be evaluated\nwith ``:as`` option (either :create  or :update)\n\nExample\n~~~~~~~\n\n.. code:: ruby\n\n   def_param_group :user do\n     param :user, Hash, :action_aware =\u003e true do\n       param :name, String, :required =\u003e true\n       param :description, String\n     end\n   end\n\n   api :POST, \"/users\", \"Create an user\"\n   param_group :user\n   def create\n     # ...\n   end\n\n   api :PUT, \"/users/admin\", \"Create an admin\"\n   param_group :user, :as =\u003e :create\n   def create_admin\n     # ...\n   end\n\n   api :PUT, \"/users/:id\", \"Update an user\"\n   param_group :user\n   def update\n     # ...\n   end\n\nIn this case, ``user[name]`` will be not be allowed nil for all\nactions and required only for ``create`` and ``create_admin``. Params\nwith ``allow_nil`` set explicitly don't have this value changed.\n\nAction awareness is inherited from ancestors (in terms of\nnested params).\n\n\nResponse Description\n--------------------\n\nThe response from an API call can be documented by adding a ``returns`` statement to the method\ndescription.  This is especially useful when using Apipie to auto-generate a machine-readable Swagger\ndefinition of your API (see the `swagger`_ section for more details).\n\nA ``returns`` statement has several possible formats:\n\n.. code:: ruby\n\n    # format #1:  reference to a param-group\n    returns \u003cparam-group-name\u003e [, :code =\u003e \u003cnumber\u003e|\u003chttp-response-code-symbol\u003e] [, :desc =\u003e \u003chuman-readable description\u003e]\n\n    # format #2:  inline response definition\n    returns :code =\u003e \u003cnumber\u003e|\u003chttp-response-code-symbol\u003e [, :desc =\u003e \u003chuman-readable description\u003e] do\n        # property ...\n        # property ...\n        # param_group ...\n    end\n\n    # format #3:  describing an array-of-objects response\n    returns :array_of =\u003e \u003cparam-group-name\u003e [, :code =\u003e \u003cnumber\u003e|\u003chttp-response-code-symbol\u003e] [, :desc =\u003e \u003chuman-readable description\u003e]\n\n\nIf the ``:code`` argument is ommitted, ``200`` is used.\n\n\nExample\n~~~~~~~\n\n.. code:: ruby\n\n  # ------------------------------------------------\n  # Example of format #1 (reference to param-group):\n  # ------------------------------------------------\n  # the param_group :pet is defined here to describe the output returned by the method below.\n  def_param_group :pet do\n    property :pet_name, String, :desc =\u003e \"Name of pet\"\n    property :animal_type, ['dog','cat','iguana','kangaroo'], :desc =\u003e \"Type of pet\"\n  end\n\n  api :GET, \"/pets/:id\", \"Get a pet record\"\n  returns :pet, :desc =\u003e \"The pet\"\n  def show_detailed\n    render JSON({:pet_name =\u003e \"Skippie\", :animal_type =\u003e \"kangaroo\"})\n  end\n\n  # ------------------------------------------------\n  # Example of format #2 (inline):\n  # ------------------------------------------------\n  api :GET, \"/pets/:id/with-extra-details\", \"Get a detailed pet record\"\n  returns :code =\u003e 200, :desc =\u003e \"Detailed info about the pet\" do\n    param_group :pet\n    property :num_legs, Integer, :desc =\u003e \"How many legs the pet has\"\n  end\n  def show\n    render JSON({:pet_name =\u003e \"Barkie\", :animal_type =\u003e \"iguana\", :legs =\u003e 4})\n  end\n\n  # ------------------------------------------------\n  # Example of format #3 (array response):\n  # ------------------------------------------------\n  api :GET, \"/pets\", \"Get all pet records\"\n  returns :array_of =\u003e :pet, :code =\u003e 200, :desc =\u003e \"All pets\"\n  def index\n    render JSON([ {:pet_name =\u003e \"Skippie\", :animal_type =\u003e \"kangaroo\"},\n                  {:pet_name =\u003e \"Woofie\", :animal_type =\u003e \"cat\"} ])\n  end\n\n\nNote the use of the ``property`` keyword rather than ``param``.  This is the\npreferred mechanism for documenting response-only fields.\n\n\nThe Property keyword\n::::::::::::::::::::::::::::::::::::::::::::::::\n\n``property`` is very similar to ``param`` with the following differences:\n\n* a ``property`` is ``:only_in =\u003e :response`` by default\n\n* a ``property`` is ``:required =\u003e :true`` by default\n\n* a ``property`` can be an ``:array_of`` objects\n\nExample\n_______\n.. code:: ruby\n\n    property :example, :array_of =\u003e Hash do\n      property :number1, Integer\n      property :number2, Integer\n    end\n\n\nDescribing multiple return codes\n::::::::::::::::::::::::::::::::::::::::::::::::\n\nTo describe multiple possible return codes, the ``:returns`` keyword can be repeated as many times as necessary\n(once for each return code).  Each one of the ``:returns`` entries can specify a different response format.\n\nExample\n_______\n\n.. code:: ruby\n\n    api :GET, \"/pets/:id/extra_info\", \"Get extra information about a pet\"\n      returns :desc =\u003e \"Found a pet\" do\n        param_group :pet\n        property 'pet_history', Hash do\n          param_group :pet_history\n        end\n      end\n      returns :code =\u003e :unprocessable_entity, :desc =\u003e \"Fleas were discovered on the pet\" do\n        param_group :pet\n        property :num_fleas, Integer, :desc =\u003e \"Number of fleas on this pet\"\n      end\n      def show_extra_info\n        # ... implementation here\n      end\n\n\n\nReusing a param_group to describe inputs and outputs\n::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nIn many cases (such as CRUD implementations), the output from certain API calls is very similar - but not\nidentical - to the inputs of the same or other API calls.\n\nIf you already have a ``:param_group`` that defines the input to a `create` or `update` routine, it would be quite\nfrustrating to have to define a completely separate ``:param_group`` to describe the output of the `show` routine.\n\nTo address such situations, it is possible to define a single ``:param_group`` which combines ``param`` and ``property``\nstatements (as well as ``:only_in =\u003e :request`` / ``:only_in =\u003e :response``) to differentiate between fields that are\nonly expected in the request, only included in the response, or common to both.\n\nThis is somewhat analogous to the way `Action Aware params`_ work.\n\nExample\n_______\n\n.. code:: ruby\n\n    def_param_group :user_record\n        param :name, String                                         # this is commong to both the request and the response\n        param :force_update, [true, false], :only_in =\u003e :request    # this does not show up in responses\n        property :last_login, String                                # this shows up only in the response\n    end\n\n   api :POST, \"/users\", \"Create a user\"\n   param_group :user_record  # the :last_login field is not expected here, but :force_update is\n   def create\n     # ...\n   end\n\n   api :GET, \"/users\", \"Create a user\"\n   returns :array_of =\u003e :user_record  # the :last_login field will be included in the response, but :force_update will not\n   def index\n     # ...\n   end\n\n\nEmbedded response descriptions\n::::::::::::::::::::::::::::::\n\nIf the code creating JSON responses is encapsulated within dedicated classes, it can be more convenient to\nplace the response descriptions outside of the controller and embed them within the response generator.\n\nTo support such use cases, Apipie allows any class to provide a `describe_own_properties` class method which\nreturns a description of the properties such a class would expose.  It is then possible to specify that\nclass in the `returns` statement instead of a `param_group`.\n\nThe `describe_own_properties` method is expected to return an array of `Apipie::prop` objects, each one\ndescribing a single property.\n\nExample\n_______\n\n.. code:: ruby\n\n    class Pet\n      # this method is automatically called by Apipie when Pet is specified as the returned object type\n      def self.describe_own_properties\n        [\n            Apipie::prop(:pet_name, 'string', {:description =\u003e 'Name of pet', :required =\u003e false}),\n            Apipie::prop(:animal_type, 'string', {:description =\u003e 'Type of pet', :values =\u003e [\"dog\", \"cat\", \"iguana\", \"kangaroo\"]}),\n            Apipie::additional_properties(false)  # this indicates that :pet_name and :animal_type are the only properties in the response\n        ]\n      end\n\n      # this method w\n      def json\n        JSON({:pet_name =\u003e @name, :animal_type =\u003e @type })\n      end\n    end\n\n\n    class PetsController\n        api :GET, \"/index\", \"Get all pets\"\n        returns :array_of =\u003e Pet  # Pet is a 'self-describing-class'\n        def index\n         # ...\n        end\n    end\n\n\nA use case where this is very useful is when JSON generation is done using a reflection mechanism or some\nother sort of declarative mechanism.\n\n\n\n\nThe `Apipie::prop` function expects the following inputs:\n\n.. code:: ruby\n\n    Apipie::prop(\u003cproperty-name\u003e, \u003cproperty-type\u003e, \u003coptions-hash\u003e [, \u003carray of sub-properties\u003e])\n\n    # property-name should be a symbol\n    #\n    # property-type can be any of the following strings:\n    #   \"integer\": maps to a swagger \"integer\" with an \"int32\" format\n    #   \"long\": maps to a swagger \"integer\" with an \"int64\" format\n    #   \"number\": maps to a swagger \"number\"(no format specifier)\n    #   \"float\": maps to a swagger \"number\" with a \"float\" format\n    #   \"double\": maps to a swagger \"number\" with a \"double\" format\n    #   \"string\": maps to a swagger \"string\" (no format specifier)\n    #   \"byte\": maps to a swagger \"string\" with a \"byte\" format\n    #   \"binary\": maps to a swagger \"string\" with a \"binary\" format\n    #   \"boolean\": maps to a swagger \"boolean\" (no format specifier)\n    #   \"date\": maps to a swagger \"string\" with a \"date\" format\n    #   \"dateTime\": maps to a swagger \"string\" with a \"date-time\" format\n    #   \"password\": maps to a swagger \"string\" with a \"password\" format\n    #   \"object\": the property has sub-properties. include \u003carray of sub-properties\u003e in the call.\n    # (see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more information\n    # about the mapped swagger types)\n    #\n    # options-hash can include any of the options fields allowed in a :returns statement.\n    # additionally, it can include the ':is_array =\u003e true', in which case the property is understood to be\n    # an array of the described type.\n\n\n\nTo describe an embedded object:\n\n.. code:: ruby\n\n\n    #\n    # PetWithMeasurements is a self-describing class with an embedded object\n    #\n    class PetWithMeasurements\n      def self.describe_own_properties\n        [\n            Apipie::prop(:pet_name, 'string', {:description =\u003e 'Name of pet', :required =\u003e false}),\n            Apipie::prop('animal_type', 'string', {:description =\u003e 'Type of pet', :values =\u003e [\"dog\", \"cat\", \"iguana\", \"kangaroo\"]}),\n            Apipie::prop(:pet_measurements, 'object', {}, [\n                Apipie::prop(:weight, 'number', {:description =\u003e \"Weight in pounds\" }),\n                Apipie::prop(:height, 'number', {:description =\u003e \"Height in inches\" }),\n                Apipie::prop(:num_legs, 'number', {:description =\u003e \"Number of legs\", :required =\u003e false }),\n                Apipie::additional_properties(false)\n            ])\n        ]\n      end\n    end\n\n    #\n    # PetWithManyMeasurements is a self-describing class with an embedded array of objects\n    #\n    class PetWithManyMeasurements\n      def self.describe_own_properties\n        [\n            Apipie::prop(:pet_name, 'string', {:description =\u003e 'Name of pet', :required =\u003e false}),\n            Apipie::prop(:many_pet_measurements, 'object', {is_array: true}, [\n                Apipie::prop(:weight, 'number', {:description =\u003e \"Weight in pounds\" }),\n                Apipie::prop(:height, 'number', {:description =\u003e \"Height in inches\" }),\n            ])\n        ]\n      end\n    end\n\n\n\nConcerns\n--------\n\nSometimes, the actions are not defined in the controller class\ndirectly but included from a module instead. You can load the Apipie\nDSL into the module by extending it with ``Apipie::DSL::Concern``.\n\nThe module can be used in more controllers. Therefore there is a way to\nsubstitute parts of the documentation in the module with controller\nspecific values. These substitutions can be stated explicitly with\n``apipie_concern_subst(:key =\u003e \"value\")`` (needs to be called before\nthe module is included to take effect). The substitutions are\nperformed in the paths and descriptions of APIs and names and descriptions\nof params.\n\nThere are some default substitutions available:\n\n:controller_path\n  value of ``controller.controller_path``, e.g. ``api/users`` for\n  ``Api::UsersController``. Only if not using the ``api!`` keyword.\n\n:resource_id\n  Apipie identifier of the resource, e.g. ``users`` for\n  ``Api::UsersController`` or set by ``resource_id``\n\nExample\n~~~~~~~\n\n.. code:: ruby\n\n   # users_module.rb\n   module UsersModule\n     extend Apipie::DSL::Concern\n\n     api :GET, '/:controller_path', 'List :resource_id'\n     def index\n       # ...\n     end\n\n     api! 'Show a :resource'\n     def show\n       # ...\n     end\n\n     api :POST, '/:resource_id', \"Create a :resource\"\n     param :concern, Hash, :required =\u003e true\n       param :name, String, 'Name of a :resource'\n       param :resource_type, ['standard','vip']\n     end\n     def create\n       # ...\n     end\n\n     api :GET, '/:resource_id/:custom_subst'\n     def custom\n       # ...\n     end\n   end\n\n   # users_controller.rb\n   class UsersController \u003c ApplicationController\n\n     resource_description { resource_id 'customers' }\n\n     apipie_concern_subst(:custom_subst =\u003e 'custom', :resource =\u003e 'customer')\n     include UsersModule\n\n     # the following paths are documented\n     # api :GET, '/users'\n     # api :GET, '/customers/:id', 'Show a customer'\n     # api :POST, '/customers', 'Create a customer'\n     #   param :customer, :required =\u003e true do\n     #     param :name, String, 'Name of a customer'\n     #     param :customer_type, ['standard', 'vip']\n     #   end\n     # api :GET, '/customers/:custom'\n   end\n\n\nSometimes, it's needed to extend an existing controller method with additional\nparameters (usually when extending exiting API from plugins/rails engines).\nThe concern can be also used for this purposed, using `update_api` method.\nThe params defined in this block are merged with the params of the original method\nin the controller this concern is included to.\n\nExample\n~~~~~~~\n\n.. code:: ruby\n\n   module Concerns\n     module OauthConcern\n       extend Apipie::DSL::Concern\n\n       update_api(:create, :update) do\n         param :user, Hash do\n           param :oauth, String, :desc =\u003e 'oauth param'\n         end\n       end\n     end\n   end\n\nThe concern needs to be included to the controller after the methods are defined\n(either at the end of the class, or by using\n``Controller.send(:include, Concerns::OauthConcern)``.\n\n\nResponse validation\n-------------------\n\nThe swagger definitions created by Apipie can be used to auto-generate clients that access the\ndescribed APIs.  Those clients will break if the responses returned from the API do not match\nthe declarations.  As such, it is very important to include unit tests that validate the actual\nresponses against the swagger definitions.\n\nThe implemented mechanism provides two ways to include such validations in RSpec unit tests:\nmanual (using an RSpec matcher) and automated (by injecting a test into the http operations 'get', 'post',\nraising an error if there is no match).\n\nExample of the manual mechanism:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: ruby\n\n  require 'apipie/rspec/response_validation_helper'\n\n  RSpec.describe MyController, :type =\u003e :controller, :show_in_doc =\u003e true do\n\n    describe \"GET stuff with response validation\" do\n      render_views   # this makes sure the 'get' operation will actually\n                     # return the rendered view even though this is a Controller spec\n\n      it \"does something\" do\n        response = get :index, {format: :json}\n\n        # the following expectation will fail if the returned object\n        # does not match the 'returns' declaration in the Controller,\n        # or if there is no 'returns' declaration for the returned\n        # HTTP status code\n        expect(response).to match_declared_responses\n      end\n    end\n  end\n\n\nExample of the automated mechanism:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: ruby\n\n  require 'apipie/rspec/response_validation_helper'\n\n  RSpec.describe MyController, :type =\u003e :controller, :show_in_doc =\u003e true do\n\n    describe \"GET stuff with response validation\" do\n      render_views\n      auto_validate_rendered_views\n\n      it \"does something\" do\n        get :index, {format: :json}\n      end\n      it \"does something else\" do\n        get :another_index, {format: :json}\n      end\n    end\n\n    describe \"GET stuff without response validation\" do\n      it \"does something\" do\n        get :index, {format: :json}\n      end\n      it \"does something else\" do\n        get :another_index, {format: :json}\n      end\n    end\n  end\n\n\n=========================\n Configuration Reference\n=========================\n\nCreate a configuration file in e.g. ``/config/initializers/apipie.rb``.\nYou can set the application name, footer text, API and documentation base URL\nand turn off validations. You can also choose your favorite markup language\nfor full descriptions.\n\napp_name\n  Name of your application; used in breadcrumbs navigation.\n\ncopyright\n  Copyright information (shown in page footer).\n\ncompress_examples\n  If ``true`` recorded examples are compressed using ``Zlib``. Useful for big test-suits.\n\ndoc_base_url\n  Documentation frontend base url.\n\napi_base_url\n  Base url for default version of your API. To set it for specific version use ``config.api_base_url[version] = url``.\n\ndefault_version\n  Default API version to be used (1.0 by default)\n\nvalidate\n  Parameters validation is turned off when set to false. When set to\n  ``:explicitly``, you must invoke parameter validation yourself by calling\n  controller method ``apipie_validations`` (typically in a before_action).\n  When set to ``:implicitly`` (or just true), your controller's action\n  methods are wrapped with generated methods which call ``apipie_validations``,\n  and then call the action method. (``:implicitly`` by default)\n\nvalidate_value\n  Check the value of params against specified validators (true by\n  default)\n\nvalidate_presence\n  Check the params presence against the documentation.\n\nvalidate_key\n  Check the received params to ensure they are defined in the API. (false by default)\n\nprocess_params\n  Process and extract the parameter defined from the params of the request\n  to the api_params variable\n\napp_info\n  Application long description.\n\nreload_controllers\n  Set to enable/disable reloading controllers (and the documentation with it). Enabled by default in development.\n\napi_controllers_matcher\n  For reloading to work properly you need to specify where your API controllers are. Can be an array if multiple paths are needed\n\napi_routes\n  Set if your application uses a custom API router, different from the Rails\n  default\n\nroutes_formatter\n  An object providing the translation from the Rails routes to the\n  format usable in the documentation when using the `api!` keyword. By\n  default, the ``Apipie::RoutesFormatter`` is used.\n\nmarkup\n  You can choose markup language for descriptions of your application,\n  resources and methods. RDoc is the default but you can choose from\n  Apipie::Markup::Markdown.new or Apipie::Markup::Textile.new.\n  In order to use Markdown you need Maruku gem and for Textile you\n  need RedCloth. Add those to your gemfile and run bundle if you\n  want to use them. You can also add any other markup language\n  processor.\n\nlayout\n  Name of a layout template to use instead of Apipie's layout. You can use\n  Apipie.include_stylesheets and Apipie.include_javascripts helpers to include\n  Apipie's stylesheets and javascripts.\n\nignored\n  An array of controller names (strings) (might include actions as well)\n  to be ignored when generationg the documentation\n  e.g. ``%w[Api::CommentsController Api::PostsController#post]``\n\nnamespaced_resources\n  Use controller paths instead of controller names as resource id.\n  This prevents same named controllers overwriting each other.\n\nauthenticate\n  Pass a proc in order to authenticate user. Pass nil for\n  no authentication (by default).\n\nauthorize\n  Pass a proc in order to authorize controllers and methods. The Proc is evaluated in the controller context.\n\nshow_all_examples\n  Set this to true to set show_in_doc=1 in all recorded examples\n\nlink_extension\n  The extension to use for API pages ('.html' by default). Link extensions\n  in static API docs cannot be changed from '.html'.\n\nlanguages\n  List of languages the API documentation should be translated into. Empty by default.\n\ndefault_locale\n  Locale used for generating documentation when no specific locale is set.\n  Set to 'en' by default.\n\nlocale\n  Pass locale setter/getter\n\n.. code:: ruby\n\n    config.locale = lambda { |loc| loc ? FastGettext.set_locale(loc) : FastGettext.locale }\n\ntranslate\n  Pass proc to translate strings using the localization library your project uses.\n  For example see `Localization`_\n\nExample:\n\n.. code:: ruby\n\n   Apipie.configure do |config|\n     config.app_name = \"Test app\"\n     config.copyright = \"\u0026copy; 2012 Pavel Pokorny\"\n     config.doc_base_url = \"/apidoc\"\n     config.api_base_url = \"/api\"\n     config.validate = false\n     config.markup = Apipie::Markup::Markdown.new\n     config.reload_controllers = Rails.env.development?\n     config.api_controllers_matcher = File.join(Rails.root, \"app\", \"controllers\", \"**\",\"*.rb\")\n     config.api_routes = Rails.application.routes\n     config.app_info[\"1.0\"] = \"\n       This is where you can inform user about your application and API\n       in general.\n     \"\n     config.authenticate = Proc.new do\n        authenticate_or_request_with_http_basic do |username, password|\n          username == \"test\" \u0026\u0026 password == \"supersecretpassword\"\n       end\n     end\n     config.authorize = Proc.new do |controller, method, doc|\n       !method   # show all controller doc, but no method docs.\n     end\n   end\n\nchecksum_path\n  Used in ChecksumInHeaders middleware (see `JSON checksums`_ for more info). It contains path prefix(es) where the header with checksum is added. If set to nil, checksum is added in headers in every response. e.g. ``%w[/api /apipie]``\n\nupdate_checksum\n  If set to true, the checksum is recalculated with every documentation_reload call\n\n========================\nRails Routes Integration\n========================\n\nApipie is able to load the information about the paths based on the\nroutes defined in the Rails application, by using the `api!` keyword\nin the DSL.\n\nIt should be usable out of box, however, one might want\nto do some customization (such as omitting some implicit parameters in\nthe path etc.). For this kind of customizations one can create a new\nformatter and pass as the ``Apipie.configuration.routes_formatter``\noption, like this:\n\n.. code:: ruby\n\n   class MyFormatter \u003c Apipie::RoutesFormatter\n     def format_path(route)\n       super.gsub(/\\(.*?\\)/, '').gsub('//','') # hide all implicit parameters\n     end\n   end\n\n   Apipie.configure do |config|\n    ...\n    config.routes_formatter = MyFormatter.new\n    ...\n   end\n\nA similar way can be used to influence things like order, or a description\nof the loaded APIs, even omitting some paths if needed.\n\n============\n Processing\n============\n\nThe goal is to extract and pre-process parameters of the request.\n\nFor example Rails, by default, transforms an empty array to nil value. Perhaps\nyou want to transform it again into an empty array. Or you\nwant to support an enumeration type (comma separated values) and\nyou want to automatically transform this string into an array.\n\nTo use it, set the ``process_params`` configuration variable to true.\n\nAlso by using ``as`` you can separate your API parameter\nnames from the names you are using inside your code.\n\nTo implement it, you just have to write a process_value\nfunction in your validator:\n\nFor an enumeration type:\n\n.. code:: ruby\n\n   def process_value(value)\n    value ? value.split(',') : []\n   end\n\n============\n Validators\n============\n\nEvery parameter needs to have an associated validator. For now there are some\nbasic validators. You can always provide your own to achieve complex\nresults.\n\nIf validations are enabled (default state) the parameters of every\nrequest are validated. If the value is wrong an +ArgumentError+ exception\nis raised and can be rescued and processed. It contains a description\nof the parameter value expectations. Validations can be turned off\nin the configuration file.\n\nParameter validation normally happens after before_actions, just before\nyour controller method is invoked. If you prefer to control when parameter\nvalidation occurs, set the configuration parameter ``validate`` to ``:explicitly``.\nYou must then call the ``apipie_validations`` method yourself, e.g.:\n\n.. code:: ruby\n\n   before_action :apipie_validations\n\nThis is useful if you have before_actions which use parameter values: just add them\nafter the ``apipie_validations`` before_action.\n\nTypeValidator\n-------------\nCheck the parameter type. Only String, Hash and Array are supported\nfor the sake of simplicity. Read more to find out how to add\nyour own validator.\n\n.. code:: ruby\n\n   param :session, String, :desc =\u003e \"user is logged in\", :required =\u003e true\n   param :facts, Hash, :desc =\u003e \"Additional optional facts about the user\"\n\n\nRegexpValidator\n---------------\nCheck parameter value against given regular expression.\n\n.. code:: ruby\n\n   param :regexp_param, /^[0-9]* years/, :desc =\u003e \"regexp param\"\n\n\nEnumValidator\n--------------\n\nCheck if parameter value is included in the given array.\n\n.. code:: ruby\n\n   param :enum_param, [100, \"one\", \"two\", 1, 2], :desc =\u003e \"enum validator\"\n\n\nProcValidator\n-------------\n\nIf you need more complex validation and you know you won't reuse it, you\ncan use the Proc/lambda validator. Provide your own Proc, taking the value\nof the parameter as the only argument. Return true if value passes validation\nor return some text about what is wrong otherwise. _Don't use the keyword *return*\nif you provide an instance of Proc (with lambda it is ok), just use the last\nstatement return property of ruby.\n\n.. code:: ruby\n\n   param :proc_param, lambda { |val|\n     val == \"param value\" ? true : \"The only good value is 'param value'.\"\n   }, :desc =\u003e \"proc validator\"\n\n\nHashValidator\n-------------\n\nYou can describe hash parameters in depth if you provide a block with a\ndescription of nested values.\n\n.. code:: ruby\n\n   param :user, Hash, :desc =\u003e \"User info\" do\n     param :username, String, :desc =\u003e \"Username for login\", :required =\u003e true\n     param :password, String, :desc =\u003e \"Password for login\", :required =\u003e true\n     param :membership, [\"standard\",\"premium\"], :desc =\u003e \"User membership\"\n   end\n\n\nNilValidator\n------------\n\nIn fact there isn't any NilValidator, but setting it to nil can be used to\noverride parameters described on the resource level.\n\n.. code:: ruby\n\n   param :user, nil\n   def destroy\n     #...\n   end\n\nNumberValidator\n---------------\n\nCheck if the parameter is a positive integer number or zero\n\n.. code:: ruby\n\n  param :product_id, :number, :desc =\u003e \"Identifier of the product\", :required =\u003e true\n  param :quantity, :number, :desc =\u003e \"Number of products to order\", :required =\u003e true\n\nDecimalValidator\n--------------\n\nCheck if the parameter is a decimal number\n\n.. code:: ruby\n\n  param :latitude, :decimal, :desc =\u003e \"Geographic latitude\", :required =\u003e true\n  param :longitude, :decimal, :desc =\u003e \"Geographic longitude\", :required =\u003e true\n\nArrayValidator\n--------------\n\nCheck if the parameter is an array\n\nAdditional options\n~~~~~~~~~~~~~~~~~\n\nof\n  Specify the type of items. If not given it accepts an array of any item type\n\nin\n  Specify an array of valid item values.\n\nExamples\n~~~~~~~~\n\nAssert `things` is an array of any items\n\n.. code:: ruby\n\n  param :things, Array\n\nAssert `hits` must be an array of integer values\n\n.. code:: ruby\n\n  param :hits, Array, of: Integer\n\nAssert `colors` must be an array of valid string values\n\n.. code:: ruby\n\n  param :colors, Array, in: [\"red\", \"green\", \"blue\"]\n\n\nThe retrieving of valid items can be deferred until needed using a lambda. It is evaluated only once\n\n.. code:: ruby\n\n  param :colors, Array, in: -\u003e  { Color.all.pluck(:name) }\n\n\nNestedValidator\n-------------\n\nYou can describe nested parameters in depth if you provide a block with a\ndescription of nested values.\n\n.. code:: ruby\n\n   param :comments, Array, :desc =\u003e \"User comments\" do\n     param :name, String, :desc =\u003e \"Name of the comment\", :required =\u003e true\n     param :comment, String, :desc =\u003e \"Full comment\", :required =\u003e true\n   end\n\n\n\nAdding custom validator\n-----------------------\n\nOnly basic validators are included but it is really easy to add your own.\nCreate a new initializer with a subclass of Apipie::Validator::BaseValidator.\nTwo methods are required to implement this - instance method\n:code:`validate(value)` and class method\n:code:`build(param_description, argument, options, block)`.\n\nWhen searching for the validator +build+ method, every subclass of\nApipie::Validator::BaseValidator is called. The first one that returns the\nconstructed validator object is used.\n\nExample: Adding IntegerValidator\n\nWe want to check if the parameter value is an integer like this:\n\n.. code:: ruby\n\n   param :id, Integer, :desc =\u003e \"Company ID\"\n\nSo we create apipie_validators.rb initializer with this content:\n\n.. code:: ruby\n\n   class IntegerValidator \u003c Apipie::Validator::BaseValidator\n\n     def initialize(param_description, argument)\n       super(param_description)\n       @type = argument\n     end\n\n     def validate(value)\n       return false if value.nil?\n       !!(value.to_s =~ /^[-+]?[0-9]+$/)\n     end\n\n     def self.build(param_description, argument, options, block)\n       if argument == Integer || argument == Fixnum\n         self.new(param_description, argument)\n       end\n     end\n\n     def description\n       \"Must be #{@type}.\"\n     end\n   end\n\nParameters of the build method:\n\nparam_description\n  Instance of Apipie::ParamDescription contains all\n  given information about the validated parameter.\n\nargument\n  Specified validator; in our example it is +Integer+\n\noptions\n  Hash with specified options, for us just ``{:desc =\u003e \"Company ID\"}``\n\nblock\n  Block converted into Proc, use it as you desire. In this example nil.\n\n\n============\n Versioning\n============\n\nEvery resource/method can belong to one or more versions. The version is\nspecified with the `api_version` DSL keyword. When not specified,\nthe resource belongs to `config.default_version` (\"1.0\" by default)\n\n.. code:: ruby\n\n   resource_description do\n     api_versions \"1\", \"2\"\n   end\n\n   api :GET, \"/api/users/\", \"List: users\"\n   api_version \"1\"\n   def index\n     # ...\n   end\n\n   api :GET, \"/api/users/\", \"List: users\", :deprecated =\u003e true\n\nIn the example above we say the whole controller/resource is defined\nfor versions \"1\" and \"2\", but we override this by explicitly saying\n`index` belongs only to version \"1\". Also, inheritance works (therefore\nwe can specify the api_version for the parent controller, and all\nchildren will know about that). Routes can be flagged as deprecated,\nand an annotation will be added to them when viewing in the API\ndocumentation.\n\nFrom the Apipie API perspective, the resources belong to the version.\nWith versioning, there are paths like this provided by apipie:\n\n.. code::\n\n   /apipie/1/users/index\n   /apipie/2/users/index\n\nWhen not specifying the version explicitly in the path (or in DSL),\ndefault version (`Apipie.configuration.default_version`) is used\ninstead (\"1.0\" by default). Therefore, an application that doesn't\nneed versioning should work as before.\n\nThe static page generator takes a version parameter (or uses default).\n\nYou can specify the versions for the examples, with the `versions`\nkeyword. It specifies the versions the example is used for. When not\nspecified, it's shown in all versions with the given method.\n\nWhen referencing or quering the resource/method descripion, this\nformat should be used: \"version#resource#method\". When not specified,\nthe default version is used instead.\n\n\n========\n Markup\n========\n\nThe default markup language is `RDoc\n\u003chttps://rdoc.github.io/rdoc/RDoc/Markup.html\u003e`_. It can be changed in\nthe config file (``config.markup=``) to one of these:\n\nMarkdown\n  Use Apipie::Markup::Markdown.new. You need Maruku gem.\n\nTextile\n  Use Apipie::Markup::Textile.new. You need RedCloth gem.\n\nOr provide you own object with a ``to_html(text)`` method.\nFor inspiration, this is how Textile markup usage is implemented:\n\n.. code:: ruby\n\n   class Textile\n     def initialize\n       require 'RedCloth'\n     end\n     def to_html(text)\n       RedCloth.new(text).to_html\n     end\n   end\n\n============\nLocalization\n============\n\nApipie has support for localized API documentation in both formats (JSON and HTML).\nApipie uses the library I18n for localization of itself.\nCheck ``config/locales`` directory for available translations.\n\nA major part of strings in the documentation comes from the API.\nAs preferences regarding localization libraries differ amongst project, Apipie needs to know how to set the locale for your project,\nand how to translate a string using the library your project uses. That can be done using lambdas in configuration.\n\nSample configuration when your project uses FastGettext\n\n\n.. code:: ruby\n\n   Apipie.configure do |config|\n    ...\n    config.languages = ['en', 'cs']\n    config.default_locale = 'en'\n    config.locale = lambda { |loc| loc ? FastGettext.set_locale(loc) : FastGettext.locale }\n    config.translate = lambda do |str, loc|\n      old_loc = FastGettext.locale\n      FastGettext.set_locale(loc)\n      trans = _(str)\n      FastGettext.set_locale(old_loc)\n      trans\n    end\n   end\n\nAnd the strings in the API documentation need to be marked with the ``N_()`` function\n\n.. code:: ruby\n\n  api :GET, \"/users/:id\", N_(\"Show user profile\")\n  param :session, String, :desc =\u003e N_(\"user is logged in\"), :required =\u003e true\n\n\n\nWhen your project use I18n, localization related configuration could appear as follows\n\n.. code:: ruby\n\n   Apipie.configure do |config|\n    ...\n    config.languages = ['en', 'cs']\n    config.default_locale = 'en'\n    config.locale = lambda { |loc| loc ? I18n.locale = loc : I18n.locale }\n    config.translate = lambda do |str, loc|\n      return '' if str.blank?\n      I18n.t str, locale: loc, scope: 'doc'\n    end\n   end\n\nAnd the strings in the API documentation needs to be in the form of translation keys\n\n.. code:: ruby\n\n  api :GET, \"/users/:id\", \"show_user_profile\"\n  param :session, String, :desc =\u003e \"user_is_logged_in\", :required =\u003e true\n\n\nThe localized versions of the documentation are distinguished by language in the filename.\nE.g. ``doc/apidoc/apidoc.cs.html`` is static documentation in the Czech language.\nIf the language is missing, e.g. ``doc/apidoc/apidoc.html``,\nthe documentation is localized with the ``default_locale``.\n\nThe dynamic documentation follows the same schema. The ``http://localhost:3000/apidoc/v1.cs.html`` is documentation for version '1' of the API in the Czech language. For JSON descriptions, the API applies the same format: ``http://localhost:3000/apidoc/v1.cs.json``\n\n\n================\nModifying Views\n================\n\nTo modify the views of your documentation, run ``rails g apipie:views``.\nThis will copy the Apipie views to ``app/views/apipie/apipies`` and\n``app/views/layouts/apipie``.\n\n\n==============\n Static files\n==============\n\nTo generate a static version of documentation (perhaps to put it on\nyour project site or something), run the ``rake apipie:static`` task. It will\ncreate a set of HTML files (multi-pages, single-page, plain) in your doc\ndirectory. If you prefer a JSON version run ``rake apipie:static_json``.\nBy default the documentation for the default API version is\nused. You can specify the version with ``rake apipie:static[2.0]``\n\nWhen you want to avoid any unnecessary computation in production mode,\nyou can generate a cache with ``rake apipie:cache`` and configure the\napp to use it in production with ``config.use_cache = Rails.env.production?``\n\nDefault cache dir is ``File.join(Rails.root, \"public\", \"apipie-cache\")``,\nyou can change it to where you want, example: ``config.cache_dir = File.join(Rails.root, \"doc\", \"apidoc\")``.\n\nIf, for some complex cases, you need to generate/re-generate just part of the cache\nuse ``rake apipie:cache cache_part=index`` resp. ``rake apipie:cache cache_part=resources``\nTo generate it for different locations for further processing use ``rake apipie:cache OUT=/tmp/apipie_cache``.\n\n.. _Swagger:\n\n====================================\n Static Swagger (OpenAPI 2.0) files\n====================================\n\nTo generate a static Swagger definition file from the api, run ``rake apipie:static_swagger_json``.\nBy default the documentation for the default API version is\nused. You can specify the version with ``rake apipie:static_swagger_json[2.0]``. A swagger file will be\ngenerated for each locale.  The files will be generated in the same location as the static_json files, but\ninstead of being named ``schema_apipie[.locale].json``, they will be called ``schema_swagger[.locale].json``.\n\nSpecifying default values for parameters\n-----------------------------------------\nSwagger allows method definitions to include an indication of the the default value for each parameter. To include such\nindications, use ``:default_value =\u003e \u003csome value\u003e`` in the parameter definition DSL.  For example:\n\n.. code:: ruby\n\n     param :do_something, Boolean, :desc =\u003e \"take an action\", :required =\u003e false, :default_value =\u003e false\n\n\nGenerated Warnings\n-------------------\nThe help identify potential improvements to your documentation, the swagger generation process issues warnings if\nit identifies various shortcomings of the DSL documentation. Each warning has a code to allow selective suppression\n(see swagger-specific configuration below)\n\n:100: missing short description for method\n:101: added missing / at beginning of path\n:102: no return codes specified for method\n:103: a parameter is a generic Hash without an internal type specification\n:104: a parameter is an 'in-path' parameter, but specified as 'not required' in the DSL\n:105: a parameter is optional but does not have a default value specified\n:106: a parameter was ommitted from the swagger output because it is a Hash without fields in a formData specification\n:107: a path parameter is not described\n:108: inferring that a parameter type is boolean because described as an enum with [false,true] values\n\n\n\nSwagger-Specific Configuration Parameters\n-------------------------------------------------\n\nThere are several configuration parameters that determine the structure of the generated swagger file:\n\n``config.swagger_content_type_input``\n    If the value is ``:form_data`` - the swagger file will indicate that the server consumes the content types\n    ``application/x-www-form-urlencoded`` and ``multipart/form-data``.  Non-path parameters will have the\n    value ``\"in\": \"formData\"``.  Note that parameters of type Hash that do not have any fields in them will *be ommitted*\n    from the resulting files, as there is no way to describe them in swagger.\n\n    If the value is ``:json`` - the swagger file will indicate that the server consumes the content type\n    ``application/json``. All non-path parameters will be included in the schema of a single ``\"in\": \"body\"`` parameter\n    of type ``object``.\n\n    You can specify the value of this configuration parameter as an additional input to the rake command (e.g.,\n    ``rake apipie:static_swagger_json[2.0,form_data]``).\n\n``config.swagger_json_input_uses_refs``\n    This parameter is only relevant if ``swagger_content_type_input`` is ``:json``.\n\n    If ``true``: the schema of the ``\"in\": \"body\"`` parameter of each method is given its own entry in the ``definitions``\n    section, and is referenced using ``$ref`` from the method definition.\n\n    If ``false``: the body parameter definitions are inlined within the method definitions.\n\n``config.swagger_include_warning_tags``\n    If ``true``: in addition to tagging methods with the name of the resource they belong to, methods for which warnings\n    have been issued will be tagged with.\n\n``config.swagger_suppress_warnings``\n    If ``false``: no warnings will be suppressed\n\n    If ``true``: all warnings will be suppressed\n\n    If an array of values (e.g., ``[100,102,107]``), only the warnings identified by the numbers in the array will be suppressed.\n\n``config.swagger_api_host``\n    The value to place in the swagger host field.\n\n    Default is ``localhost:3000``\n\n    If ``nil`` then then host field will not be included.\n\n``config.swagger_allow_additional_properties_in_response``\n    If ``false`` (default):  response descriptions in the generated swagger will include an ``additional-properties: false``\n    field\n\n    If ``true``:  the ``additional-properties: false`` field will not be included in response object descriptions\n\n\nKnown limitations of the current implementation\n-------------------------------------------------\n* There is currently no way to document the structure and content-type of the data returned from a method\n* Recorded examples are currently not included in the generated swagger file\n* The apipie ``formats`` value is ignored.\n* It is not possible to specify the \"consumed\" content type on a per-method basis\n* It is not possible to leverage all of the parameter type/format capabilities of swagger\n* Only OpenAPI 2.0 is supported\n* Responses are defined inline and not as a $ref\n\n====================================\n Dynamic Swagger generation\n====================================\n\nTo generate swagger dynamically, use ``http://localhost:3000/apipie.json?type=swagger``.\n\nNote that authorization is not supported for dynamic swagger generation, so if ``config.authorize`` is defined,\ndynamic swagger generation will be disabled.\n\nDynamically generated swagger is not cached, and is always generated on the fly.\n\n\n===================\n JSON checksums\n===================\n\nIf the API client needs to be sure that the JSON didn't changed, add\nthe ``ApipieChecksumInHeaders`` middleware in your rails app.\nIt can add a checksum of the entire JSON document in the response headers.\n\n.. code::\n\n  \"Apipie-Checksum\"=\u003e\"fb81460e7f4e78d059f826624bdf9504\"\n\n`Apipie bindings \u003chttps://github.com/Apipie/apipie-bindings\u003e`_ uses this feature to refresh its JSON cache.\n\nTo set it up add the following to your ``application.rb``\n\n.. code::\n\n   require 'apipie/middleware/checksum_in_headers'\n   # Add JSON checksum in headers for smarter caching\n   config.middleware.use \"Apipie::Middleware::ChecksumInHeaders\"\n\nAnd in your apipie initializer allow checksum calculation\n\n.. code::\n\n   Apipie.configuration.update_checksum = true\n\n\nBy default the header is added to responses for ``config.doc_base_url`` and ``/api``.\nIt can be changed in configuration (see `Configuration Reference`_ for details).\n\nThe checksum calculation is lazy, and done with the first request. If you run with ``use_cache = true``,\ndo not forget to run the rake task ``apipie:cache``.\n\n\n===================\n Tests Integration\n===================\n\nApipie integrates with automated testing in two ways. *Documentation\nbootstrapping* and *examples recording*.\n\nDocumentation Bootstrapping\n---------------------------\n\nLet's say you have an application without REST API documentation.\nHowever you have a set of tests that are run against this API. A lot\nof information is already included in these tests, it just needs to be\nextracted somehow. Luckily, Apipie provides such a feature.\n\nWhen running the tests, set the ``APIPIE_RECORD=params`` environment\nvariable or call ``Apipie.record('params')`` from specs starter. You can either use it with functional tests:\n\n.. code::\n\n   APIPIE_RECORD=params rake test:functionals\n\nor you can run your server with this param, in case you run the tests\nagainst running server:\n\n.. code::\n\n   APIPIE_RECORD=params rails server\n\nWhen the process quits, the data from requests/responses are used to\ndetermine the documentation. It's quite raw, but it makes the initial\nphase much easier.\n\nExamples Recording\n------------------\n\nYou can also use the tests to generate up-to-date examples for your\ncode. Similar to the bootstrapping process, you can use it with functional\ntests or a running server, setting ``APIPIE_RECORD=examples`` or calling ``Apipie.record('examples')`` in your specs starter.\n\n.. code::\n\n   APIPIE_RECORD=examples rake test:functionals\n   APIPIE_RECORD=examples rails server\n\nThe data is written into ``doc/apipie_examples.yml``. By default,\nonly the first example is shown for each action. You can customize\nthis by setting the ``show_in_doc`` attribute at each example.\n\nYou can add a title to the examples (useful when showing more than\none example per method) by adding a 'title' attribute.\n\n.. code::\n\n   --- !omap\n     - announcements#index:\n       - !omap\n         - title: This is a custom title for this example\n         - verb: :GET\n         - path: /api/blabla/1\n         - versions:\n           - '1.0'\n         - query:\n         - request_data:\n         - response_data:\n           ...\n         - code: 200\n         - show_in_doc: 1   # If 1, show. If 0, do not show.\n         - recorded: true\n\nIn RSpec you can add metadata to examples. We can use that feature\nto mark selected examples - the ones that perform the requests that we want to\nshow as examples in the documentation.\n\nFor example, we can add ``show_in_doc`` to examples, like this:\n\n.. code:: ruby\n\n   describe \"This is the correct path\" do\n     it \"some test\", :show_in_doc do\n       ....\n     end\n   end\n\n   context \"These are edge cases\" do\n     it \"Can't authenticate\" do\n       ....\n     end\n\n      it \"record not found\" do\n        ....\n      end\n   end\n\nAnd then configure RSpec in this way:\n\n.. code:: ruby\n\n   RSpec.configure do |config|\n     config.treat_symbols_as_metadata_keys_with_true_values = true\n     config.filter_run :show_in_doc =\u003e true if ENV['APIPIE_RECORD']\n   end\n\nThis way, when running in recording mode, only the tests that have been marked with the\n``:show_in_doc`` metadata will be run, and hence only those will be used as examples.\n\nCaveats\n-------\n\nMake sure to enable ``config.render_views`` in your ``config/rails_helper.rb`` or\n``config/spec_helper.rb`` if you're using jbuilder, or you will get back empty results\n\n====================\n Bindings Generator\n====================\n\nIn earlier versions (\u003c= 0.0.13), there was a simple client generator\nas a part of Apipie gem. As more features and users came to Apipie,\nthere was a greater need for changes on a per project basis. It's\nhard (or even impossible) to provide a generic solution for the client\ncode. We also don't want to tell you what's the right way to do it\n(what gems to use, how the API should look like etc.).\n\nTherefore you can't generate client code directly by a rake task in\nfurther versions.\n\nThere is, however, an even better and more flexible way to reuse your API\ndocumentation for this purpose: using the API the Apipie\nprovides in the generator code. Check out our sister project\n`apipie-bindings \u003chttps://github.com/Apipie/apipie-bindings\u003e`_, as they\nuse exactly this approach. You also don't need to run the service,\nprovided it uses Apipie as a backend.\n\nAnd if you write one on your own, don't hesitate to share it with us!\n\n\n====================\n Disqus Integration\n====================\n\nYou can setup `Disqus \u003chttp://www.disqus.com\u003e`_ discussion within\nyour documentation. Just set the credentials in the Apipie\nconfiguration:\n\n.. code:: ruby\n\n   config.disqus_shortname = \"MyProjectDoc\"\n\n=====================\n External References\n=====================\n\n* `Getting started tutorial \u003chttps://github.com/iNecas/apipie-demo\u003e`_ -\n  including examples of using the tests integration and versioning.\n\n* `Real-world application usage \u003chttps://github.com/Katello/katello\u003e`_\n\n* `Read-world application usage with versioning \u003chttps://github.com/theforeman/foreman\u003e`_\n\n* `Using Apipie API to generate bindings \u003chttps://github.com/Apipie/apipie-bindings\u003e`_\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpowermobileweb%2Fapipie-rails","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpowermobileweb%2Fapipie-rails","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpowermobileweb%2Fapipie-rails/lists"}