Description
Hi,
I have an API which accepts requests using XML. It accepts an array of products. However for a case where there is only one product in the array, validation errors occur.
Sample request -
curl -X POST \ http://localhost:3000/v1/products \ -H 'cache-control: no-cache' \ -H 'content-type: application/xml' \ -d '<?xml version="1.0" encoding="UTF-8" ?> <admin> <product> <id>1</id> <price>100</price> </product> </admin>'
This is because when there is a single element in an array, the product will be parsed to a hash instead of an array of hash objects.
Expected - { admin: { products: [{ id: "1", price: "100" }] } }
Actual - { admin: { products: { id: "1", price: "100" } } }
the parameters are defined as
params do
requires :admin, type: Hash do
requires :products, type: Array do
requires :id, type: String
requires :price, type: String
end
end
end
Currently to overcome this, I run the following before_validation
block
before_validation do
params[:admin][:products] = [params[:admin][:products]] if params[:admin][:products].is_a?(Hash)
end
I was wondering since grape knows the request type (Array or Hash), can it convert the hash to an array before validating (similar to the before_validation block).
Notes:
Using Grape version : 1.0.0
Sample code - https://github.com/ramkumar-kr/grape-xml-error