Sergio Trejo
Sergio Trejo

Reputation: 633

Rails API Get with parameters

What is the right way to create a service receiving parameters?

Currently I´m working on API on ruby on rails:

module Api
module V1
    class UsersController < ActionController::API
        def  index
            users = User.order('created_at');
            render json: {status: 'Success', message: 'Loaded users', users: users},statu: :ok
        end
        def show
            user = User.find(params[:id])
            render json: user, statu: :ok
        end
    end

end
end

When I try to get user with id = 1 using this url(localhost:3000/api/v1/users/1) on postman works great I get only one record as expected, but when I set parameter using postman (creates this url localhost:3000/api/v1/users?id=1)and I get back all records.

I have those routes:

Rails.application.routes.draw do
  namespace 'api' do
    namespace 'v1' do   
        resources :users
        resources :messages
        resources :conversations
    end

  end
end

Do I have to create other route for this case?

Upvotes: 1

Views: 5924

Answers (1)

jvillian
jvillian

Reputation: 20263

/api/v1/users/1

is not the same as

/api/v1/users?id=1

As can be seen from rake routes:

    api_v1_users GET    /api/v1/users(.:format)                 api/v1/users#index
                 POST   /api/v1/users(.:format)                 api/v1/users#create
 new_api_v1_user GET    /api/v1/users/new(.:format)             api/v1/users#new
edit_api_v1_user GET    /api/v1/users/:id/edit(.:format)        api/v1/users#edit
     api_v1_user GET    /api/v1/users/:id(.:format)             api/v1/users#show
                 PATCH  /api/v1/users/:id(.:format)             api/v1/users#update
                 PUT    /api/v1/users/:id(.:format)             api/v1/users#update
                 DELETE /api/v1/users/:id(.:format)             api/v1/users#destroy

api/v1/users/1 will route to api/v1/users#show. And api/v1/users?id=1 will route to api/v1/users#index with params: {'id'=>'1'}.

So, the routing is happening exactly as it is supposed to.

I'm not sure what 'other route' you would create. But you could do:

module Api
  module V1
    class UsersController < ActionController::API

      def index
        if params[:id]
          user = User.find(params[:id])
          render json: user, status: :ok
        else
          users = User.order('created_at');
          render json: {status: 'Success', message: 'Loaded users', users: users}, status: :ok
        end
      end

      def show
        user = User.find(params[:id])
        render json: user, status: :ok
      end

    end

  end
end

But, that's really ugly and terrible.

Better to just format your URL correctly in iOS(swift).

Upvotes: 3

Related Questions