grape icon indicating copy to clipboard operation
grape copied to clipboard

Ability to describe multiple success entities

Open Koilanetroc opened this issue 3 years ago • 6 comments

Sometimes it's necessary to return different entities depending on internal business logic. It would be nice to be able to document all possible success entities. Like with failure method but without status codes.
Something like this:

desc "List of users" do
  success [Entities::Customer, Entities::Client]
  is_array true
end

Koilanetroc avatar Aug 11 '22 15:08 Koilanetroc

I dislike APIs that return two different types of things, but it's a matter of preference, so the proposal makes sense. Want to give it a try?

dblock avatar Aug 12 '22 16:08 dblock

Yeah, I'd like to try. Will send a pr when it's ready

Koilanetroc avatar Aug 13 '22 03:08 Koilanetroc

Well, after some research I realised that limitation was from OpenAPI 2.0. It does not support multiple response schemas per status code. There is a branch in grape-swagger for oapi-3, but it's abandoned, so there is no way to add this functionality for now.

Koilanetroc avatar Aug 25 '22 01:08 Koilanetroc

But is it a grape-swagger problem or a grape problem? Can we do one without the other?

dblock avatar Aug 25 '22 13:08 dblock

Grape-swagger actually is able to accept an array in success section, but then in response_object hash is used for storing entities where response code is a key. So if you pass an array of multiple entities with same response codes like this:

  desc 'user' do
    success [{ code: 200, model: Entities::User }, { code: 200, model: Entities::Admin }]
  end

In swagger you'll see only Entities::Admin as a result for 200. If you pass entities with different codes they will appear in swagger correctly. As I said before, there is a limitation from openapi 2.0. It also uses response code as a key:

  "paths": {
    "/user": {
      "get": {
        "description": "user",
        "produces": [
          "application/json"
        ],
        "responses": {
          "200": {
            "description": "user",
            "schema": {
              "$ref": "#/definitions/User"
            }
          }
        },
        "tags": [
          "user"
        ],
        "operationId": "getUser"
      }
    }
  }

And you can't pass an array to "200" key, this option is available only in openapi 3

Koilanetroc avatar Aug 27 '22 13:08 Koilanetroc

Looks like a bug in grape-swagger, which should raise an error here, short of supporting openapi 3.

For Grape though I don't see a reason not to implement it. If someone ends up using it and swagger has a problem with it, 🤷

dblock avatar Aug 28 '22 15:08 dblock