Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

41 Commits

Repository files navigation

API Controller

Base API controller for Phoenix.

Installation

If available in Hex, the package can be installed as:

  • Add api_controller to your list of dependencies in mix.exs:
defdepsdo[{:api_controller,"~> 0.2"]end
  • Ensure api_controlleris started before your application:
defapplicationdo[applications: [:api_controller]]end

Usage

Set your application module in config:

config:api_controller,application_module: MyApp
defmoduleMyApp.UserControllerdouseApiController# Inside method you can access 'request_params' and 'conn' variablesdefmethod:create,user_schemado# name = request_params["name"]# show_result(conn, name)enddefpuser_schemado[name: [required: true,type: :string],password: [required: true,type: :string,length: 8..32],type: [required: true,type: :string,inclusion: ["user","admin"]],bio: [type: :string],age: [type: :integer],country: [type: :string,exclusion: ["Russia"]],friends: [type: :list,length: 10]]endend

if params invalid, response will look like:

{
"status": "error",
"reason": "invalid_attributes",
"errors": ["name is required and can't be blank",
"password length must be between 8 and 32",
"age should be a integer",
"type should be in [\"user\", \"admin\"]",
"country should not be in [\"Russia\"]",
"friends length should be less than or equal 10"]
}

You also can use API helpers:

@doc"""Render JSON error and status.Response example:{"status": "error", "reason": "record_not_found", errors: [], error_data: %{}}"""@callbackshow_error(Plug.Conn.t,String.t,Keyword.t)::Plug.Conn.t@callbackshow_error(Plug.Conn.t,String.t,atom|non_neg_integer,[]|[String.t],%{}|map)::Plug.Conn.tdefshow_error(conn,reason,opts)defshow_error(conn,reason,status\\:bad_request,errors\\[])show_error(conn,"record_not_found",status: 404,errors: [],error_data: %{chat_id: "uuid"})show_error(conn,"record_not_found",404,[],%{chat_id: "uuid"})
@doc"""Render JSON result and status.Response example:{"status": "ok", "result": "data"}"""@callbackshow_result(Plug.Conn.t,term,atom|non_neg_integer)::Plug.Conn.tdefshow_result(conn,result,status\\200)show_result(conn,"user_created",201)

Configuration

config:api_controller,application_module: MyApp,attributes_key_path: false# get attributes from request_params map#attributes_key_path: "data" # from request_params["data"]#attributes_key_path: ["data", "attributes"] # from request_params["data"]["attributes"]

About

Base API controller for Phoenix

Resources

Stars

6 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages