Search code examples
rubyapiruby-grapegrape-apiyo

How to extract data from a get request with Ruby Grape


I'm experimenting with grape and Ruby by trying to make a Yo API callback function.

I can get simple examples up and running like this . . .

resource :loc do
    get ':loc' do        
        params.to_yaml
    end
end

How would I go about extracting username and x and y coordinates into separate ruby variable given a callback with the following format?

http://yourcallbackurl.com/yourendpoint?username=THEYOER&location=42.360091;-71.094159

When the location data is screwed up . . .

--- !ruby/hash:Hashie::Mash
username: sfsdfsdf
location: '42.360091'
"-71.094159": 
route_info: !ruby/object:Grape::Route
  options:
    :prefix: 
    :version: v1
    :namespace: "/loc"
    :method: GET
    :path: "/:version/loc/:loc(.:format)"
    :params:
      loc: ''
    :compiled: !ruby/regexp /\A\/(?<version>v1)\/loc\/(?<loc>[^\/.?]+)(?:\.(?<format>[^\/.?]+))?\Z/
version: v1
loc: toto
format: txt

Solution

  • This is how Rack::Utils works. Default params separators are "&" and ";" (its totally legal according to HTTP standard). So you have to parse query string by yourself here.

    location = Rack::Utils.parse_nested_query(env['QUERY_STRING'], '&')['location']
    coordinates = location.split(';')
    

    UPD: typo with hash key fixed.