Elixir: Building a REST API using Phoenix Framework Part I

Augusto Cezar
Red Ventures Brasil - Tech
7 min readJun 8, 2020
Photo by Zan on Unsplash

What is Elixir and Phoenix Framework ?

Elixir it’s a pure dynamic functional language and as any kind of functional language it does have support for First-Class Functions, Currying, Pattern Matching and data is treated as immutable. It runs on top of ErlangVM (BEAM), to give you some context is the same virtual machine that Whats App Server from Facebook runs on top.

Phoenix it’s a Framework that gives you everything you need to start your project. Requires almost zero configuration, which means you don’t need to worry about setup a library to interact with database layer, router to handle the requests or even have to configure a test runner. Also, it does have a Command Line Interface integrated to generate Migrations, Schemas, Controllers and Views.

Getting Started

As requirement to you follow this guide, you must have Elixir with Mix tool installed. In case don’t have it, you can follow this guide of how install in your machine.

Another dependency but this time not required, it’s docker with docker-compose tool. This dependencies are not required because they will be used to run the PostgreSQL database instance, so you can simply run the instance directly from your machine instead. The following image refers to docker-compose example file for postgres instance.

docker-compose.yml file example for postgres instance

Installing Phoenix Framework CLI

After you’ve completed the installation of Elixir and Mix, now let’s install Phoenix CLI which is a Command Line tool for help scaffold Phoenix framework projects. To install it’s pretty simple you’ll just need open an terminal window anywhere in your machine and type the following command

mix local.hex && mix archive.install hex phx_new 1.4.16

The command above will install hex, or updates if you already have it installed and finally get all the Phoenix CLI related dependencies globally.

Creating an Web API Based Project

To create Web API based project, you can simply type the following command below from a terminal window where you wants to that the project gets created.

mix phx.new [project_name] --no-html --no-webpack

The CLI tool, it will create a Phoenix WebAPI based project the flags --no-html and --no-webpack just means that we don’t want to our project comes up with webpack or any template engine, by default Phoenix will configure with these features if you don’t specify any of those flags. If you wish, visit this guide to read about all available commands that Phoenix CLI comes up.

After the project is created, the Phoenix CLI will prompt you if the dependencies should be fetched and installed automatically in case you prefer not to it’s also possible do it later. Running the following command.

mix deps.get && mix deps.compile

My Hero Academy API

Well, i am an bigger fan of Anime and you probably already have seen the Pokemon API (Poke API), for those who don’t seen and have curiosity it can be found here. So in this guide, i am going to make a clone, but following with Boku No Hero Anime Theme instead of Pokemon.

Folder Structure From Project

After the project have been created and all dependencies installed. Phoenix CLI give us the following folder structure.

project structure folder generated from phoenix framework

The config folder is where all the configuration stuff related to project is placed like database credentials or any sort of configuration required for a third-party library for instance.

The lib folder is where all source-code like Controller, Repository, Schema (Model) and Views lives. Notice that some folders have a prefix with _web on front of it, Phoenix use this to separate the domain logic from the application controller part.

And finally the test folder, where all the tests related from the application is placed.

The First Route and Controller

To create our first Route and Controller, Phoenix CLI provide to us a command that generate the Schema, Migration, Repository, Controller and View. The command is phx.gen.json also there is phx.gen.html, the main difference between those two, is that the first one use JSON to render and the second use the template engine built-in into Phoenix Framework. The syntax can be written as the following command below:

mix phx.gen.json ContextName schema_name tb_name [ attr_name:type ]

Context in phoenix means a group of related functionality, to understand better this concept, you can read this guide here.

The entity will contain the following attributes first_name, last_name and nick_name with type string. To create the resources for that you will just need to type the following command inside of the Phoenix Application.

mix phx.gen.json Heros Hero tb_heros first_name:string last_name:string nick_name:string

Registering our routes

Our route is still missing one thing which is, register the route itself. To do that, you can take a look at router.ex file inside of lib/project-name_web folder. At your router.ex, you should include the following line:

resources “/heros”, HeroController, except: [:new, :edit]

This way Phoenix will be able to know what handler call when you hit the /heros endpoint and finally your controller should seems similar to mine.

Router file example

Inside of Controller there is a naming convention for the handler functions, but of course it’s not required one, which is basically.

GET :index - ideally for list all resources.
POST :create - ideally for create an resource
GET :show - ideally to get an resource by given an id
PUT :update - ideally to update an resource by a given an id
DELETE :delete - ideally to deletes an resource by given an id
GET :new - ideally to show a form to create an resource
GET :edit - ideally to show a form to edit an given resource

The “resources” is a special function that Phoenix allow us to use, as first argument is the path, second argument is Controller itself and finally on third you got some optional parameters, on our example, except means that we don’t want to some special methods, in the case the new and edit one.
If you wish have more a grain control over your routes, it’s possible register each one separately. You can read more about here.

After you’ve registered that route, it’s possible to check it, to do that just type the following command in the terminal inside of Phoenix application folder.

mix phx.routes

Migrations

There’s still one thing that we need to do before we can start the server and hit that endpoint, which is create the database and run the migrations. Phoenix uses under-hood Ecto to deal with all the SQL part. Ecto provides to us a Command Line Interface (CLI) to interact with database, the commands you’ll need to know are:

create - used to create the database if doesn’t already exists.
drop - used to drop the database.
setup- used to create the database and run all the migrations needed.
migrations - list all the migrations that already have been performed.
migrate - used to setup only the migrations that are needed.

So, to setup the database and all migrations, you will just need to run the following command in terminal inside of the Phoenix application folder:

mix ecto.setup

Running the Server

Finally to start the server it’s pretty simple, you will just need to run the following command inside of the Phoenix application:

docker-compose up -d && mix phx.server

By default according with the environment Phoenix will start the server at port 4000 in development mode and in production will be at port 80. It’s possible to change it through port configuration option. Also it’s possible make others configurations such as database environment, HTTPS Support or JWT Secret Keys for instance.

Notice that at config folder there are multiple files, one for each environment the explanation it’s pretty simple and straightforward:

dev.exs - the development configuration file
prod.exs - the production configuration file
test.exs - the testing configuration file

Configuration file example

Requests and Response Example

After the server it’s up and running we can make a request example to test it. The following image corresponds to a Request and Response respectively with purpose of creates an hero resource.

Request and Response Example

Conclusions

The main goal of this article was to demonstrate the very basics of using Phoenix Framework. There are still a bunch of topics to cover such as how to handle with authentication, associations, paginate the results for instance. I intend to cover these topics later in a separately article. If you wants to check the source code directly from repository, you can click here.

If you’ve any doubt or trouble, please feel free to leave a comment or reach me out through a private message, i will do my best to answer you all.

References

[1]: Installing Elixir with Mix Tool. https://elixir-lang.org/install.html
[2]: PokeApi Project. https://pokeapi.co/
[3]: Phoenix Router Documentation. https://hexdocs.pm/phoenix/Phoenix.Router.html

--

--