James Black James Black - 1 year ago 37
reST (reStructuredText) Question

Phoenix error adding user to REST service

I made this call:

curl -X POST -H "Content-Type: application/json" -d '{
"user": {
"email": "[email protected]",
"first_name": "Léo",
"last_name": "Hetsch",
"password": "notsosecure",
"username": "test1"
}
}' "http://localhost:4000/api/users"


And on the server I get:

[info] POST /api/users
[debug] Processing by VirtualTeams.UserController.create/2
Parameters: %{"user" => %{"email" => "[email protected]", "first_name" => "Léo", "last_name" => "Hetsch", "password" => "[FILTERED]", "username" => "test1"}}
Pipelines: [:api]


This is in my user.ex file:

schema "users" do
field :email, :string
field :password, :string
field :first_name, :string
field :last_name, :string
field :api_token, :string
field :username, :string

timestamps()
end

@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:email, :password, :first_name, :last_name, :api_token, :username])
|> validate_required([:email, :password, :first_name, :last_name, :api_token, :username])
|> unique_constraint(:email)
|> unique_constraint(:username)
end

def create(params) do
changeset(%VirtualTeams.User{}, params)
|> put_change(:password, hashed_password(params["password"]))
|> put_change(:api_token, :base64.encode(:crypto.strong_rand_bytes(24)))
|> VirtualTeams.Repo.insert()
end

defp hashed_password(password) do
Comeonin.Pbkdf2.hashpwsalt(password)
end


Just to verify I did:

mix ecto.migrate

00:40:35.074 [info] Already up


Why am I getting an error?

UPDATE:
Forgot the error:

{"error":"error creating user"}


In my controller I have this code, which has the error:

def create(conn, %{"user" => user_params}) do
case User.create(user_params) do
{:ok, user} ->
conn
|> put_status(:created)
|> render("user.json", user: user)
{:error, changeset} ->
conn
|> put_status(:bad_request)
|> json(%{error: "error creating user"})
end

Answer Source

The problem appears to be that :api_token is required by changeset/2, but not present in the params from the request.

In general, it's useful to get a look at the changeset in {:error, changeset} (returned by create/1 in this case) in order to see what validation failed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download