备注:
官方提供的脚手架工具,我们可以直接使用,生成代码,同时需要nodejs 环境配置(比较简单,参考
相关资料即可)
1. 安装脚手架
mix . archive.install https://github.com/phoenixframework/archives/raw/master/phx_new.ez
2. 生成基本项目
mix . phx.new hello
完整代码参考github 项目
https://github.com/rongfengliang/phoenix-rest-demo
3. 代码说明
备注:代码添加了一个简单的restdemo,参考web/controllers/democontroller.ex
a. 初始化项目处理:
a. mix deps.get
b. mix ecto.create && mix ecto.migrate
c. npm install
d. mix phoenix.server or mix phx.server
b. 代码 controller
比较简单
defmodule Hello.DemoController do
use Hello.Web, :controller
def show(conn,params) do
render conn,"index.json", params
end
def index(conn,params) do
render conn,"index.json", params
end
def app(conn,params) do
render conn,"app.json", params
end
def create(conn,params) do
render conn,"create.json", params
end
def update(conn,params) do
render conn,"update.json", params
end
end
c. 代码view(就是简单的数据返回)
defmodule Hello.DemoView do
use Hello.Web, :view
def render("index.json",_params) do
%{
name: "dalong",
age: 444
}
end
def render("create.json",_params) do
[
%{
name: "update",
age: 333,
}
]
end
def render("update.json",_params) do
[
%{
name: "appdemo",
age: 444
}
]
end
def render("app.json",_params) do
[
%{
name: "appdemo",
age: 444
}
]
end
end
d. router(配置api访问)
web/router.ex
scope "/api", Hello do
pipe_through: api
resources "/demo", DemoController
end
4. 启动测试
项目使用了一个vscode插件http可以直接模拟使用,或者参考README.md
mix phx.server
a. post
http://localhost:4000/api/demo
curl --request POST \
--url http://localhost:4000/api/demo \
--header 'content-type: application/json'\
--data '{"name": "sample","time": "Wed, 21 Oct 2015 18:27:50 GMT"}'
b. put
http://localhost:4000/api/demo/demoid
curl --request PUT\
--url http://localhost:4000/api/demo/appdemo \
--header 'content-type: application/json'\
--data '{"name": "sample","time": "Wed, 21 Oct 2015 18:27:50 GMT"}'
c. get
http://localhost:4000/api/demo
curl --request GET\
--url http://localhost:4000/api/demo
5. 参考资料
https://github.com/rongfengliang/phoenix-rest-demo
https://hexdocs.pm/phoenix/Phoenix.Router.html#resources/4