Grape API with Rails | Calling one API endpoint from another endpoint

I’m working with Grape API in my Ruby on Rails app and need help with something. I want to call a POST endpoint from Api::Users inside another endpoint that’s in Api::Orders. Both APIs are mounted under my main Api class.

class Api < Grape::API
  mount Api::Users
  mount Api::Orders
end

class Api::Common < Grape::API
  # shared methods go here
end

# handles user related endpoints
class Api::Users < Api::Common
  namespace :users do
    params do
     # user params here
    end
    post '' do
      # user creation logic
    end
  end
end

# handles order related endpoints  
class Api::Orders < Api::Common
  namespace :orders do
    params do
     # order params here
    end
    post '' do
      # Need to call the Users POST endpoint from here
      # What's the best way to do this?
    end
  end
end

What’s the proper way to make this internal API call work?

Had this exact problem last year. I skipped service classes and just threw the shared logic into helper methods in Api::Common since both APIs already inherit from it. Way simpler. Just create something like create_user_record(params) in Api::Common that returns the user object. Both your Users and Orders endpoints call it directly - no code duplication, no HTTP requests between services. It’s cleaner than spinning up separate service classes and works with your current API structure. Just make sure your helper method returns consistent data so both endpoints can handle the result the same way.

Don’t make HTTP calls between endpoints - pull that business logic into service classes instead. Create a UserService that handles user creation, then call it from both your Users and Orders endpoints. Way more efficient since you skip the network overhead and keep your code cleaner. ```ruby
class UserService
def self.create_user(params)
# user creation logic here
end
end

class Api::Orders < Api::Common
namespace :orders do
post ‘’ do
# Call the service directly
user = UserService.create_user(user_params)
# continue with order logic
end
end
end

you can also use grape’s call method to hit endpoints internally - just do Api::Users.call(env) where env is the rack environment hash. but this gets messy quick and isn’t maintainable. the service class approach mentioned above is definitely better.