ruby elixir
这篇文章将展示如何使用Elixir和Phoenix框架构建REST API。 重点将是为持久化到Postgres数据库后端的模型提供CRUD(创建,读取,更新,删除)端点。 我应该警告你; 这是一个简单的例子。 但是,希望它可以帮助您在Elixir和Phoenix的旅程中前进。
附带说明 :我来自使用Akka和Scala构建REST API。 与Akka相似,Elixir具有Erlang的基础。 我喜欢异步处理的Erlang模型。 一个人怎么可能不是? 好吧,分布式异步系统很难调试,但是我离题了。 就像我说的那样,我仍然喜欢这种模型,因为它可以扩展。 很高兴回到Elixir中的松散类型语言。
一,安装要求
- 安装Elixir(详细信息:http://elixir-lang.org/install.html。请按照以下说明进行操作,因为其中包含Erlang。我使用自制软件进行安装)
-  通过在终端中运行来安装Hex: 
 Elixir Hex安装mix local.hex
-  安装Phoenix: mix archive.install https://github.com/phoenixframework/archives/raw/master/phoenix_new.ez
- 也许安装Node.js作为资产管理的依赖项。 请参见http://www.phoenixframework.org/docs/installation上的“ node.js”部分
- 安装Postgres。 我在Mac上使用Postgres.app。 确保postgres用户的密码为postgres
其次,让我们建立
-  在终端窗口中,通过发出以下命令来创建基准应用程序: 
 新的Phoenix Framework应用程序mix phoenix.new api_spike根据需要命名api_spike。 可能会要求您安装依赖项。 我说是! (参考:上面第一部分的步骤4) 
-  进入新的api_spike目录: cd api_spike
-  创建用于该应用程序的Postgres数据库: mix ecto.create背景:如果这不起作用,请检查conf / dev.exs文件中的Postgres设置。 默认连接使用用户名postgres和密码postgres 。 请参阅上面的步骤5。 
-  生成一个模型并免费获得大量其他东西: mix phoenix.gen.json User users fullname:string email:string age:integer注意: phoenix.gen任务正在指定json。 如果使用phoenix.gen.html,也可以构建HTML视图。 当我第一次尝试Phoenix时,这让我很困惑。 
-  打开web / router.ex文件,取消注释api范围,并为上一步中新生成的UserController添加新行。 它看起来应该像这样: 
 凤凰REST APIscope "/api", ApiSpike dopipe_through :apiresources "/users", UserController, except: [:new, :edit]end
- 通过发出以下命令更新数据库: - mix ecto.migrate
-  做完了 启动凤凰! mix phoenix.server
第三,尝试一下
现在,我们可以进行一些调用以执行CRUD操作,例如create:
curl -H "Content-Type: application/json" -X POST -d '{"user": {"fullname": "Todd", "email": "phoenix@apiexample.com", "age": 19}}' http://localhost:4000/api/users现在读取:
curl -H "Content-Type: application/json" http://localhost:4000/api/userscurl -H "Content-Type: application/json" http://localhost:4000/api/users/1更新:
Phoenix框架更新REST调用
curl -H "Content-Type: application/json" -X PUT -d '{"user": {"fullname": "Not Todd", "email": "phoenix@apiexample.com", "age": 43}}' http://localhost:4000/api/users/1最后,删除:
curl -H "Content-Type: application/json" -X DELETE http://localhost:4000/api/users/1吃喝玩乐跳舞
我确实将此帖子称为“快速入门”。 旨在帮助您开始使用Phoenix构建REST API,并更轻松地使用Elixir。 如果您需要更多详细信息,只需在Twitter上与我联系或在下面发表评论。
翻译自: https://www.javacodegeeks.com/2016/02/build-crud-rest-apis-elixir-phoenix-quick-start.html
ruby elixir