View Source OpenApiSpex.Plug.CastAndValidate (open_api_spex v3.21.2)

Module plug that will cast and validate the Conn.params and Conn.body_params according to the schemas defined for the operation. Note that when using this plug, the body params are no longer merged into Conn.params and must be read from Conn.body_params separately.

The operation_id can be given at compile time as an argument to init:

plug OpenApiSpex.Plug.CastAndValidate,
  json_render_error_v2: true,
  operation_id: "MyApp.ShowUser"

For phoenix applications, the operation_id can be obtained at runtime automatically.

defmodule MyAppWeb.UserController do
  use Phoenix.Controller
  plug OpenApiSpex.Plug.CastAndValidate, json_render_error_v2: true
  ...
end

Casted params and body params are always stored in conn.private. The option :replace_params can be set to false to avoid overwriting conn :body_params and :params with their casted version.

plug OpenApiSpex.Plug.CastAndValidate,
  json_render_error_v2: true,
  operation_id: "MyApp.ShowUser",
  replace_params: false

If you want customize the error response, you can provide the :render_error option to register a plug which creates a custom response in the case of a validation error.

Example

defmodule MyAppWeb.UserController do
  use Phoenix.Controller
  plug OpenApiSpex.Plug.CastAndValidate, render_error: MyApp.RenderError
  ...
end

defmodule MyApp.RenderError do
  def init(opts), do: opts

  def call(conn, reason) do
    msg = Jason.encode!(%{error: reason})

    conn
    |> Conn.put_resp_content_type("application/json")
    |> Conn.send_resp(400, msg)
  end
end