Using Phoenix to create a REST API
2 min read
- Install Elixir and Erlang
# Arch Linuxsudo pacman -S elixir
# Debiansudo apt install erlang-dev elixir
# Fedorasudo dnf install elixir erlang
# macOSbrew install elixir
$ elixir -v
Erlang/OTP 27 [erts-15.1.2] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit:ns]
Elixir 1.17.3 (compiled with Erlang/OTP 27)
- Install Hex
mix local.hex
- Install Phoenix
mix archive.install hex phx_new
- Create a new Phoenix project (since we are creating a REST API, we will skip some of the options)
mix phx.new $FOLDERNAME \ --app $APPNAME \ --database $DATABASE \ --no-install \ --no-live \ --no-assets \ --no-html \ --no-dashboard \ --no-mailer \ --binary-id
Options:
folder name
- The name of the folder where the project will be created.app name
- The name of the OTP application.database
- Specify the database adapter for Ecto. One of:postgres
- via https://github.com/elixir-ecto/postgrexmysql
- via https://github.com/elixir-ecto/myxqlmssql
- via https://github.com/livehelpnow/tdssqlite3
- via https://github.com/elixir-sqlite/ecto_sqlite3
Defaults topostgres
.
--no-install
- Skip installing dependencies.--no-live
- Skip LiveView.--no-assets
- Skip assets.--no-html
- Skip HTML views.--no-dashboard
- Skip the Phoenix Dashboard.--no-mailer
- Skip generating Swoosh mailer files.--binary-id
- Use binary UUIDs for primary keys.
Example:
mix phx.new my_app \ --app my_app \ --database postgres \ --no-install \ --no-live \ --no-assets \ --no-html \ --no-dashboard \ --no-mailer \ --binary-id
- Change directory to the project folder
cd my_app
- Change the database configuration in
config/dev.exs
import Config
# Configure your databaseconfig :my_app, My_app.Repo, username: "postgres", password: "postgres", hostname: "localhost", database: "my_app_dev", stacktrace: true, show_sensitive_data_on_connection_error: true, pool_size: 10
- Install dependencies
mix deps.get
- Create the database
mix ecto.create
- Start the Phoenix server
mix phx.server
- Visit
http://localhost:4000
in your browser to see the Phoenix welcome page.
Resources: