Rails: Grape swagger array in response attribute

From FVue
Jump to: navigation, search

Problem

Using Grapi API, we want to describe an api response containing an object (e.g. User) with an attribute params containing an array of name/value pairs:

module API
  class User < Grape::Entity
    expose :email
    expose :params
  end
  class Param < Grape::Entity
    expose :name
    expose :value
  end
end

How does one do? We've tried: is_array, present_collection, etc. but can't get it to work.

Can't get it to work with the documentation (https://rubydoc.info/github/intridea/grape-entity/Grape/Entity#expose-class_method), since they're using an array `items' at the main level, but we want an array attribute at a secondary level.

Environment

  • rails-7.0
  • grape-1.7.1

Solution

Credits: https://stackoverflow.com/questions/75230970/rails-grape-swagger-array-example-value-is-showing-as-an-object#76870053

module API
  class User < Grape::Entity
    expose :email
    expose(:params, documentation: { type: API::Param, using: API::Param, is_array: true }) do |uu|
      uu.params
    end
  end
 
  class Param < Grape::Entity
    expose :name
    expose :value
  end
end

This produces Swagger UI documentation, with a response description like this - params being an array :)

{
  "email": "string",
  "params": [
    {
      "name": "string",
      "value": "string"
    }
  ]
}


Comments

blog comments powered by Disqus