Reputation: 2572
I am writing a Sinatra-based API, and want to protect certain endpoints with an API key, validating the key before the route is processed.
I understand why throwing an error in the before
block doesn't work, because the begin
/rescue
statements haven't been called yet, however I want a JSON response to be sent back to the client with the error message as a JSON object.
How would I do this?
namespace '/v1/sponser/:key' do
before do
if APIHelper.valid_key?(params[:key]) == false
throw 'Error, invalid API key'
# is it possible to return a JSON response from the before statement here?
end
end
get '/test' do
begin
json status: 200, body: 'just a test'
rescue => error
json status: 404, error: error
end
end
end
Upvotes: 1
Views: 1469
Reputation: 23
You can use halt
method to return response with specific code, body and headers. So it looks like this:
before do
halt 401, {'Content-Type' => 'application/json'}, '{"Message": "..."}'
end
It looks sloppy so you can just redirect to another url, that provide some service
Upvotes: 0
Reputation: 106972
I would consider using halt
:
before do
unless APIHelper.valid_key?(params[:key])
halt 404, { 'Content-Type' => 'application/json' },
{ error: 'Error, invalid API key' }.to_json
end
end
get '/test' do
json status: 200, body: 'just a test'
end
Upvotes: 2