Checking REST API Parameters in Rails

I am writing a Rails application that has only a REST API (no web interface or such). I need to check if requests are being executed with the correct parameters and return different error codes if not. For example, all API endpoints require user_access_token and client_id. Some other endpoints require various other parameters.

In all controllers, I have code that performs this check, but the code is duplicated, and there are many if conditions that can be extracted and put somewhere else. So I thought about adding before_filter to my ApplicationController , which performs this check. I defined a hash that contains the entire endpoint to display the required_pairs, and this filter is triggered before the control transfers to the actual controller in question.

But for some endpoints, it becomes a little complicated because some parameters are required if some other parameters are present, and in some cases one of two parameters is required. So now I am wondering if there is a better way to do this.

Am I doing it right? Is there a better / standardized way to do this? Or some kind of stone that does this?

+4
source share
1 answer

I would need to see some code in order to understand the context. But in essence it sounds like you have a basic ApplicationController from which all of your other controller is inherited. The thing that is changing is the parameters you are expecting (with the exception of user_access_token and client_id, which you must always provide). Since you use inheritance, you can define a method in your ApplicationController that contains a list of the parameters you expect, and then override the method in your subclasses to verify that other parameters are added. Your base controller will be responsible for the actual validation, but subclasses will be able to override the required parameters.

 class ApplicationController < ActionController::Base before_filter :validate_params protected def required_params [:user_access_token, :client_id] end def validate_params unless (require_params - params.keys).count.zero? # do something end end end class AnotherController < ApplicationController protected def required_params p = super + [:email, :password] p = p + [:another, :and_another] if some_condition? p end end 

Essentially, you would let the subclass decide whether to add any additional required parameters. Of course, I don’t know what your exact context is, but I hope this helps you in the right direction. Do some research on polymorphism when you get a chance :-)

+5
source

Source: https://habr.com/ru/post/1499710/


All Articles