zipmark / rspec_api_documentation Goto Github PK
View Code? Open in Web Editor NEWAutomatically generate API documentation from RSpec
License: MIT License
Automatically generate API documentation from RSpec
License: MIT License
In the same way that the DSL ensures that the API is called with the right parameters (required or not), have you ever thought of adding an expected_attributes method?
If your API returns a JSON, wouldn't it be nice to know (and to enforce with rspec) which attributes are returned and (at least) their type?
To make a comparison, it would like having on the Github API orgs page not only one single example of the response:
[
{
"login": "github",
"id": 1,
"url": "https://api.github.com/orgs/github",
"avatar_url": "https://github.com/images/error/octocat_happy.gif"
}
]
but a documentation specifying that the organization object returned by the API always has:
The documentation might then add some more value to these attributes, explaining in words what they are, and what their characteristics are (example: if they can be null, what is their maximum size, etc.).
What is your opinion on this?
There is a warning being printed for deprecation of RSpec::Core::Configuration#backtrace_clean_patterns
DEPRECATION: RSpec::Core::Configuration#backtrace_clean_patterns is deprecated.
Use RSpec::Core::Configuration#backtrace_exclusion_patterns instead.
Called from lib/rspec_api_documentation/dsl.rb:17:in `<top (required)>'.
Rack::Test needs example groups to define an "app" method. This is easy enough to do, but we should be nice and default this to Rails.application (if Rails is defined).
There should also be a configuration option to override this across all API doc specs.
Users should still be able to override the app per example group by defining "app."
The way configuration sets/configurations work right now doesn't make a whole lot of sense. Configurations define an output format, e.g. json, which is used to choose a mustache template.
The configurations should instead be based on a scope鈥攍ike public, private, vendor, client鈥攚hich would be used to generate different "collections" of documentation.
Formats should be selected per collection, allowing multiple.
Required parameters are not being displayed as required in the docs.
parameter :auth_token, "Authentication Token for User"
required_parameters :auth_token
It is nice to have some way to describe response parameters, because now it is not full API documentation. Something like response_parameter :property_name, 'Property Name description'
I wanted to use the typical RSpec before filters, so I tagged several of my resources as:
resource_spec.rb
resource "Resource Name", api: :json do
# specs...
end
spec_helper.rb
RSpec.configure do |config|
config.before(:each, api: :json) do
header 'Authorization', "Bearer [access token]"
header 'Content-Type', 'application/json'
header 'Accept', 'application/json'
end
end
It fails on the header, because that's part of the DSL, and doesn't seem to be available any other way. I dug around a good bit, but there doesn't seem to be a way to specify headers/params within a before filter -- which would be nice, because I have to duplicate this at the top of all of the specs.
Thanks for a great library, it's been working really well for me and has been a pleasure to work with.
The idea here is to let users pass parameters into client.(get|put|post|delete) and also do_request, which would then override the parameters defined in the example group.
This would make it easier to write degenerate cases, which currently need to be wrapped in a context so we can override.
Each route should be clearly delineated (with the 2nd biggest heading on the page, or with an <hr> or something)
It would also be nice if each route had an English-readable summary of what it did, eg "POST /orders" creates a new order.
It would be nice in the curl command if the headers lined up - just makes it a little easier to scan. So instead of:
curl "http://rad-example.herokuapp.com/orders" -d "{"order":{"name":"Order 1","paid":true,"email":"[email protected]"}}" -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Host: example.org" -H "Cookie: "
you'd have:
curl "http://rad-example.herokuapp.com/orders" -d "{"order":{"name":"Order 1","paid":true,"email":"[email protected]"}}" -X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Host: example.org" \
-H "Cookie: "
Also it's a little odd that the host doesn't match the domain in the URL, although thit might be harder to fix.
Hello again! 馃榾
Parameters passed to POST/PUT should be URI.escaped, for instance in this example the line
let(:auth_token) { user.authentication_token }
should actually say
let(:auth_token) { URI.escape user.authentication_token }
This is important when the parameter includes UTF-8 (or non-ASCII characters), and here is how to prove it. In your Rails /example, add # encoding: UTF-8
at the top, then change this line from
let(:name) { "Order 1" }
to
let(:name) { "Order W铆th 脷nic贸de 1" }
and run rake docs:generate
.
The documentation will then include the following cURL example:
curl "http://localhost:3000/orders" -d '{"order":{"name":"Order W\u00edth \u00danic\u00f3de 1","paid":true,"email":"[email protected]"}}' -X POST
which is incorrect, because it POSTs an order with name Order W\u00edth \u00danic\u00f3de 1
.
Instead, if you use URI.encode
, then the documentation would output:
curl "http://localhost:3000/orders" -d '{"order":{"name":"Order%20W%C3%ADth%20%C3%9Anic%C3%B3de%201","paid":true,"email":"[email protected]"}}' -X POST
which is correct, because it POSTs an order with name Order W铆th 脷nic贸de 1
This shouldn't be the case, otherwise you get confusing examples such as:
curl "https://foo.com/orders.json" -X GET -H "Accept: application/json" -H "Content-Type: application/json" -H "Host: example.org" -H "Cookie: "
Those two headers really confuse people when they read through the docs. Is there any real value added in having them, as is?
I am following the http://jsonapi.org/ guidelines in a new api I'm creating. These guidelines enforce you to treat your resources always as arrays.
By example, if I want to create a Post object, even if its only a post, the POST request payload should look like this:
{
posts: [
{ title: "Some fame war begin", content: "Loren ipsum...", author_id: 1 }
]
}
I could't figure out how to use de DSL to express that there is two parameters (title
and content
), that both are required, and they are nested inside an array.
Is there a way? Could this be acomplised with the new DSL?
It looks funny with an empty block.
It's only required for the OAuthClient.
Remove any requirement for asset management from RAD. It's something that RAD shouldn't care about. Raddocs does a much better job at this anyways.
Reference this issue for any PRs that affect the DSL.
Currently it generates into docs/
. It seems that using the already existing doc/
folder would make more sense, maybe doc/api/
to keep things organized in case someone is actually using doc/
for other things.
An API documentation example might encompass multiple requests to the API. Right now we don't support this, and I believe a later request will override a former one.
When an API only responds to calls on a given subdomain, it seems the full url must be specified in the example group. It would be preferable to specify the api host in the configuration instead.
I had a spec defining a client like this:
let(:client) { FactoryGirl.create :client }
It took some time to realize that the call to client
here:
was conflicting with my previous declaration.
Usually there is some amount of business logic attached to a request - eg, "Orders can't have more than 20 items" or something - would be nice if there was a place in the documentation for that.
In order to help a consumer of my API know what fields mean
In order to validate responses match schema
RspecApiDocumentation.configure do |config|
config.schema_dir = "schemas"
end
resource "Order" do
representation "application/json", "order_schema.json"
get "/orders/1" do
example_request "How can we validate the response body against the schema?" do
status.should eq(200)
response_body.should be_valid_schema
end
end
end
Links:
http://tools.ietf.org/html/draft-zyp-json-schema-03
https://github.com/hoxworth/json-schema
Given the following
get "/orders/:id" do
let(:id) { 1 }
example "Another order" do
do_request(:id => 2)
end
end
The path is not updated to reflect the new id
Here for example:
http://rad-example.herokuapp.com/docs/orders/getting_a_specific_order
What parameters are in the body? what are the possible values? what type is each parameter? are all the parameters always there? etc.
when running rake docs:generate I get:
rspec_api_documentation-0.9.0/lib/rspec_api_documentation/api_formatter.rb:14
in start' undefined method
documentations' for RspecApiDocumentation:Module (NoMethodError)
We have a number of tests we would like to exclude from our generated documentation, but we can't seem to get the no_doc function (https://github.com/zipmark/rspec_api_documentation/wiki/DSL#no_doc) to work properly. We're still using 0.9.0 of the gem, but we tried upgrading to 1.0.0 just to see if it fixed it and it had no effect.
I created a simple example below of how we're trying to use it. When we run that spec through rake docs:generate, the result is API documentation for both tests, rather than just the first one. Is this functionality known to be broken, or are we perhaps just using it wrong?
https://gist.github.com/lazerwalker/6132709
Thanks!
It'd be awesome if they were in there.
HEAD and PATCH are missing, PATCH is not so important but I think HEAD is.
Hi,
now in iodocs output, the protocol is hardcoded to "http". I think that should be a configurable option but I'm not sure that it feels right for you. Any suggestions?
Under what license is this code released?
Right now we use rack/test, which gets included in every resource context and injected into TestClient as "session." We should provide a configuration option to use something other than rack/test. For example, someone using rest-client should be able to run the tests against a live server.
The README leaves a lot to be desired and could be better.
Right now we store all of our metadata directly in the RSpec metadata hash. To avoid possible collisions with existing metadata uses, we should store all of our metadata under a single key.
WebMock normalizes uri in a way, Rack can't parse correctly. But OAuth2MacClient relies on WebMock.
The limitation is: Hashes with digits as keys: {:digits => {'1' => 'One, '2' => 'Two'}}
. In tests, they will be treated as {:digits => ['One', 'Two']}
.
More information can be found here: #51
The case is:
WebMock::Util::URI.normalize_uri("e.com?a[]=b&a[]=c")
#=> ...a%5B0%5D=b&a%5B1%5D=c <- it added 0 and 1
Rack::Utils.parse_nested_query("a%5B0%5D=b&a%5B1%5D=c")
#=> {"a"=>{"0"=>"b", "1"=>"c"}} <- this is wrong: it must be {"a"=>["b", "c"]}
So, unfortunatly, I've added hack to remove digits, put by WebMock: denyago@69b6222#L1R57
For instance header "Content-Type", "application/json"
causes:
ActionDispatch::ParamsParser::ParseError:
unexpected character at line 1, column 1 [parse.c:625]
# /Users/Aerlinger/.rvm/gems/ruby-1.9.3-p362/gems/actionpack-4.0.0/lib/action_dispatch/middleware/params_parser.rb:53:in `rescue in parse_formatted_parameters'
# /Users/Aerlinger/.rvm/gems/ruby-1.9.3-p362/gems/actionpack-4.0.0/lib/action_dispatch/middleware/params_parser.rb:32:in `parse_formatted_parameters'
# /Users/Aerlinger/.rvm/gems/ruby-1.9.3-p362/gems/actionpack-4.0.0/lib/action_dispatch/middleware/params_parser.rb:23:in `call'
# /Users/Aerlinger/.rvm/gems/ruby-1.9.3-p362/gems/activerecord-4.0.0/lib/active_record/query_cache.rb:36:in `call'
# /Users/Aerlinger/.rvm/gems/ruby-1.9.3-p362/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
# /Users/Aerlinger/.rvm/gems/ruby-1.9.3-p362/gems/actionpack-4.0.0/lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
Any way around this without disabling the ParamsParser middleware?
HtmlWriter can't handle the encoding:
lib/rspec_api_documentation/html_writer.rb:25:in `write': "\x89" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)
The test suite is currently broken because ActiveSupport can't load a transliteration file to support the parameterize
method, which is used in the iodocs formatter.
We need to figure out where FakeFS is needed, and include it more selectively. Alternatively, we can disable FakeFS around areas where the real file system is required, if possible.
In the generated docs there should be a type column in the parameters table.
I'd like to stub or mock certain objects and classes such that when I generate the API documentation I don't have to hit external services.
I'm trying to set the HTTP_REMOTE_ADDR header to test accessing the API as a remote user. This worked fine with RSpec request specs, but broke upon converting to rspec_api_documentation.
Looking at the request.env that the controller gets, I saw that REMOTE_ADDR was "127.0.0.1", while HTTP_REMOTE_ADDR was the desired value. I eventually traced the problem back to Rack::Test::Session#default_env
, which sets REMOTE_ADDR, and RspecApiDocumentation::Headers#headers_to_env
which make it impossible to set REMOTE_ADDR.
I'm not entirely sure that it's rspec_api_documentation's responsibility to override REMOTE_ADDR, but it seems like the most plausible possibility since other test libraries use Rack::Test
without this problem.
The following monkey patch works around the issue for me:
module RspecApiDocumentation::Headers
def headers_to_env_with_remote_addr_fix headers
env = headers_to_env_without_remote_addr_fix(headers)
env["REMOTE_ADDR"] = env["HTTP_REMOTE_ADDR"] if env["HTTP_REMOTE_ADDR"]
env
end
alias_method_chain :headers_to_env, :remote_addr_fix
end
Hey,
First of all, amazing project! Conceptually and well done too.
I am missing having the route parameter (e.g. it's used in mustache html_example.mustache) in the JSON files. I don't use the generated html files, so I need the json to have all those things so I can display it otherwise.
I used requests.first.request_path, but the problem with that one is that params like :id, :model_id are already replaced with IDs here, so it's not good.
While you're at it you could also add the http_method property, so it doesn't have to be guessed from requests.first.
Thanks and keep up the good work!
The cURL examples genreated when doing a POST or PUT don't properly quote the data associated with the -d
flag.
For example, the rad-example app has the following cURL example for creating an order:
curl "http://rad-example.herokuapp.com/orders" -d "{"order":{"name":"Order 1","paid":true,"email":"[email protected]"}}" -X POST -H "Accept: application/json" -H "Content-Type: application/json" -H "Host: example.org" -H "Cookie: "
source: http://rad-example.herokuapp.com/docs/orders/creating_an_order
If you copy/paste that example it'll fail because the data uses all double quotes. Instead the outer quotes should be single quotes such as:
-d '{"order":{"name":"Order 1","paid":true,"email":"[email protected]"}}'
Hey all!
First off, thanks so much for this gem! It's saving me a lot of time working with consumers of an API I'm prototyping!
That being said, I've currently having trouble configuring rspec_api_documentation; specifically the filter
and exclude_filter
options in RspecApiDocumentation ::Configuration
.
My use case is as follows: I have a set of shared examples that look something like this:
shared_examples "an api endpoint", standard_response: true do
example_request "should respond with HTTP 200" do
status.should == 200
response_body.should =~ /"status": 200/
end
example_request "should return a response with a json mime type" do
response_headers["Content-Type"].should == "application/json; charset=utf-8"
end
end
It's useful to me to have these run for a variety of examples. Unfortunately, these examples are not at all helpful when they're included in the generated documentation. I've attempted to exclude them by adding document: false
and later document: :private
with the corresponding exclude filter configuration. Neither has worked out too well for me.
TLDR: How do I exclude shared examples from the generated documentation (rake docs:generate)?
Thanks for your time, and awesome work with this gem!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
馃枛 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 馃搳馃搱馃帀
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google 鉂わ笍 Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.