open_api_spex v3.2.0 OpenApiSpex.Plug.Validate View Source

Module plug that validates params against the schema defined for an operation.

If validation fails, the plug will send a 422 response with the reason as the body. This plug should always be run after OpenApiSpex.Plug.Cast, as it expects the params map to have atom keys and query params converted from strings to the appropriate types.

Example

defmodule MyApp.UserController do
  use Phoenix.Controller
  plug OpenApiSpex.Plug.Cast
  plug OpenApiSpex.Plug.Validate
  ...
end

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 MyApp.UserController do
  use Phoenix.Controller
  plug OpenApiSpex.Plug.Cast
  plug OpenApiSpex.Plug.Validate,
  render_error: MyApp.RenderError

  def render_error(conn, reason) do
    msg = %{error: reason} |> Posion.encode!()

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

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

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

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

Link to this section Summary

Link to this section Functions

Link to this function

render_error(conn, reason) View Source