Generate pretty API docs for your Rails APIs.
Check out a sample.
Please see the wiki for latest changes.
Add rspec_api_documentation to your Gemfile
gem 'rspec_api_documentation'
Bundle it!
$ bundle install
Set up specs.
$ mkdir spec/acceptance
$ vim spec/acceptance/orders_spec.rb
require'rails_helper'require'rspec_api_documentation/dsl'resource"Orders"doget"/orders"doexample"Listing orders"dodo_requestexpect(status).toeq200endendendGenerate the docs!
$ rake docs:generate
$ open doc/api/index.html
Consider adding a viewer to enhance the generated documentation. By itself rspec_api_documentation will generate very simple HTML. All viewers use the generated JSON.
gem 'raddocs'
or gem 'apitome'
RspecApiDocumentation.configuredo |config|
config.format=:jsonendFor both raddocs and apitome, start rails server. Then
open http://localhost:3000/docs for raddocs
or
http://localhost:3000/api/docs for apitome
See the example folder for a sample Rails app that has been documented. The sample app demonstrates the :open_api format.
# spec/acceptance/orders_spec.rbrequire'rails_helper'require'rspec_api_documentation/dsl'resource'Orders'doexplanation"Orders resource"header"Content-Type","application/json"get'/orders'do# This is manual way to describe complex parametersparameter:one_level_array,type: :array,items: {type: :string,enum: ['string1','string2']},default: ['string1']parameter:two_level_array,type: :array,items: {type: :array,items: {type: :string}}let(:one_level_array){['string1','string2']}let(:two_level_array){[['123','234'],['111']]}# This is automatic way# It's possible because we extract parameters definitions from the valuesparameter:one_level_arr,with_example: trueparameter:two_level_arr,with_example: truelet(:one_level_arr){['value1','value2']}let(:two_level_arr){[[5.1,3.0],[1.0,4.5]]}context'200'doexample_request'Getting a list of orders'doexpect(status).toeq(200)endendendput'/orders/:id'dowith_optionsscope: :data,with_example: truedoparameter:name,'The order name',required: trueparameter:amountparameter:description,'The order description'endcontext"200"dolet(:id){1}example'Update an order'dorequest={data: {name: 'order',amount: 1,description: 'fast order'}}# It's also possible to extract types of parameters when you pass data through `do_request` method.do_request(request)expected_response={data: {name: 'order',amount: 1,description: 'fast order'}}expect(status).toeq(200)expect(response_body).toeq(expected_response)endendcontext"400"dolet(:id){"a"}example_request'Invalid request'doexpect(status).toeq(400)endendcontext"404"dolet(:id){0}example_request'Order is not found'doexpect(status).toeq(404)endendendend# Values listed are the default valuesRspecApiDocumentation.configuredo |config|
# Set the application that Rack::Test usesconfig.app=Rails.application# Used to provide a configuration for the specification (supported only by 'open_api' format for now) config.configurations_dir=Rails.root.join("doc","configurations","api")# Output folder# **WARNING*** All contents of the configured directory will be cleared, use a dedicated directory.config.docs_dir=Rails.root.join("doc","api")# An array of output format(s).# Possible values are :json, :html, :combined_text, :combined_json,# :json_iodocs, :textile, :markdown, :append_json, :slate,# :api_blueprint, :open_apiconfig.format=[:html]# Location of templatesconfig.template_path="inside of the gem"# Filter by example document typeconfig.filter=:all# Filter by example document typeconfig.exclusion_filter=nil# Used when adding a cURL output to the docsconfig.curl_host=nil# Used when adding a cURL output to the docs# Allows you to filter out headers that are not needed in the cURL request,# such as "Host" and "Cookie". Set as an array.config.curl_headers_to_filter=nil# By default, when these settings are nil, all headers are shown,# which is sometimes too chatty. Setting the parameters to an# array of headers will render *only* those headers.config.request_headers_to_include=nilconfig.response_headers_to_include=nil# By default examples and resources are ordered by description. Set to true keep# the source order.config.keep_source_order=false# Change the name of the API on index pagesconfig.api_name="API Documentation"# Change the description of the API on index pagesconfig.api_explanation="API Description"# Redefine what method the DSL thinks is the client# This is useful if you need to `let` your own client, most likely a model.config.client_method=:client# Change the IODocs writer protocolconfig.io_docs_protocol="http"# You can define documentation groups as well. A group allows you generate multiple# sets of documentation.config.define_group:publicdo |config|
# By default the group's doc_dir is a subfolder under the parent group, based# on the group's name.# **WARNING*** All contents of the configured directory will be cleared, use a dedicated directory.config.docs_dir=Rails.root.join("doc","api","public")# Change the filter to only include :public examplesconfig.filter=:publicend# Change how the post body is formatted by default, you can still override by `raw_post`# Can be :json, :xml, or a proc that will be passed the paramsconfig.request_body_formatter=Proc.new{ |params| params}# Change how the response body is formatted by default# Is proc that will be called with the response_content_type & response_body# by default, a response body that is likely to be binary is replaced with the string# "[binary data]" regardless of the media type. Otherwise, a response_content_type of `application/json` is pretty formatted.config.response_body_formatter=Proc.new{ |response_content_type,response_body| response_body}# Change the embedded style for HTML output. This file will not be processed by# RspecApiDocumentation and should be plain CSS.config.html_embedded_css_file=nil# Removes the DSL method `status`, this is required if you have a parameter named status# In this case you can assert response status with `expect(response_status).to eq 200`config.disable_dsl_status!# Removes the DSL method `method`, this is required if you have a parameter named methodconfig.disable_dsl_method!end- json: Generates an index file and example files in JSON.
- html: Generates an index file and example files in HTML.
- combined_text: Generates a single file for each resource. Used by Raddocs for command line docs.
- combined_json: Generates a single file for all examples.
- json_iodocs: Generates I/O Docs style documentation.
- textile: Generates an index file and example files in Textile.
- markdown: Generates an index file and example files in Markdown.
- api_blueprint: Generates an index file and example files in APIBlueprint.
- append_json: Lets you selectively run specs without destroying current documentation. See section below.
- slate: Builds markdown files that can be used with Slate, a beautiful static documentation builder.
- open_api: Generates OpenAPI Specification (OAS) (Current supported version is 2.0). Can be used for Swagger-UI
This format cannot be run with other formats as they will delete the entire documentation folder upon each run. This format appends new examples to the index file, and writes all run examples in the correct folder.
Below is a rake task that allows this format to be used easily.
RSpec::Core::RakeTask.new('docs:generate:append',:spec_file)do |t,task_args|
ifspec_file=task_args[:spec_file]ENV["DOC_FORMAT"]="append_json"endt.pattern=spec_file || 'spec/acceptance/**/*_spec.rb't.rspec_opts=["--format RspecApiDocumentation::ApiFormatter"]endAnd in your spec/spec_helper.rb:
ENV["DOC_FORMAT"] ||= "json"RspecApiDocumentation.configuredo |config|
config.format=ENV["DOC_FORMAT"]endrake docs:generate:append[spec/acceptance/orders_spec.rb]This will update the current index's examples to include any in the orders_spec.rb file. Any examples inside will be rewritten.
This format (APIB) has additional functions:
route: APIB groups URLs together and then below them are HTTP verbs.route"/orders","Orders Collection"doget"Returns all orders"do# ...enddelete"Deletes all orders"do# ...endend
If you don't use
route, then param inget(param)should be an URL as states in the rest of this documentation.attribute: APIB has attributes besides parameters. Use attributes exactly like you'd useparameter(see documentation below).
This format (OAS) has additional functions:
authentication(type, value, opts = {})(Security schema object)The values will be passed through header of the request. Option
namehas to be provided forapiKey.authentication :basic, 'Basic Key'authentication :apiKey, 'Api Key', name: 'API_AUTH', description: 'Some description'
You could pass
Symbolas value. In this case you need to define aletwith the same name.authentication :apiKey, :api_key let(:api_key) { some_value }route_summary(text)androute_description(text). (Operation object)These two simplest methods accept
String. It will be used for route'ssummaryanddescription.Several new options on
parameterhelper.with_example: true. This option will adjust your example of the parameter with the passed value.example: <value>. Will provide a example value for the parameter.default: <value>. Will provide a default value for the parameter.minimum: <integer>. Will setup upper limit for your parameter.maximum: <integer>. Will setup lower limit for your parameter.enum: [<value>, <value>, ..]. Will provide a pre-defined list of possible values for your parameter.type: [:file, :array, :object, :boolean, :integer, :number, :string]. Will set a type for the parameter. Most of the type you don't need to provide this option manually. We extract types from values automatically.
You also can provide a configuration file in YAML or JSON format with some manual configs.
The file should be placed in configurations_dir folder with the name open_api.yml or open_api.json.
In this file you able to manually hide some endpoints/resources you want to hide from generated API specification but still want to test.
It's also possible to pass almost everything to the specification builder manually.
swagger: '2.0'info:
title: OpenAPI Appdescription: This is a sample server.termsOfService: 'http://open-api.io/terms/'contact:
name: API Supporturl: 'http://www.open-api.io/support'email: support@open-api.iolicense:
name: Apache 2.0url: 'http://www.apache.org/licenses/LICENSE-2.0.html'version: 1.0.0host: 'localhost:3000'schemes:
- http
- httpsconsumes:
- application/json
- application/xmlproduces:
- application/json
- application/xmlpaths: /orders:
hide: true/instructions:
hide: falseget:
description: This description came from configuration filehide: trueresource'Orders'doexplanation"Orders resource"authentication:apiKey,:api_key,description: 'Private key for API access',name: 'HEADER_KEY'header"Content-Type","application/json"let(:api_key){generate_api_key}get'/orders'doroute_summary"This URL allows users to interact with all orders."route_description"Long description."# This is manual way to describe complex parametersparameter:one_level_array,type: :array,items: {type: :string,enum: ['string1','string2']},default: ['string1']parameter:two_level_array,type: :array,items: {type: :array,items: {type: :string}}let(:one_level_array){['string1','string2']}let(:two_level_array){[['123','234'],['111']]}# This is automatic way# It's possible because we extract parameters definitions from the valuesparameter:one_level_arr,with_example: trueparameter:two_level_arr,with_example: truelet(:one_level_arr){['value1','value2']}let(:two_level_arr){[[5.1,3.0],[1.0,4.5]]}context'200'doexample_request'Getting a list of orders'doexpect(status).toeq(200)expect(response_body).toeq(<response>)endendendput'/orders/:id'doroute_summary"This is used to update orders."with_optionsscope: :data,with_example: truedoparameter:name,'The order name',required: trueparameter:amountparameter:description,'The order description'endcontext"200"dolet(:id){1}example'Update an order'dorequest={data: {name: 'order',amount: 1,description: 'fast order'}}# It's also possible to extract types of parameters when you pass data through `do_request` method.do_request(request)expected_response={data: {name: 'order',amount: 1,description: 'fast order'}}expect(status).toeq(200)expect(response_body).toeq(<response>)endendcontext"400"dolet(:id){"a"}example_request'Invalid request'doexpect(status).toeq(400)endendcontext"404"dolet(:id){0}example_request'Order is not found'doexpect(status).toeq(404)endendendendrspec_api_documentation lets you determine which examples get outputted into the final documentation.
All filtering is done via the :document metadata key.
You tag examples with either a single symbol or an array of symbols.
:document can also be false, which will make sure it does not get outputted.
resource"Account"doget"/accounts"doparameter:page,"Page to view"# default :document is :allexample"Get a list of all accounts"dodo_requestexpect(status).toeq200end# Don't actually document this example, purely for testing purposesexample"Get a list on page 2",:document=>falsedodo_request(:page=>2)expect(status).toeq404end# With example_request, you can't change the :documentexample_request"Get a list on page 3",:page=>3doexpect(status).toeq404endendpost"/accounts"doparameter:email,"User email"example"Creating an account",:document=>:privatedodo_request(:email=>"eric@example.com")expect(status).toeq201endexample"Creating an account - errors",:document=>[:private,:developers]dodo_requestexpect(status).toeq422endendend# All documents will be generated into the top folder, :document => false# examples will never be generated.RspecApiDocumentation.configuredo |config|
# Exclude only document examples marked as 'private'config.define_group:non_privatedo |config|
config.exclusion_filter=:privateend# Only document examples marked as 'public'config.define_group:publicdo |config|
config.filter=:publicend# Only document examples marked as 'developer'config.define_group:developersdo |config|
config.filter=:developersendendAt the beginning of each acceptance/*_spec.rb file, make sure to require the following to pull in the DSL definitions:
require'rspec_api_documentation/dsl'Create a set of documentation examples that go together. Acts as a describe block.
resource"Orders"doendThe method that will be sent along with the url.
resource"Orders"dopost"/orders"doendget"/orders"doendhead"/orders"doendput"/orders/:id"dolet(:id){order.id}example"Get an order"doexpect(path).toeq"/orders/1"# `:id` is replaced with the value of `id`endenddelete"/orders/:id"doendpatch"/orders/:id"doendendThis is just RSpec's built in example method, we hook into the metadata surrounding it. it could also be used.
resource"Orders"dopost"/orders"doexample"Creating an order"dodo_request# make assertionsendendendThe same as example, except it calls do_request as the first step. Only assertions are required in the block.
Similar to do_request you can pass in a hash as the last parameter that will be passed along to do_request as extra parameters. These will not become metadata like with example.
resource"Orders"doparameter:name,"Order name"post"/orders"doexample_request"Creating an order",:name=>"Other name"do# make assertionsendendendThis method takes a string representing a detailed explanation of the example.
resource"Orders"dopost"/orders"doexample"Creating an order"doexplanation"This method creates a new order."do_request# make assertionsendendendA resource can also have an explanation.
resource"Orders"doexplanation"Orders are top-level business objects. They can be created by a POST request"post"/orders"doexample"Creating an order"doexplanation"This method creates a new order."do_request# make assertionsendendendThis method takes the header name and value. The value can be a string or a symbol. If it is a symbol it will send the symbol, allowing you to let header values.
resource"Orders"doheader"Accept","application/json"header"X-Custom",:custom_headerlet(:custom_header){"dynamic"}get"/orders"doexample_request"Headers"doexpect(headers).toeq{"Accept"=>"application/json","X-Custom"=>"dynamic"}endendendThis method takes the parameter name, a description, and an optional hash of extra metadata that can be displayed in Raddocs as extra columns. If a method with the parameter name exists, e.g. a let, it will send the returned value up to the server as URL encoded data.
Special values:
:required => trueWill display a red '*' to show it's required:scope => :the_scopeWill scope parameters in the hash, scoping can be nested. See example:method => :method_nameWill use specified method as a parameter value
Retrieving of parameter value goes through several steps:
- if
methodoption is defined and test case responds to this method then this method is used; - if test case responds to scoped method then this method is used;
- overwise unscoped method is used.
resource"Orders"doparameter:auth_token,"Authentication Token"let(:auth_token){user.authentication_token}post"/orders"doparameter:name,"Order Name",:required=>true,:scope=>:orderparameter:item,"Order items",:scope=>:orderparameter:item_id,"Item id",:scope=>[:order,:item],method: :custom_item_idlet(:name){"My Order"}# OR let(:order_name) { "My Order" }let(:item_id){1}# OR let(:custom_item_id) { 1 }# OR let(:order_item_item_id) { 1 }example"Creating an order"doexpect(params).toeq({:order=>{:name=>"My Order",:item=>{:item_id=>1,}},:auth_token=>auth_token,})endendendThis method takes the response field name, a description, and an optional hash of extra metadata that can be displayed in Raddocs as extra columns.
Special values:
:scope => :the_scopeWill scope the response field in the hash
resource"Orders"doresponse_field:page,"Current page"get"/orders"doexample_request"Getting orders"doexpect(response_body).toeq({:page=>1}.to_json)endendendYou can also group metadata using with_options to factor out duplications.
resource"Orders"dopost"/orders"dowith_options:scope=>:order,:required=>truedoparameter:name,"Order Name"parameter:item,"Order items"endwith_options:scope=>:orderdoresponse_field:id,"Order ID"response_field:status,"Order status"endlet(:name){"My Order"}let(:item_id){1}example"Creating an order"doexpect(status).tobe201endendendThis is complicated, see relish docs.
Pass this method a block which, when evaluated, will cause the application to make a request to callback_url.
Defines the destination of the callback.
For an example, see relish docs.
Returns the test client which makes requests and documents the responses.
resource"Order"doget"/orders"doexample"Listing orders"do# Create an order via the API instead of via factoriesclient.post"/orders",order_hashdo_requestexpect(status).toeq200endendendThis will evaluate the block passed to trigger_callback, which should cause the application under test to make a callback request. See relish docs.
Sends the request to the app with any parameters and headers defined.
resource"Order"doget"/orders"doexample"Listing orders"dodo_requestexpect(status).toeq200endendendIf you wish to make a request via the client that should not be included in your documentation, do it inside of a no_doc block.
resource"Order"doget"/orders"doexample"Listing orders"dono_docdo# Create an order via the API instead of via factories, don't document itclient.post"/orders",order_hashenddo_requestexpect(status).toeq200endendendGet a hash of parameters that will be sent. See parameter documentation for an example.
This method takes the header name and value.
resource"Orders"dobeforedoheader"Accept","application/json"endget"/orders"doexample_request"Headers"doexpect(headers).toeq{"Accept"=>"application/json"}endendendThis returns the headers that were sent as the request. See header documentation for an example.
Returns a string containing the response body from the previous request.
resource"Order"doget"/orders"doexample"Listing orders"dodo_requestexpect(response_body).toeq[{:name=>"Order 1"}].to_jsonendendendReturns a hash of the response headers from the previous request.
resource"Order"doget"/orders"doexample"Listing orders"dodo_requestexpect(response_headers["Content-Type"]).toeq"application/json"endendendReturns the numeric status code from the response, eg. 200. response_status is an alias to status because status is commonly a parameter.
resource"Order"doget"/orders"doexample"Listing orders"dodo_requestexpect(status).toeq200expect(response_status).toeq200endendendData that will be sent as a query string instead of post data. Used in GET requests.
resource"Orders"doparameter:namelet(:name){"My Order"}get"/orders"doexample"List orders"doexpect(query_string).toeq"name=My+Orders"endendendYou can completely override what gets sent as parameters by let-ing raw_post.
resource"Orders"doheader"Content-Type","application/json"parameter:namelet(:name){"My Order"}post"/orders"dolet(:raw_post){params.to_json}example_request"Create new order"do# params get sent as JSONendendendThe gem contains a Railtie that defines a rake task for generating docs easily with Rails.
It loads all files in spec/acceptance/**/*_spec.rb.
$ rake docs:generateIf you are not using Rails, you can use Rake with the following Task:
require'rspec/core/rake_task'desc'Generate API request documentation from API specs'RSpec::Core::RakeTask.new('docs:generate')do |t|
t.pattern='spec/acceptance/**/*_spec.rb't.rspec_opts=["--format RspecApiDocumentation::ApiFormatter"]endor
require'rspec_api_documentation'load'tasks/docs.rake'If you are not using Rake:
$ rspec spec/acceptance --format RspecApiDocumentation::ApiFormatterFor an example on uploading a file see examples/spec/acceptance/upload_spec.rb.
- rspec_api_documentation relies on a variable
clientto be the test client. If you define your ownclientplease configure rspec_api_documentation to use another one, see Configuration above. - We make heavy use of RSpec metadata, you can actually use the entire gem without the DSL if you hand write the metadata.
- You must use
response_body,status,response_content_type, etc. to access data from the last response. You will not be able to useresponse.bodyorresponse.statusas the response object will not be created.