Sending a single element in an array using XML format fails with the request being invalid
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 10k
- Forks
- 1.2k
- Avg merge
- 14h 38m
- Merged PRs (30d)
- 92
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked grape-xml-error sample code and reproduce the single-product XML request against the shown params definition. Trace how the XML body is represented before validation and compare it with the existing before_validation workaround. Done means a single product is accepted as an array element and the request validates without that workaround.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- api
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100