问题
I have a Grape API protected by Doorkeeper and I have a bunch of methods which work perfectly. However, there's one method that behaves weirdly. It is a GET request that requires no parameters and running it throws the following error:
Grape::Exceptions::ValidationErrors at /v1/discount_cards/all.json
id is invalid
My method looks like this:
desc 'Get all the cards of current customer'
params {}
get 'all' do
current_customer.discount_cards.to_json(include:
{
barcode: {
include: :barcode_type
}
})
end
The logs say that the error happens at line 17 of the logger.rb
file, which looks like this:
module API
class Logger
def initialize(app)
@app = app
end
def call(env)
payload = {
remote_addr: env['REMOTE_ADDR'],
request_method: env['REQUEST_METHOD'],
request_path: env['PATH_INFO'],
request_query: env['QUERY_STRING'],
x_organization: env['HTTP_X_ORGANIZATION']
}
ActiveSupport::Notifications.instrument 'grape.request', payload do
@app.call(env).tap do |response| # <-- logs say the error is here
payload[:params] = env['api.endpoint'].params.to_hash
payload[:params].delete('route_info')
payload[:params].delete('format')
payload[:response_status] = response[0]
end
end
end
end
end
My main base.rb
class looks like this:
module API
class Dispatch < Grape::API
mount API::V1::Base
end
Base = Rack::Builder.new do
use API::Logger
run API::Dispatch
end
end
I really cannot understand what id
it is talking about, and, moreover, all the other api methods work absolutely fine (post, get, put, delete).
Could you help me with resolving that issue?
回答1:
I had this issue recently too, and it turned out to be an issue of code order for me. I found the answer here.
Grape evaluates routes in order, so with two routes, /:id and /nearby_missions, it matches /:id first, making id=nearby_missions. Then it tries to coerce nearby_missions into an Integer which fails, and you get the missing id error.
You could "fix" this by adding requirements: /\d*/ to the first route (didn't test), but you're probably just better off ordering them in the order you want them to be evaluated, which is what you did.
There's not enough info in your question for me to be sure that this is also your problem, but it could well be!
来源:https://stackoverflow.com/questions/34497615/rails-grape-api-id-is-invalid-in-request-that-requires-no-id