API params validation in Rails app
Hey guys!
I'm wondering, what could be a good and scalable way to validate if API request is well formed, before processing it. Rails has strong params for that, but I have a case when an API endpoint suppose to receive relatively complex chunk of data. About 20 params, plus couple of arrays of nested objects.
I was thinking about using JSON Schema for that. The good thing is that it will allow to do more validation for HTTP request payload. Like data types, string lengths, mandatory params, etc. More than what ActionController::Parameters
can do.
But I would still appreciate to hear about alternatives, may be libraries or best practices people in Ruby world use to solve this.
I've implemented it with JSON Schema. So far, it works pretty fine. And here are few more references I found:
- JSON API implementation for Ruby: http://jsonapi-rb.org. Never tried, but I think I will take a look at that. They have a generic Ruby library with Rails and Hanami integration.
- https://github.com/nicolasblanco/rails_param - Parameter Validation & Type Coercion for Rails (gem)
- http://gilesbowkett.blogspot.se/2015/05/strong-parameters-are-weak-schema.html - Strong Parameters Are A Weak Schema - an opinion on Rails strong params
How about ActiveModel::Validations
?
class MyValidator
include ActiveModel::Validations
attr_reader :data
validates_presence_of :name
def initialize(data)
@data = data || {}
end
def read_attribute_for_validation(key)
data[key]
end
end
MyValidator.new(name: '').valid? # => false
I couldn't find the etiquette guide about external links, but you can find more info about a nested case with Rails integration and tests here
I've implemented a gem for that purpose. You can have a look if you want here: https://github.com/felipefava/request_params_validation
A very excellent post. I am thankful for you. I have noticed a lot of approaches after attending your post.