设为首页 加入收藏

TOP

phoenix 开发API系列(二)phoenix 各类 api 实现方式(二)
2017-10-09 13:27:26 】 浏览:960
Tags:phoenix 开发 API 系列 各类 api 实现 方式
am"
, "message": "your name is " <> params["name"] <> " and age is " <> to_string(params["age"]), } else json conn, %{ "result": "success from json_param", "message": "your name is " <> params["name"], } end end
  • router 相关代码: (router.ex)
    post "/json-param", ApiParamController, :json_param
  • 启动 phoenix 开发服务器,就可以在浏览器中访问对应的 URL
    mix phoenix.server

测试api 可以使用 curl 命令:

    curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
 "name": "wyb"
 }' "http://localhost:4000/api/json-param"
    
    curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
 "name": "wyb",
 "age": 33
 }' "http://localhost:4000/api/json-param"

下载 文件

introduce by code: api的参数的上面的示例一样

  • controller 中相关代码:(api_param_controller.ex)
    @doc "/api/file-param"
    def file_param(conn, params) do
      filepath = "/tmp/downloadfile.txt"
      if Map.has_key?(params, "age") do
        File.write(filepath, "your name is " <> params["name"] <> " and age is " <> to_string(params["age"]))
      else
        File.write(filepath, "your name is " <> params["name"])
      end
    
      conn |> send_file(200, filepath)
    end
  • router 相关代码: (router.ex)
    get "/file-param", ApiParamController, :file_param
  • 启动 phoenix 开发服务器,就可以在浏览器中访问对应的 URL
    mix phoenix.server

在 浏览器 中访问 http://localhost:4000/api/file-param?name=wang&age=33http://localhost:4000/api/file-param?name=wang 可以看到返回的 json。

上传 文件

introduce by code: api的参数的上面的示例一样

  • controller 中相关代码:(api_param_controller.ex)
    @doc "/api/file-param"
    def upload_param(conn, params) do
    
      file = params["file"]
      File.cp(file.path, "/tmp/upload.file")
    
      json conn, %{
        "result": "success from file_param",
        "message": "your name is " <> params["name"] <> " and age is " <> to_string(params["age"])
        <> " and the filename which you upload is " <> file.filename,
      }
    end
  • router 相关代码: (router.ex)
    post "/file-param", ApiParamController, :upload_param
  • 启动 phoenix 开发服务器,就可以在浏览器中访问对应的 URL
    mix phoenix.server

测试api 可以使用 curl 命令: 命令中的 file 要替换成你的实际文件路径

    curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: multipart/form-data" \
        -F "name=wyb" -F "age=33" -F "file=@/tmp/test.jpg" "http://localhost:4000/api/file-param"

总结

可以看岀,phoenix framework 的 Plug 提供了丰富的功能,所以编写 api 非常方便。 掌握了上面的示例,基本就可以满足构建web服务时大部分的 api 的写法了。

来源:http://blog.iotalabs.io/

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇云巴:基于 MQTT 协议的实时通信.. 下一篇酒罢问君三语

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目