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.

Reply

I've implemented it with JSON Schema. So far, it works pretty fine. And here are few more references I found:

Reply

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

Reply

I've implemented a gem for that purpose. You can have a look if you want here: https://github.com/felipefava/request_params_validation

Reply

A very excellent post. I am thankful for you. I have noticed a lot of approaches after attending your post.

Reply

Grape APIs are Rack applications that are created by subclassing Grape::API . ... You can define validations and coercion options for your parameters using ...

Reply
Join the discussion
Create an account Log in

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

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

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