This is the first lesson in which we will make significant changes to our Phoenix backend. Just about every app has user accounts, often with varying degrees of complexity. For our app, we will use a standard email-password combination.
In this lesson, we create the User model and add API endpoints so our frontend can create and update an account. We're also going to create and run a migration to update our database.
The first thing we need to do is create a user model and controller, which we cover in more detail shortly. Creating these components is a standard part of most Phoenix applications so there are helpers available to generate the boilerplate.
To view a list of the generators, and other mix tasks available to us, run mix -h:
$ mix -hmix # Runs the default task (current: "mix run")...mix new # Creates a new Elixir projectmix phoenix.digest # Digests and compress static filesmix phoenix.gen.channel # Generates a Phoenix channelmix phoenix.gen.html # Generates controller, model and views for an HTML based resourcemix phoenix.gen.json # Generates a controller and model for a JSON based resourcemix phoenix.gen.model # Generates an Ecto modelmix phoenix.gen.secret # Generates a secretmix phoenix.new # Create a new Phoenix v1.1.3 applicationmix phoenix.routes # Prints all routesmix phoenix.server # Starts applications and their servers...There are many tasks but for now we'll focus only on the Phoenix ones. Since we're building a JSON API, let's try the phoenix.gen.json generator. This will cause an error but the errors in Phoenix are quite helpful and will tell you what you're missing.
$ mix phoenix.gen.json** (Mix) mix phoenix.gen.json expects both singular and plural namesof the generated resource followed by any number of attributes: mix phoenix.gen.json User users name:stringLet's try it again but this time for a user with an email, encrypted password, and a username:
$ mix phoenix.gen.json User users email:string encrypted_password:string \ username:stringYou will get output similar to the following.
* creating web/controllers/user_controller.ex* creating web/views/user_view.ex* creating test/controllers/user_controller_test.exs* creating web/views/changeset_view.ex* creating priv/repo/migrations/20160406190555_create_user.exs* creating web/models/user.ex* creating test/models/user_test.exsAdd the resource to your api scope in web/router.ex: resources "/users", UserController, except: [:new, :edit]Remember to update your repository by running migrations: $ mix ecto.migrateThis generates a number of different files and instructions for setting up our user. We'll take this opportunity to discuss some of the files and their purpose within our project.
In the output from our generator the very first file is web/controllers/user_controller.ex.
Controllers are responsible for doing most of the work for a given request. When our application receives a request it will use the router to direct the request to a controller and a specific function. For example, when someone arrives at your website, you need to determine whether or not that person is a logged-in user. The controller is where your app will check with the database to determine how to handle the current connection.
If you come from a Rails background, the concept of a controller should be familiar.
Controllers are a big topic and will be used frequently so if you do not understand them now, you will after we use them a little more.
The second file created is web/views/user_view.ex, our view. If you're familiar with other frameworks, you might be expecting the view to be HTML files but that's not necessarily the case. In Phoenix, our view is a module containing functions for rendering data into a consumable format which can be either JSON or HTML. Since we're building a JSON API, it will respond with JSON.
Our layout and other HTML assets are referred to as templates in Phoenix. These templates can be used by our views to generate the final HTML or JSON.
By default our generated boilerplate includes our password in the JSON response. Open the user view and update the render/3 function by removing the encrypted_password reference:
... def render("user.json", %{user: user}) do %{id: user.id, email: user.email, username: user.username} endA migration is a set of changes we want applied to our database schema, such as adding new tables and columns or updating existing ones. When we look at the generated migration we'll see it is creates a new database table for "users" and add a number of column for each of the three fields we supplied the generator. The migration that was generated for us can be found at priv/repo/migrations/20160406190555_create_user.exs; it's important to note that your file will almost certainly be different since migrations rely on timestamps at the beginning of the file for uniqueness.
Let's open our migration make a few changes. For starters we want to make sure that users enter a valid username and email for an account to be created. We also want to make sure that email addresses are unique.
defmodule PhoenixChat.Repo.Migrations.CreateUser do use Ecto.Migration def change do create table(:users) do add :username, :string, null: false add :email, :string, null: false add :encrypted_password, :string timestamps end create unique_index(:users, [:email]) create unique_index(:users, [:username]) endendThe first change we made was to add null: false to both :username and :email, this tells the database that null values are not to be accepted. In other words, a value is required. The second change we made was to add create unique_index/2. A unique index is to make sure a username and email is only used once.
Next up is our model, found in web/models/user.ex. In Phoenix, models are modules containing functions for working with our data's schema and the struct that contains its values. We're already familiar with structs and if you've worked in another framework, you're probably already familiar with a schema, but in case you aren't, a schema is describes the different fields of our table and it is defined within the schema block. You can think of it as a way to enforce a particular structure.
Let's open our model and add support for the unique index we added into our migration.
defmodule PhoenixChat.User do use PhoenixChat.Web, :model schema "users" do field :email, :string field :encrypted_password, :string field :username, :string timestamps end @required_fields ~w(email encrypted_password username) @optional_fields ~w() def changeset(model, params \\ :empty) do model |> cast(params, @required_fields, @optional_fields) |> validate_format(:email, ~r/@/) |> validate_length(:username, min: 1, max: 20) |> update_change(:email, &String.downcase/1) |> unique_constraint(:email) |> update_change(:username, &String.downcase/1) |> unique_constraint(:username) endendWe've made some changes to our changeset/2 function. A changeset is a function that validates and transforms data into a format the database is expecting. For now we'll focus on a single changeset function but it's possible, and common, to use different functions for different situations. You will see some of these later on.
Let's look at the individual changeset changes we made. With validate_format(:email, ~r/@/) we check the email field using a regular expression to ensure it contains an @. The second change we introduced is validate_length(:username, min: 1, max: 20) to ensure a username is at least one character and at most 20.
Finally, the last change ties in with the index we added to our migration: unique_constraint(:email). With the unique_constraint/3 function we can ensure the email is not already in use, thanks to our unique_index. We also do the same for :username.
The last piece to our puzzle is the router, found in web/router.ex. The output from our generator directed us to make a change, open the router and update it accordingly.
When our frontend makes a request to our API, the first place it hits is the router. This router sends that request to the right place so the request can be handled properly.
defmodule PhoenixChat.Router do use PhoenixChat.Web, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", PhoenixChat do pipe_through :browser # Use the default browser stack get "/", PageController, :index end scope "/api", PhoenixChat do pipe_through :api resources "/users", UserController, except: [:show, :index, :new, :edit] endendWith this change we are telling Phoenix that any requests to /users, except :new and :edit should be sent to our UserController. We're also removing :index and :show since we don't want random users to be able to see our list of users, but for some apps, you'd want this behavior.
There are a few things to notice in this file. There are two pipeline functions and two scope functions. Since we are creating an API we won't be using the :browser pipeline, but you can see that it accepts HTML and has a series of plugs that apply useful transformations to your connection. For our application we'll focus on the :api pipeline.
Within the code we just wrote, you see that any connection that hits the /users route is "piped through" the :api pipeline. Be wary of adding plugs to the API pipeline, because if you do, that transformation will be applied to every incoming connection. This is a very powerful tool and should be used with discretion.
The scope allow us group different routes together under a common base path. In our case, we want to direct anyone hitting the /api/users route to the UserController.
Finally, we see the resources/4 function which takes our path, controller, and options. Within the Phoenix router, resources/4, is a handy function that takes care of generating all of the standard routes for us. We can see a list of the routes resources/4 has created by running mix phoenix.routes in our command line:
$ mix phoenix.routesIf you run the above command you should see something like this (if you do not see these, make sure your app has been compiled):
page_path GET / PhoenixChat.PageController :indexuser_path POST /api/users PhoenixChat.UserController :createuser_path PATCH /api/users/:id PhoenixChat.UserController :update PUT /api/users/:id PhoenixChat.UserController :updateuser_path DELETE /api/users/:id PhoenixChat.UserController :deleteIn later sections we'll explore creating individual routes without the resources/4 helper.
Once we've updated our migration we should create the database and run the migration. Running our migration will apply the changes to our database:
$ mix ecto.create$ mix ecto.migrateIf this isn't your first time through the tutorial, you might need to run mix ecto.drop first to drop the old database.