Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 479
Hiromu Masuda Avatar asked Jun 20 '17 15:06

Hiromu Masuda


People also ask

How do I find routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

What is grape API?

What is Grape? Grape is a REST-like API framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs.

What is grape swagger?

The grape-swagger gem provides an autogenerated documentation for your Grape API. The generated documentation is Swagger-compliant, meaning it can easily be discovered in Swagger UI. You should be able to point the petstore demo to your API.


1 Answers

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.

like image 185
Pavan Avatar answered Oct 08 '22 21:10

Pavan