jgallinari

jgallinari

Hello,

I’ve got a question regarding the use of :minimum.

I’m using

   plug OpenApiSpex.Plug.CastAndValidate, json_render_error_v2: true

for implicit validation on my Phoenix requests.

If you happen to define a schema like in:

defmodule MyAppWeb.ApiSpec.Quantity do
  alias OpenApiSpex.Schema
  require OpenApiSpex

  OpenApiSpex.schema(%{
    type: :object,
    properties: %{
      quantity: %Schema{type: :integer, minimum: 1, description: "Quantity requested"}
    }
  })
end

you may get different types of error for say a request body containing %{quantity: 0} depending on how you use this schema.

E.g. While using :oneOf like in:

defmodule MyAppWeb.ApiSpec.Items do
  alias OpenApiSpex.Schema
  require OpenApiSpex

  OpenApiSpex.schema(%{
    type: :object,
    properties: %{
        items: %Schema{oneOf: [MyAppWeb.ApiSpec.Quantity, ...]}
    }
  })
end

you will get:

[%{“detail” => “Failed to cast value to one of: no schemas validate”, “source” => %{“pointer” => “/items”}, “title” => “Invalid value”}]

But if you try to use it directly, like in:

defmodule MyAppWeb.ApiSpec.Items do
  alias OpenApiSpex.Schema
  require OpenApiSpex

  OpenApiSpex.schema(%{
    type: :object,
    properties: %{
        items: MyAppWeb.ApiSpec.Quantity
    }
  })
end

then you will get a nicer message:

[%{“detail” => “0 is smaller than inclusive minimum 1”, “source” => %{“pointer” => “/items/quantity”}, “title” => “Invalid value”}]

So, if you have multiple schemas to check in your :oneOf, your request will basically fail because it won’t match, but you won’t know why.
Can this be avoided?

Thanks

0
Post #51
moxley

moxley

Hi @jgallinari, this is a limitation of the way errors are calculated and represented for polymorphic types such as oneOf. OpenApiSpex will need to be enhanced to carry forward errors from the child type up through the parent type. Feel free to submit a feature request on the Github page: GitHub - open-api-spex/open_api_spex: Open API Specifications for Elixir Plug applications · GitHub.

0
Post #52
aloukissas

aloukissas

Is it possible to use this with Phoenix Channels to define the request and response types?

0
Post #53
mbuhot

mbuhot OP

You could define the schemas for those messages, but there isn’t any support for CastAndValidate on Channels.

Maybe the library could be extended to output an AsyncAPI spec for the channels along with an OpenAPI spec for the HTTP endpoints.

0
Post #54
— All posts loaded —