All threads / API params validation in Rails app

Ask A Question

Notifications

You’re not receiving notifications from this thread.

API params validation in Rails app

Alex Musayev asked in Rails

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 || {}
  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

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,629+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.