Skip to main content

API params validation in Rails app

Rails • Asked by Alex Musayev

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:

How about ActiveModel::Validations?

class MyValidator
  include ActiveModel::Validations

  attr_reader :data

  validates_presence_of :name

  def initialize(data)
    @data = data || {}

  def read_attribute_for_validation(key)
end '').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

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.