用 Elixir 和 Phoenix 创建 RESTful API 服务的实战教程
Elixir 是一种功能强大的函数式编程语言,它运行在 Erlang 虚拟机上,具有高并发、高可用性和可扩展性的特点。Phoenix 是一个用 Elixir 编写的 Web 框架,它旨在快速构建健壮的 Web 应用程序。本文将带你通过一个实战项目,学习如何使用 Elixir 和 Phoenix 创建一个 RESTful API 服务。
环境准备
在开始之前,请确保你的系统中已经安装了以下软件:
- Elixir
- Erlang
- Node.js
- 包管理器(如 npm 或 yarn)
你可以通过以下命令安装 Elixir 和 Erlang:
sh
安装 Elixir
https://elixir-lang.org/install/
安装 Erlang
https://www.erlang-solutions.com/downloads/otp
创建新项目
使用 Elixir 的 `mix` 命令创建一个新的 Phoenix 项目:
sh
mix new rest_api
cd rest_api
这将创建一个名为 `rest_api` 的新目录,其中包含一个基本的 Phoenix 应用程序结构。
配置数据库
在这个例子中,我们将使用 PostgreSQL 作为数据库。你需要安装 PostgreSQL 和相应的 Elixir 驱动程序:
sh
安装 PostgreSQL
https://www.postgresql.org/download/
安装 Elixir PostgreSQL 驱动程序
mix archive.install hex pg
接下来,编辑 `config/config.exs` 文件,配置数据库连接:
elixir
config/config.exs
import Config
config :rest_api, RestApi.Repo,
username: "your_username",
password: "your_password",
database: "rest_api",
hostname: "localhost",
port: 5432,
pool_size: 10
确保替换 `your_username` 和 `your_password` 为你的 PostgreSQL 用户名和密码。
创建模型
在 `lib/rest_api` 目录下创建一个名为 `user.ex` 的文件,用于定义用户模型:
elixir
lib/rest_api/user.ex
defmodule RestApi.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name, :string
field :email, :string
timestamps()
end
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
end
end
接下来,创建一个名为 `repo.ex` 的文件,用于定义仓库:
elixir
lib/rest_api/repo.ex
defmodule RestApi.Repo do
use Ecto.Repo,
adapter: Ecto.Adapters.Postgres
end
创建控制器
在 `web/controllers` 目录下创建一个名为 `user_controller.ex` 的文件,用于处理用户相关的请求:
elixir
web/controllers/user_controller.ex
defmodule RestApi.Web.UserController do
use RestApi.Web, :controller
alias RestApi.User
alias RestApi.Repo
action_fallback RestApi.Web.FallbackController
def create(conn, %{"user" => user_params}) do
with {:ok, %User{} = user} <- RestApi.Repo.insert(User.changeset(%User{}, user_params)),
{:ok, user} <- RestApi.Repo.preload(user, :changeset) do
conn
|> put_status(:created)
|> put_resp_header("location", user_path(conn, :show, user))
|> render("show.json", user: user)
end
end
def show(conn, %{"id" => id}) do
user = RestApi.Repo.get(User, id)
render(conn, "show.json", user: user)
end
end
创建路由
在 `web/router.ex` 文件中,添加用户路由:
elixir
web/router.ex
defmodule RestApi.Web.Router do
use RestApi.Web, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/api", RestApi.Web do
pipe_through :api
resources "/users", UserController, only: [:create, :show]
end
end
创建视图
在 `web/views/user_view.ex` 文件中,定义用户视图:
elixir
web/views/user_view.ex
defmodule RestApi.Web.UserView do
use RestApi.Web, :view
def render("show.json", %{user: user}) do
%{
id: user.id,
name: user.name,
email: user.email,
inserted_at: user.inserted_at,
updated_at: user.updated_at
}
end
end
启动服务器
现在,你可以启动 Phoenix 服务器了:
sh
mix phx.server
访问 `http://localhost:4000/api/users`,你应该能看到一个空的用户列表。
创建用户
为了测试我们的 API,我们可以创建一个新的用户:
sh
curl -X POST http://localhost:4000/api/users
-H "Content-Type: application/json"
-d '{"user": {"name": "John Doe", "email": "john@example.com"}}'
你应该会收到一个包含新创建用户信息的 JSON 响应。
总结
通过这个实战教程,你学习了如何使用 Elixir 和 Phoenix 创建一个简单的 RESTful API 服务。你可以根据需要扩展这个项目,添加更多的功能和模型。Elixir 和 Phoenix 是构建高性能、可扩展的 Web 应用程序的优秀选择。
Comments NOTHING