2
votes

I'm doing an API with grape gem, in one of my services I would like to retrieve the complete URL. For example if the user does request on :

api.myapp.com/android/users.json

I would like be able to retrieve api.myapp.com/android/users.json or at least /android/users.json

class MyApp::API::Users < Grape::API

    resource :users do

        get do
            request.original_url
            # stuff ...
        end
    end
end

I tried what I know from Rails, but now it's Grape and it doesn't work :

  "error": "undefined method `original_url' for #<Grape::Request:0x00000005a78c08>"
2

2 Answers

4
votes

I wanted to do the same thing (generate absolute URIs) within my own API and after much research, I eventually gave up. There is, amazingly, no good way I can find to get the information you're looking for out of Grape—you cannot, for instance, specify a resource is "mounted" at a specific path and then retrieve that information later.

What I wound up doing in the meantime was saving the base URL (scheme, hostname and port) in a global variable at the start of each request:

before do
  # Save the base URL of the request, used by resources to build
  # their canonical URI
  Resources::base_url = request.base_url
end

and then, within each resource representer, "manually" assembling the URI using hardcoded path information:

link :self do
  RideYork::API::Resources::base_url +
    "/resources/agencies/#{represented.id}" if represented.id
end

It's a terrible hack, but I'm not aware of a better solution.

3
votes

Grape::Request is just a Rack::Request. It looks like the Rack::Request has a #url method you could try.