How to handler required params on controllers

Hi everyone!

For example, when I need to validate that my required params are informed, that’s how I do:

def index(conn, %{"params1" => params1, "params2" => params2} = _params) do
  search_return =
    MyContext.get_by_params1_and_params2(params1, params2)

  conn
  |> put_status(:ok)
  |> render("index.json", %{search_return: search_return})
end

def index(conn, _params) do
  conn
  |> put_status(:bad_request)
  |> put_view(AppWeb.ErrorView)
  |> render("default_error.json",
    message: "The params params1 and params2 are both required"
  )
end

I would like to know if you handle this in a different way. Any suggestions?

Hello and welcome,

It’s very common to have multiple function heads to process different cases.

But sometime, You want better validations, and that’s what changeset are made for.

You could pass the params to a context function, get the data validated by the changeset, and have {:ok, …} or {:error, changeset}

Even if this does not imply db calls.

1 Like