Search code examples
ruby-on-railsapiruby-grape

How to get routes by Grape API


I use gem, grape for api. I tried to get api urls by the command rake grape:routes

    namespace :grape do
      desc "routes"
      task :routes => :environment do
        API::Root.routes.map { |route| puts "#{route} \n" }
      end
    end

but I got by rake grape:routes

    #<Grape::Router::Route:0x007f9040d13878>
    #<Grape::Router::Route:0x007f9040d13878>
    #<Grape::Router::Route:0x007f9040d13878>
    #<Grape::Router::Route:0x007f9040d13878>
    ...

I want something like this.

    version=v1, method=GET, path=/services(.:format)
    version=v1, method=GET, path=/services/:id(.:format)
    ...

My grape implementation is below. This works well.

    module API
      class Root < Grape::API
        version 'v1', using: :path
        format :json

        helpers Devise::Controllers::Helpers

        mount API::Admin::Services
      end
    end



    module API
      class Services < Grape::API
        resources :services do
          resource ':service_id' do
            ...
          end
        end
      end
    end

Solution

  • Try adding the the below to your Rakefile as discussed in this proposal

    desc "Print out routes"
    task :routes => :environment do
      API::Root.routes.each do |route|
        info = route.instance_variable_get :@options
        description = "%-40s..." % info[:description][0..39]
        method = "%-7s" % info[:method]
        puts "#{description}  #{method}#{info[:path]}"
      end
    end
    

    Or

    Try the below as mentioned here

    desc "API Routes"
    task :routes do
      API::Root.routes.each do |api|
        method = api.request_method.ljust(10)
        path = api.path
        puts "#{method} #{path}"
      end
    end
    

    And run rake routes

    Also there are couple of gems(grape_on_rails_routes & grape-raketasks) which are built for this purpose. You might be interested to have a look at them.