11# Easy::Api
22
3+ [ <img src =" https://travis-ci.org/AbleTech/easy-api.png " />] ( https://travis-ci.org/AbleTech/easy-api )
4+
35A repository of common, reusable API code. Its purpose is to make all of Abletech's APIs respond in a consistent manner.
46
57## Installation
@@ -31,16 +33,59 @@ To initialise an error, pass in the type you want, e.g.
3133If you want to override the default error message, pass in a custom message, e.g.
3234
3335 Easy::Api::Error.new(:invalid, @user.errors.full_messages.join(', '))
34-
36+
3537Easy::Api::Error objects have a code (e.g. 404) and a message (e.g. 'Resource not found')
3638
39+ ### Using Easy::Api
40+
41+ Add the following line to all Api Controllers:
42+
43+ include Easy::Api
44+
45+ Then in your Api actions, do your logic inside a block:
46+
47+ easy_api do |api|
48+ api.parcel = Parcel.first
49+ api.status_code = 200
50+ api.success = true
51+ api.render_result(format: params[:format])
52+ end
53+
54+ If the request is a success, you must set
55+
56+ api.status_code = 200
57+ api.success = true
58+
59+ and you can also set any other values you want to send back, e.g.
60+
61+ api.parcel = Parcel.first
62+
63+ If the request is unsuccessful, you must set the status_code, e.g.
64+
65+ api.status_code = 401
66+
67+ and you also need to set error to be an instance of Easy::Api::Error, e.g.
68+
69+ api.error = Easy::Api::Error.new(:unauthorized)
70+
71+ Then render the result
72+
73+ api.render_result(format: params[:format])
74+
75+ If your API supports callbacks these can also be passed
76+
77+ api.render_result(format: params[:format], callback: params[:callback])
78+
3779### Using Easy::Api::ControllerMethods
80+
81+ ** Depricated**
82+
3883Add the following line to all Api Controllers:
39-
84+
4085 include Easy::Api::ControllerMethods
4186
42- then in your Api actions, add values to the @result (Easy::Api::Result) object.
43- If the request is a success, you must set
87+ then in your Api actions, add values to the @result (Easy::Api::Result) object.
88+ If the request is a success, you must set
4489
4590 @result.status_code = 200
4691 @result.success = true
@@ -57,6 +102,10 @@ and you also need to set error to be an instance of Easy::Api::Error, e.g.
57102
58103 @result.error = Easy::Api::Error.new(:unauthorized)
59104
105+ Then render the result
106+
107+ render_format
108+
60109## Contributing
61110
621111 . Fork it
0 commit comments