

العنب هو إطار API يشبه الراحة لروبي. تم تصميمه ليتم تشغيله على الرف أو استكمال أطر تطبيق الويب الحالية مثل Rails و Sinatra من خلال توفير DSL بسيط لتطوير واجهات برمجة التطبيقات المريحة بسهولة. لديها دعم مدمج للاتفاقيات الشائعة ، بما في ذلك تنسيقات متعددة ، وتقييد النطاق الفرعي/البادئة ، والتفاوض على المحتوى ، والإصدار وأكثر من ذلك بكثير.
أنت تقرأ وثائق الإصدار التالي من العنب ، والذي يجب أن يكون 2.3.0. الإصدار المستقر الحالي هو 2.2.0.
متاح كجزء من اشتراك Tidelift.
يعمل مشرفي العنب مع Tidelift لتقديم الدعم التجاري والصيانة. وفر الوقت ، وتقليل المخاطر ، وتحسين صحة الكود ، مع دفع مشرفي العنب. انقر هنا لمزيد من التفاصيل.
مطلوب روبي 2.7 أو الأحدث.
العنب متاح كجوهرة ، لتثبيته تشغيل:
bundle add grape
واجهات برمجة تطبيقات العنب عبارة عن تطبيقات رف يتم إنشاؤها بواسطة Grape::API . فيما يلي مثال بسيط يوضح بعض الميزات الأكثر شيوعًا للعنب في سياق إعادة إنشاء أجزاء من واجهة برمجة تطبيقات Twitter.
module Twitter
class API < Grape :: API
version 'v1' , using : :header , vendor : 'twitter'
format :json
prefix :api
helpers do
def current_user
@current_user ||= User . authorize! ( env )
end
def authenticate!
error! ( '401 Unauthorized' , 401 ) unless current_user
end
end
resource :statuses do
desc 'Return a public timeline.'
get :public_timeline do
Status . limit ( 20 )
end
desc 'Return a personal timeline.'
get :home_timeline do
authenticate!
current_user . statuses . limit ( 20 )
end
desc 'Return a status.'
params do
requires :id , type : Integer , desc : 'Status ID.'
end
route_param :id do
get do
Status . find ( params [ :id ] )
end
end
desc 'Create a status.'
params do
requires :status , type : String , desc : 'Your status.'
end
post do
authenticate!
Status . create! ( {
user : current_user ,
text : params [ :status ]
} )
end
desc 'Update a status.'
params do
requires :id , type : String , desc : 'Status ID.'
requires :status , type : String , desc : 'Your status.'
end
put ':id' do
authenticate!
current_user . statuses . find ( params [ :id ] ) . update ( {
user : current_user ,
text : params [ :status ]
} )
end
desc 'Delete a status.'
params do
requires :id , type : String , desc : 'Status ID.'
end
delete ':id' do
authenticate!
current_user . statuses . find ( params [ :id ] ) . destroy
end
end
end
end ستتم إضافة DepreCator's Grape إلى استراحة التطبيق تلقائيًا على النحو التالي :grape ، بحيث يمكن تطبيق تكوين التطبيق الخاص بك.
بشكل افتراضي ، سيقوم العنب بتجميع الطرق على المسار الأول ، فمن الممكن تحميل الطرق المسبقة باستخدام compile! طريقة.
Twitter :: API . compile! يمكن إضافة ذلك إلى config.ru (إذا كنت تستخدم Rackup) أو application.rb (إذا كنت تستخدم Rails) أو أي ملف يقوم بتحميل الخادم الخاص بك.
تنشئ العينة أعلاه تطبيق رف يمكن تشغيله من ملف config.ru Rackup مع rackup :
run Twitter :: API(مع التحميل المسبق يمكنك استخدامه)
Twitter :: API . compile!
run Twitter :: APIوسوف ترد على الطرق التالية:
GET /api/statuses/public_timeline
GET /api/statuses/home_timeline
GET /api/statuses/:id
POST /api/statuses
PUT /api/statuses/:id
DELETE /api/statuses/:id
سيستجيب العنب أيضًا تلقائيًا للرأس والخيارات لجميع GET ، وخيارات فقط لجميع الطرق الأخرى.
إذا كنت ترغب في تركيب العنب إلى جانب إطار آخر على رف مثل سيناترا ، فيمكنك القيام بذلك بسهولة باستخدام Rack::Cascade :
# Example config.ru
require 'sinatra'
require 'grape'
class API < Grape :: API
get :hello do
{ hello : 'world' }
end
end
class Web < Sinatra :: Base
get '/' do
'Hello world.'
end
end
use Rack :: Session :: Cookie
run Rack :: Cascade . new [ Web , API ] لاحظ هذا الترتيب لتحميل التطبيقات باستخدام Rack::Cascade Matters. يجب أن يكون تطبيق العنب يدوم إذا كنت ترغب في رفع أخطاء 404 مخصصة من العنب (مثل error!('Not Found',404) ). إذا لم يستمر تطبيق العنب وأرجع استجابة 404 أو 405 ، فإن Cascade يستخدم ذلك كإشارة لتجربة التطبيق التالي. قد يؤدي هذا إلى سلوك غير مرغوب فيه يظهر صفحة 404 الخاطئة من التطبيق الخطأ.
ضع ملفات API في app/api . تتوقع Rails دليلًا فرعيًا يطابق اسم وحدة Ruby واسم ملف يطابق اسم الفصل. في مثالنا ، يجب أن يكون موقع اسم الملف ودليل Twitter::API app/api/twitter/api.rb .
تعديل config/routes :
mount Twitter :: API => '/' Zeitwerk Rails الافتراضي هو Zeitwerk . بشكل افتراضي ، فإنه يصيب api Api بدلاً من API . لجعل مثالنا يعمل ، تحتاج API فك الخطية في الجزء السفلي من config/initializers/inflections.rb .
ActiveSupport :: Inflector . inflections ( :en ) do | inflect |
inflect . acronym 'API'
endيمكنك تركيب تطبيقات API متعددة داخل واحد آخر. لا يجب أن تكون هذه الإصدارات مختلفة ، ولكن قد تكون مكونات من نفس واجهة برمجة التطبيقات.
class Twitter :: API < Grape :: API
mount Twitter :: APIv1
mount Twitter :: APIv2
end يمكنك أيضًا التركيز على مسار ، وهو ما يشبه استخدام prefix داخل واجهة برمجة التطبيقات المثبتة نفسها.
class Twitter :: API < Grape :: API
mount Twitter :: APIv1 => '/v1'
end يمكن وضع إعلانات كما كان before/after/rescue_from قبل أو بعد mount . في أي حال سيتم مورثها.
class Twitter :: API < Grape :: API
before do
header 'X-Base-Header' , 'will be defined for all APIs that are mounted below'
end
rescue_from :all do
error! ( { "error" => "Internal Server Error" } , 500 )
end
mount Twitter :: Users
mount Twitter :: Search
after do
clean_cache!
end
rescue_from ZeroDivisionError do
error! ( { "error" => "Not found" } , 404 )
end
end يمكنك تركيب نفس نقاط النهاية في موقعين مختلفين.
class Voting :: API < Grape :: API
namespace 'votes' do
get do
# Your logic
end
post do
# Your logic
end
end
end
class Post :: API < Grape :: API
mount Voting :: API
end
class Comment :: API < Grape :: API
mount Voting :: API
end على افتراض أن نقاط نهاية المنشور والتعليقات يتم تركيبها في /posts و /comments ، يجب أن تكون قادرًا الآن على القيام get /posts/votes ، post /posts/votes ، get /comments/votes والبريد post /comments/votes .
يمكنك تكوين نقاط النهاية القابلة للتطبيق لتغيير كيفية تصرفها وفقًا للمكان الذي يتم تركيبه.
class Voting :: API < Grape :: API
namespace 'votes' do
desc "Vote for your #{ configuration [ :votable ] } "
get do
# Your logic
end
end
end
class Post :: API < Grape :: API
mount Voting :: API , with : { votable : 'posts' }
end
class Comment :: API < Grape :: API
mount Voting :: API , with : { votable : 'comments' }
end لاحظ أنه إذا كنت تمر تجزئة كمعلمة أول mount ، فستحتاج إلى وضع () بشكل صريح حول المعلمات:
# good
mount ( { :: Some :: Api => '/some/api' } , with : { condition : true } )
# bad
mount :: Some :: Api => '/some/api' , with : { condition : true } يمكنك الوصول إلى configuration في الفصل (لاستخدام سمات ديناميكية) ، داخل الكتل (مثل مساحة الاسم)
إذا كنت تريد أن يحدث المنطق في configuration ، فيمكنك استخدام المساعد given .
class ConditionalEndpoint :: API < Grape :: API
given configuration [ :some_setting ] do
get 'mount_this_endpoint_conditionally' do
configuration [ :configurable_response ]
end
end
end إذا كنت ترغب في تشغيل كتلة من المنطق في كل مرة يتم فيها تثبيت نقطة نهاية (يمكنك من خلالها الوصول إلى تجزئة configuration )
class ConditionalEndpoint :: API < Grape :: API
mounted do
YourLogger . info "This API was mounted at: #{ Time . now } "
get configuration [ :endpoint_name ] do
configuration [ :configurable_response ]
end
end
end يمكن تحقيق نتائج أكثر تعقيدًا باستخدام mounted كتعبير يتم تقييم configuration فيه بالفعل على أنه تجزئة.
class ExpressionEndpointAPI < Grape :: API
get ( mounted { configuration [ :route_name ] || 'default_name' } ) do
# some logic
end
end class BasicAPI < Grape :: API
desc 'Statuses index' do
params : ( configuration [ :entity ] || API :: Entities :: Status ) . documentation
end
params do
requires :all , using : ( configuration [ :entity ] || API :: Entities :: Status ) . documentation
end
get '/statuses' do
statuses = Status . all
type = current_user . admin? ? :full : :default
present statuses , with : ( configuration [ :entity ] || API :: Entities :: Status ) , type : type
end
end
class V1 < Grape :: API
version 'v1'
mount BasicAPI , with : { entity : mounted { configuration [ :entity ] || API :: Entities :: Status } }
end
class V2 < Grape :: API
version 'v2'
mount BasicAPI , with : { entity : mounted { configuration [ :entity ] || API :: Entities :: V2 :: Status } }
end لديك خيار تقديم إصدارات مختلفة من واجهة برمجة التطبيقات الخاصة بك من خلال إنشاء فئة منفصلة Grape::API لكل إصدار معروض ثم دمجها في فئة Grape::API . تأكد من تركيب الإصدارات الأحدث قبل الإصدارات الأكبر سناً. يوجه النهج الافتراضي لإصدار الإصدار الطلب إلى البرامج الوسيطة الحامل اللاحقة إذا لم يتم العثور على إصدار معين.
require 'v1'
require 'v2'
require 'v3'
class App < Grape :: API
mount V3
mount V2
mount V1
endللحفاظ على نفس نقاط النهاية من إصدارات API السابقة دون إعادة كتابتها ، يمكنك الإشارة إلى إصدارات متعددة ضمن إصدارات API السابقة.
class V1 < Grape :: API
version 'v1' , 'v2' , 'v3'
get '/foo' do
# your code for GET /foo
end
get '/other' do
# your code for GET /other
end
end
class V2 < Grape :: API
version 'v2' , 'v3'
get '/var' do
# your code for GET /var
end
end
class V3 < Grape :: API
version 'v3'
get '/foo' do
# your new code for GET /foo
end
endباستخدام المثال المقدم ، سيتم الوصول إلى نقاط النهاية اللاحقة عبر الإصدارات المختلفة:
GET /v1/foo
GET /v1/other
GET /v2/foo # => Same behavior as v1
GET /v2/other # => Same behavior as v1
GET /v2/var # => New endpoint not available in v1
GET /v3/foo # => Different behavior to v1 and v2
GET /v3/other # => Same behavior as v1 and v2
GET /v3/var # => Same behavior as v2 هناك أربع استراتيجيات يمكن للعملاء الوصول فيها إلى نقاط نهاية واجهة برمجة التطبيقات الخاصة بك :: :path ، :header ، :accept_version_header و :param . الاستراتيجية الافتراضية هي :path .
version 'v1' , using : :pathباستخدام استراتيجية الإصدار هذه ، يجب على العملاء تمرير الإصدار المطلوب في عنوان URL.
curl http://localhost:9292/v1/statuses/public_timeline
version 'v1' , using : :header , vendor : 'twitter'حاليًا ، يدعم العنب فقط أنواع الوسائط ذات الإصدار بالتنسيق التالي:
vnd.vendor-and-or-resource-v1234+format
في الأساس ، سيتم تفسير جميع الرموز المميزة بين النهائي - و + كنسخة.
باستخدام استراتيجية الإصدار هذه ، يجب على العملاء تمرير الإصدار المطلوب في HTTP Accept الرأس.
curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline
بشكل افتراضي ، يتم استخدام الإصدار الأول المطابقة عند عدم توفير رأس Accept . هذا السلوك يشبه التوجيه في القضبان. للتحايل على هذا السلوك الافتراضي ، يمكن للمرء استخدام خيار :strict . عندما يتم ضبط هذا الخيار على true ، يتم إرجاع خطأ 406 Not Acceptable عند عدم توفير رأس Accept صحيح.
عند توفير رأس Accept غير صالح ، يتم إرجاع خطأ 406 Not Acceptable إذا تم تعيين خيار :cascade على false . وإلا فإن 404 Not Found خطأ يتم إرجاعه بواسطة Rack إذا لم يتطابق مسار آخر.
سيقوم العنب بتقييم تفضيل الجودة النسبية المتضمنة في رؤوس قبول وافتراضي إلى جودة 1.0 عند حذفها. في المثال التالي ، ستعيد واجهة برمجة تطبيقات العنب التي تدعم XML و JSON بهذا الترتيب JSON:
curl -H "Accept: text/xml;q=0.8, application/json;q=0.9" localhost:1234/resource
version 'v1' , using : :accept_version_header باستخدام استراتيجية الإصدار هذه ، يجب على العملاء تمرير الإصدار المطلوب في رأس HTTP Accept-Version .
curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline
بشكل افتراضي ، يتم استخدام الإصدار الأول المطابق عند عدم توفير رأس Accept-Version . هذا السلوك يشبه التوجيه في القضبان. للتحايل على هذا السلوك الافتراضي ، يمكن للمرء استخدام خيار :strict . عندما يتم تعيين هذا الخيار على true ، يتم إرجاع خطأ 406 Not Acceptable عند عدم توفير رأس Accept صحيح ويتم تعيين خيار :cascade على false . وإلا فإن 404 Not Found خطأ يتم إرجاعه بواسطة Rack إذا لم يتطابق مسار آخر.
version 'v1' , using : :paramباستخدام استراتيجية الإصدار هذه ، يجب على العملاء تمرير الإصدار المطلوب كمعلمة طلب ، إما في سلسلة استعلام عنوان URL أو في هيئة الطلب.
curl http://localhost:9292/statuses/public_timeline?apiver=v1
الاسم الافتراضي لمعلمة الاستعلام هو "apiver" ولكن يمكن تحديده باستخدام خيار :parameter .
version 'v1' , using : :param , parameter : 'v' curl http://localhost:9292/statuses/public_timeline?v=v1
يمكنك إضافة وصف لأساليب ومساحات الأسماء API. سيتم استخدام الوصف بواسطة Grape-Swagger لإنشاء وثائق متوافقة مع Swagger.
ملاحظة: الوصف كتلة فقط للوثائق ولن يؤثر على سلوك API.
desc 'Returns your public timeline.' do
summary 'summary'
detail 'more details'
params API :: Entities :: Status . documentation
success API :: Entities :: Entity
failure [ [ 401 , 'Unauthorized' , 'Entities::Error' ] ]
default { code : 500 , message : 'InvalidRequest' , model : Entities :: Error }
named 'My named route'
headers XAuthToken : {
description : 'Validates your identity' ,
required : true
} ,
XOptionalHeader : {
description : 'Not really needed' ,
required : false
}
hidden false
deprecated false
is_array true
nickname 'nickname'
produces [ 'application/json' ]
consumes [ 'application/json' ]
tags [ 'tag1' , 'tag2' ]
end
get :public_timeline do
Status . limit ( 20 )
enddetail : وصف أكثر تعزيزًاparams : تحديد المعلمات مباشرة من Entitysuccess : (الكيان السابق) Entity الذي سيتم استخدامه لتقديم استجابة النجاح لهذا الطريق.failure : (HTTP_CODES السابق) تعريف لرموز وكيانات الفشل المستخدم المستخدمة.default : التعريف Entity المستخدمان لتقديم الاستجابة الافتراضية لهذا المسار.named : مساعد لإعطاء مسار اسم والعثور عليه بهذا الاسم في تجزئة الوثائقheaders : تعريف للرؤوس المستخدمة استخدم Grape.configure لإعداد الإعدادات العالمية في وقت التحميل. حاليا الإعدادات القابلة للتكوين هي:
param_builder : تعيين منشئ المعلمة ، الافتراضيات إلى Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder .لتغيير قيمة الإعداد ، تأكد من أنه في وقت ما أثناء التحميل يتم تشغيل الكود التالي
Grape . configure do | config |
config . setting = value
end على سبيل المثال ، بالنسبة إلى param_builder ، يمكن تشغيل الكود التالي في مُهيئ:
Grape . configure do | config |
config . param_builder = Grape :: Extensions :: Hashie :: Mash :: ParamBuilder
endيمكنك أيضًا تكوين واجهة برمجة تطبيقات واحدة:
API . configure do | config |
config [ key ] = value
end سيكون هذا متاحًا داخل واجهة برمجة التطبيقات مع configuration ، كما لو كان تكوين Mount.
تتوفر معلمات الطلب من خلال كائن params . يتضمن ذلك معلمات الحصول على ومعلمات GET و POST و PUT ، إلى جانب أي معلمات محددة تحددها في سلاسل المسار.
get :public_timeline do
Status . order ( params [ :sort_by ] )
end يتم ملء المعلمات تلقائيًا من هيئة الطلب في POST ويتم PUT لإدخال النموذج ، و json و xml من أنواع المحتوى.
الطلب:
curl -d '{"text": "140 characters"}' 'http://localhost:9292/statuses' -H Content-Type:application/json -v
نقطة نهاية العنب:
post '/statuses' do
Status . create! ( text : params [ :text ] )
endيتم دعم المشاركات المتعددة والوضع أيضًا.
الطلب:
curl --form image_file='@image.jpg;type=image/jpg' http://localhost:9292/upload
نقطة نهاية العنب:
post 'upload' do
# file in params[:image_file]
endفي حالة الصراع بين أي من:
GET المعلمات POST PUTPOST PUTمعلمات سلسلة الطريق سيكون لها الأسبقية.
بشكل افتراضي ، تتوفر المعلمات كـ ActiveSupport::HashWithIndifferentAccess . يمكن تغيير هذا إلى ، على سبيل المثال ، Ruby Hash أو Hashie::Mash لجميع API بأكمله.
class API < Grape :: API
include Grape :: Extensions :: Hashie :: Mash :: ParamBuilder
params do
optional :color , type : String
end
get do
params . color # instead of params[:color]
end يمكن أيضًا تجاوز الفصل على كتل المعلمات الفردية باستخدام build_with على النحو التالي.
params do
build_with Grape :: Extensions :: Hash :: ParamBuilder
optional :color , type : String
end أو عالميًا مع تكوين Grape.configure.param_builder .
في المثال أعلاه ، ستعود params["color"] إلى nil نظرًا لأن params عبارة عن Hash عادي.
بناة المعلمات المتاحة هي Grape::Extensions::Hash::ParamBuilder ، Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder and Grape::Extensions::Hashie::Mash::ParamBuilder .
يتيح لك العنب الوصول فقط إلى المعلمات التي تم الإعلان عنها بواسطة كتلة params الخاصة بك. فإنه سوف:
النظر في نقطة نهاية API التالية:
format :json
post 'users/signup' do
{ 'declared_params' => declared ( params ) }
end إذا لم تحدد أي معلمات ، فسيتم declared ستعيد علامة تجزئة فارغة.
طلب
curl -X POST -H " Content-Type: application/json " localhost:9292/users/signup -d ' {"user": {"first_name":"first name", "last_name": "last name"}} 'إجابة
{
"declared_params" : {}
}
بمجرد إضافة متطلبات المعلمات ، سيبدأ العنب في إرجاع المعلمات المعلنة فقط.
format :json
params do
optional :user , type : Hash do
optional :first_name , type : String
optional :last_name , type : String
end
end
post 'users/signup' do
{ 'declared_params' => declared ( params ) }
endطلب
curl -X POST -H " Content-Type: application/json " localhost:9292/users/signup -d ' {"user": {"first_name":"first name", "last_name": "last name", "random": "never shown"}} 'إجابة
{
"declared_params" : {
"user" : {
"first_name" : " first name " ,
"last_name" : " last name "
}
}
} سيتم تضمين المعاملات المفقودة التي تم إعلانها كنوع Hash أو Array .
format :json
params do
optional :user , type : Hash do
optional :first_name , type : String
optional :last_name , type : String
end
optional :widgets , type : Array
end
post 'users/signup' do
{ 'declared_params' => declared ( params ) }
endطلب
curl -X POST -H " Content-Type: application/json " localhost:9292/users/signup -d ' {} 'إجابة
{
"declared_params" : {
"user" : {
"first_name" : null ,
"last_name" : null
},
"widgets" : []
}
} التجزئة التي تم إرجاعها هو ActiveSupport::HashWithIndifferentAccess .
طريقة #declared غير متوفرة before المرشحات ، حيث يتم تقييمها قبل إكراه المعلمة.
بشكل افتراضي ، يتضمن declared(params) معلمات تم تعريفها في جميع مساحات الأسماء الوالدين. إذا كنت ترغب في إرجاع المعلمات فقط من مساحة الاسم الحالية الخاصة بك ، فيمكنك تعيين خيار include_parent_namespaces إلى false .
format :json
namespace :parent do
params do
requires :parent_name , type : String
end
namespace ':parent_name' do
params do
requires :child_name , type : String
end
get ':child_name' do
{
'without_parent_namespaces' => declared ( params , include_parent_namespaces : false ) ,
'with_parent_namespaces' => declared ( params , include_parent_namespaces : true ) ,
}
end
end
endطلب
curl -X GET -H " Content-Type: application/json " localhost:9292/parent/foo/barإجابة
{
"without_parent_namespaces" : {
"child_name" : " bar "
},
"with_parent_namespaces" : {
"parent_name" : " foo " ,
"child_name" : " bar "
},
} افتراضيًا ، يتضمن declared(params) معلمات لها قيم nil . إذا كنت ترغب في إرجاع المعلمات التي لا تكون nil ، فيمكنك استخدام خيار include_missing . بشكل افتراضي ، تم تعيين include_missing على true . النظر في واجهة برمجة التطبيقات التالية:
format :json
params do
requires :user , type : Hash do
requires :first_name , type : String
optional :last_name , type : String
end
end
post 'users/signup' do
{ 'declared_params' => declared ( params , include_missing : false ) }
endطلب
curl -X POST -H " Content-Type: application/json " localhost:9292/users/signup -d ' {"user": {"first_name":"first name", "random": "never shown"}} 'الرد مع inswer_missing: خطأ
{
"declared_params" : {
"user" : {
"first_name" : " first name "
}
}
}الاستجابة مع inswer_missing: صحيح
{
"declared_params" : {
"user" : {
"first_name" : " first name " ,
"last_name" : null
}
}
}كما أنه يعمل على تجزئة متداخلة:
format :json
params do
requires :user , type : Hash do
requires :first_name , type : String
optional :last_name , type : String
requires :address , type : Hash do
requires :city , type : String
optional :region , type : String
end
end
end
post 'users/signup' do
{ 'declared_params' => declared ( params , include_missing : false ) }
endطلب
curl -X POST -H " Content-Type: application/json " localhost:9292/users/signup -d ' {"user": {"first_name":"first name", "random": "never shown", "address": { "city": "SF"}}} 'الرد مع inswer_missing: خطأ
{
"declared_params" : {
"user" : {
"first_name" : " first name " ,
"address" : {
"city" : " SF "
}
}
}
}الاستجابة مع inswer_missing: صحيح
{
"declared_params" : {
"user" : {
"first_name" : " first name " ,
"last_name" : null ,
"address" : {
"city" : " Zurich " ,
"region" : null
}
}
}
} لاحظ أن السمة ذات قيمة nil لا تعتبر مفقودة وسيتم إرجاعها أيضًا عند ضبط include_missing على false :
طلب
curl -X POST -H " Content-Type: application/json " localhost:9292/users/signup -d ' {"user": {"first_name":"first name", "last_name": null, "address": { "city": "SF"}}} 'الرد مع inswer_missing: خطأ
{
"declared_params" : {
"user" : {
"first_name" : " first name " ,
"last_name" : null ,
"address" : { "city" : " SF " }
}
}
} بشكل افتراضي ، لن يتم تقييم declared(params) given وإرجاع جميع المعلمات. استخدم evaluate_given لتقييم جميع الكتل given وإرجاع المعلمات فقط التي تلبي الشروط given . النظر في واجهة برمجة التطبيقات التالية:
format :json
params do
optional :child_id , type : Integer
given :child_id do
requires :father_id , type : Integer
end
end
post 'child' do
{ 'declared_params' => declared ( params , evaluate_given : true ) }
endطلب
curl -X POST -H " Content-Type: application/json " localhost:9292/child -d ' {"father_id": 1} 'استجابة مع تقييم _given: خطأ
{
"declared_params" : {
"child_id" : null ,
"father_id" : 1
}
}استجابة مع تقييم _given: صحيح
{
"declared_params" : {
"child_id" : null
}
}كما أنه يعمل على تجزئة متداخلة:
format :json
params do
requires :child , type : Hash do
optional :child_id , type : Integer
given :child_id do
requires :father_id , type : Integer
end
end
end
post 'child' do
{ 'declared_params' => declared ( params , evaluate_given : true ) }
endطلب
curl -X POST -H " Content-Type: application/json " localhost:9292/child -d ' {"child": {"father_id": 1}} 'استجابة مع تقييم _given: خطأ
{
"declared_params" : {
"child" : {
"child_id" : null ,
"father_id" : 1
}
}
}استجابة مع تقييم _given: صحيح
{
"declared_params" : {
"child" : {
"child_id" : null
}
}
} إن استخدام route_param يأخذ الأسبقية أعلى على معلمة منتظمة محددة بنفس الاسم:
params do
requires :foo , type : String
end
route_param :foo do
get do
{ value : params [ :foo ] }
end
endطلب
curl -X POST -H " Content-Type: application/json " localhost:9292/bar -d ' {"foo": "baz"} 'إجابة
{
"value" : " bar "
} يمكنك تحديد عمليات التحقق وخيارات الإكراه للمعلمات الخاصة بك باستخدام كتلة params .
params do
requires :id , type : Integer
optional :text , type : String , regexp : / A [a-z]+ z /
group :media , type : Hash do
requires :url
end
optional :audio , type : Hash do
requires :format , type : Symbol , values : [ :mp3 , :wav , :aac , :ogg ] , default : :mp3
end
mutually_exclusive :media , :audio
end
put ':id' do
# params[:id] is an Integer
endعندما يتم تحديد نوع ما ، يتم التحقق من صحة ضمنية بعد الإكراه لضمان أن يكون نوع الإخراج هو الناتج.
يمكن أن يكون للمعلمات الاختيارية قيمة افتراضية.
params do
optional :color , type : String , default : 'blue'
optional :random_number , type : Integer , default : -> { Random . rand ( 1 .. 100 ) }
optional :non_random_number , type : Integer , default : Random . rand ( 1 .. 100 )
end يتم تقييم القيم الافتراضية بفارغ الصبر. أعلاه :non_random_number إلى نفس الرقم لكل مكالمة إلى نقطة النهاية من كتلة params هذه. للحصول على التقييم الافتراضي بتكاسل مع كل طلب ، استخدم lambda ، مثل :random_number أعلاه.
لاحظ أنه سيتم تمرير القيم الافتراضية إلى أي خيارات التحقق من الصحة المحددة. سوف يفشل المثال التالي دائمًا إذا لم يتم توفير :color بشكل صريح.
params do
optional :color , type : String , default : 'blue' , values : [ 'red' , 'green' ]
endيتمثل التنفيذ الصحيح في التأكد من أن القيمة الافتراضية تمر بجميع عمليات التحقق.
params do
optional :color , type : String , default : 'blue' , values : [ 'blue' , 'red' , 'green' ]
end يمكنك استخدام قيمة معلمة واحدة كقيمة افتراضية لبعض المعلمة الأخرى. في هذه الحالة ، إذا لم يتم توفير المعلمة primary_color ، فسيكون لها نفس القيمة مثل color . إذا لم يتم توفير كلاهما ، فسيكون لكلاهما قيمة blue .
params do
optional :color , type : String , default : 'blue'
optional :primary_color , type : String , default : -> ( params ) { params [ :color ] }
endفيما يلي كل أنواع صالحة ، مدعومة خارج الصندوق عن طريق العنب:
File الاسم المستعار)يرجى العلم أن السلوك يختلف بين Ruby 2.4 والإصدارات السابقة. في Ruby 2.4 ، يتم تحويل القيم التي تتكون من الأرقام إلى عدد صحيح ، ولكن في الإصدارات السابقة سيتم التعامل معها على أنها FixNum.
params do
requires :integers , type : Hash do
requires :int , coerce : Integer
end
end
get '/int' do
params [ :integers ] [ :int ] . class
end
. ..
get '/int' integers : { int : '45' }
#=> Integer in ruby 2.4
#=> Fixnum in earlier ruby versions بصرف النظر عن المجموعة الافتراضية من الأنواع المدعومة المذكورة أعلاه ، يمكن استخدام أي فئة كنوع طالما يتم توفير طريقة إكراه صريحة. إذا كان النوع ينفذ طريقة parse مستوى الفصل ، فسيستخدمه العنب تلقائيًا. يجب أن تأخذ هذه الطريقة وسيطة سلسلة واحدة وإرجاع مثيل من النوع الصحيح ، أو إرجاع مثيل من Grape::Types::InvalidValue الذي يقبل اختياريًا رسالة يتم إرجاعها في الاستجابة.
class Color
attr_reader :value
def initialize ( color )
@value = color
end
def self . parse ( value )
return new ( value ) if %w[ blue red green ] . include? ( value )
Grape :: Types :: InvalidValue . new ( 'Unsupported color' )
end
end
params do
requires :color , type : Color , default : Color . new ( 'blue' )
requires :more_colors , type : Array [ Color ] # Collections work
optional :unique_colors , type : Set [ Color ] # Duplicates discarded
end
get '/stuff' do
# params[:color] is already a Color.
params [ :color ] . value
end بدلاً من ذلك ، قد يتم توفير طريقة إكراه مخصصة لأي نوع من المعلمة باستخدام coerce_with . قد يتم إعطاء أي فئة أو كائن يقوم بتنفيذ parse أو طريقة call ، في ترتيب الأسبقية هذا. يجب أن تقبل الطريقة معلمة سلسلة واحدة ، ويجب أن تتطابق قيمة الإرجاع مع type المحدد.
params do
requires :passwd , type : String , coerce_with : Base64 . method ( :decode64 )
requires :loud_color , type : Color , coerce_with : -> ( c ) { Color . parse ( c . downcase ) }
requires :obj , type : Hash , coerce_with : JSON do
requires :words , type : Array [ String ] , coerce_with : -> ( val ) { val . split ( / s +/ ) }
optional :time , type : Time , coerce_with : Chronic
end
end لاحظ أن قيمة nil ستستدعي طريقة الإكراه المخصص ، في حين أن المعلمة المفقودة لن تفعل ذلك.
مثال على استخدام coerce_with مع lambda (يمكن أيضًا استخدام فئة ذات طريقة parse ) ، وسوف يتم تحليل سلسلة وإرجاع مجموعة من الأعداد الصحيحة ، مع مطابقة type Array[Integer] .
params do
requires :values , type : Array [ Integer ] , coerce_with : -> ( val ) { val . split ( / s +/ ) . map ( & :to_i ) }
end سوف يؤكد العنب أن القيم الإكراهية تتطابق مع type المحدد ، وسوف يرفض الطلب إذا لم يفعلوا ذلك. لتجاوز هذا السلوك ، قد تنفذ أنواع مخصصة parsed? الطريقة التي يجب أن تقبل وسيطة واحدة وإرجاع true إذا تم تمرير القيمة التحقق من صحة نوع.
class SecureUri
def self . parse ( value )
URI . parse value
end
def self . parsed? ( value )
value . is_a? URI :: HTTPS
end
end
params do
requires :secure_uri , type : SecureUri
end يستفيد العنب من الدعم المدمج Rack::Request لمعلمات الملفات المتعددة. يمكن إعلان مثل هذه المعلمات type: File :
params do
requires :avatar , type : File
end
post '/' do
params [ :avatar ] [ :filename ] # => 'avatar.png'
params [ :avatar ] [ :type ] # => 'image/png'
params [ :avatar ] [ :tempfile ] # => #<File>
endJSON من الدرجة الأولى يدعم العنب المعلمات المعقدة المعطاة كسلاسل تنسيق JSON باستخدام type: JSON . يتم قبول كائنات JSON ومصفوفات الكائنات بالتساوي ، مع تطبيق قواعد التحقق المتداخل على جميع الكائنات في كلتا الحالتين:
params do
requires :json , type : JSON do
requires :int , type : Integer , values : [ 1 , 2 , 3 ]
end
end
get '/' do
params [ :json ] . inspect
end
client . get ( '/' , json : '{"int":1}' ) # => "{:int=>1}"
client . get ( '/' , json : '[{"int":"1"}]' ) # => "[{:int=>1}]"
client . get ( '/' , json : '{"int":4}' ) # => HTTP 400
client . get ( '/' , json : '[{"int":4}]' ) # => HTTP 400 بالإضافة إلى type: Array[JSON] ، والذي يمثل بشكل صريح المعلمة كمجموعة من الكائنات. إذا تم توفير كائن واحد ، فسيتم لفه.
params do
requires :json , type : Array [ JSON ] do
requires :int , type : Integer
end
end
get '/' do
params [ :json ] . each { | obj | ... } # always works
end للتحكم الأكثر صرامة في نوع بنية JSON التي يمكن توفيرها ، استخدم type: Array, coerce_with: JSON أو type: Hash, coerce_with: JSON .
يمكن إعلان المعلمات من النوع المتغير باستخدام خيار types بدلاً من type :
params do
requires :status_code , types : [ Integer , String , Array [ Integer , String ] ]
end
get '/' do
params [ :status_code ] . inspect
end
client . get ( '/' , status_code : 'OK_GOOD' ) # => "OK_GOOD"
client . get ( '/' , status_code : 300 ) # => 300
client . get ( '/' , status_code : %w( 404 NOT FOUND ) ) # => [404, "NOT", "FOUND"] كحالة خاصة ، قد يتم أيضًا الإعلان عن مجموعات من النوع المتغير ، من خلال تمرير Set أو Array مع أكثر من عضو واحد type :
params do
requires :status_codes , type : Array [ Integer , String ]
end
get '/' do
params [ :status_codes ] . inspect
end
client . get ( '/' , status_codes : %w( 1 two ) ) # => [1, "two"] يمكن تداخل المعلمات باستخدام group أو عن طريق الاتصال requires أو optional مع كتلة. في المثال أعلاه ، هذا يعني أن params[:media][:url] مطلوب مع params[:id] ، و params[:audio][:format] فقط إذا كانت params[:audio] موجودة. مع كتلة ، group ، requires وقبول optional type خيار إضافي يمكن أن يكون إما Array أو Hash ، والافتراضات إلى Array . اعتمادًا على القيمة ، سيتم التعامل مع المعلمات المتداخلة إما كقيم تجزئة أو كقيم تجزئة في صفيف.
params do
optional :preferences , type : Array do
requires :key
requires :value
end
requires :name , type : Hash do
requires :first_name
requires :last_name
end
end لنفترض أن بعض المعلمات الخاصة بك ذات صلة فقط إذا تم إعطاء معلمة أخرى ؛ يتيح لك العنب التعبير عن هذه العلاقة من خلال الطريقة given في كتلة المعلمات الخاصة بك ، مثل ذلك:
params do
optional :shelf_id , type : Integer
given :shelf_id do
requires :bin_id , type : Integer
end
end في المثال أعلاه العنب سوف يستخدم blank? للتحقق مما إذا كان المراوغة shelf_id موجودة.
given يأخذ أيضًا Proc مع رمز مخصص. أدناه ، لا يلزم description Param إلا إذا كانت قيمة category متساوية foo :
params do
optional :category
given category : -> ( val ) { val == 'foo' } do
requires :description
end
endيمكنك إعادة تسمية المعلمات:
params do
optional :category , as : :type
given type : -> ( val ) { val == 'foo' } do
requires :description
end
end ملاحظة: يجب أن يكون Param In given هو واحد. في المثال ، يجب أن يكون type ، وليس category .
يمكن تجميع خيارات المعلمات. يمكن أن يكون مفيدًا إذا كنت ترغب في استخراج التحقق من الصحة الشائعة لعدة معلمات. ضمن هذه المجموعات ، يمكن للمعلمات الفردية تمديد أو تجاوز الإعدادات الشائعة بشكل انتقائي ، مما يتيح لك الحفاظ على الإعدادات الافتراضية على مستوى المجموعة مع الاستمرار في تطبيق القواعد الخاصة بالمعلمة عند الضرورة.
يعرض المثال أدناه حالة نموذجية عندما تشترك المعلمات في الخيارات الشائعة.
params do
requires :first_name , type : String , regexp : /w+/ , desc : 'First name' , documentation : { in : 'body' }
optional :middle_name , type : String , regexp : /w+/ , desc : 'Middle name' , documentation : { in : 'body' , x : { nullable : true } }
requires :last_name , type : String , regexp : /w+/ , desc : 'Last name' , documentation : { in : 'body' }
end يسمح لك العنب بتقديم نفس المنطق من خلال الطريقة with كتلة المعلمات الخاصة بك ، مثل ذلك:
params do
with ( type : String , regexp : /w+/ , documentation : { in : 'body' } ) do
requires :first_name , desc : 'First name'
optional :middle_name , desc : 'Middle name' , documentation : { x : { nullable : true } }
requires :last_name , desc : 'Last name'
end
endيمكنك تنظيم الإعدادات في طبقات باستخدام كتل متداخلة "مع". يمكن لكل طبقة استخدام أو إضافة أو تغيير إعدادات الطبقة فوقها. هذا يساعد على الحفاظ على المعلمات المعقدة منظمة ومتسقة ، مع السماح بتخصيصات محددة.
params do
with ( documentation : { in : 'body' } ) do # Applies documentation to all nested parameters
with ( type : String , regexp : / w +/ ) do # Applies type and validation to names
requires :first_name , desc : 'First name'
requires :last_name , desc : 'Last name'
end
optional :age , type : Integer , desc : 'Age' , documentation : { x : { nullable : true } } # Specific settings for 'age'
end
end يمكنك إعادة تسمية المعلمات باستخدام as ، والتي يمكن أن تكون مفيدة عند إعادة إنشاء واجهات برمجة التطبيقات الحالية:
resource :users do
params do
requires :email_address , as : :email
requires :password
end
post do
User . create! ( declared ( params ) ) # User takes email and password
end
end القيمة التي تم تمريرها as ستكون المفتاح عند الاتصال declared(params) .
allow_blank يمكن تعريف المعلمات على أنها allow_blank ، مما يضمن أنها تحتوي على قيمة. بشكل افتراضي ، requires التحقق من صحة فقط أنه تم إرسال المعلمة في الطلب ، بغض النظر عن قيمتها. باستخدام allow_blank: false أو فارغة أو قيم بيضاء فقط غير صالحة.
يمكن الجمع بين allow_blank مع كل من requires optional . إذا كانت المعلمة مطلوبة ، فيجب أن تحتوي على قيمة. إذا كان الأمر اختياريًا ، فمن الممكن عدم إرساله في الطلب ، ولكن إذا تم إرساله ، فيجب أن يكون له بعض القيمة ، وليس سلسلة بيضاء فارغة فقط.
params do
requires :username , allow_blank : false
optional :first_name , allow_blank : false
end values يمكن تقييد المعلمات على مجموعة محددة من القيم مع خيار :values .
params do
requires :status , type : Symbol , values : [ :not_started , :processing , :done ]
optional :numbers , type : Array [ Integer ] , default : 1 , values : [ 1 , 2 , 3 , 5 , 8 ]
end يضمن توفير نطاق إلى خيار :values أن تكون المعلمة (أو المعلمات) مدرجة في هذا النطاق (باستخدام Range#include? ).
params do
requires :latitude , type : Float , values : - 90.0 ..+ 90.0
requires :longitude , type : Float , values : - 180.0 ..+ 180.0
optional :letters , type : Array [ String ] , values : 'a' .. 'z'
endملاحظة يتم دعم النطاقات التي لا نهاية لها أيضًا مع ActivesUpport> = 6.0 ، لكنها تتطلب توفير النوع.
params do
requires :minimum , type : Integer , values : 10 ..
optional :maximum , type : Integer , values : .. 10
end لاحظ أن كلا من نقاط النهاية يجب أن تكون #kind_of? خيار :type (إذا لم تقم بتوفير خيار :type ، فسيتم تخمينه ليكون مساوياً لفئة نقطة النهاية الأولى للنطاق). لذا فإن ما يلي غير صالح:
params do
requires :invalid1 , type : Float , values : 0 .. 10 # 0.kind_of?(Float) => false
optional :invalid2 , values : 0 .. 10.0 # 10.0.kind_of?(0.class) => false
end يمكن أيضًا تزويد خيار :values باستخدام Proc ، تم تقييمه بتكاسل مع كل طلب. إذا كان لدى Proc arity Zero (أي أنه لا يتطلب أي وسيطات) ، فمن المتوقع أن يعيد إما قائمة أو نطاق سيتم استخدامه بعد ذلك للتحقق من صحة المعلمة.
على سبيل المثال ، بالنظر إلى نموذج الحالة قد ترغب في تقييد علامات التجزئة التي سبق أن حددتها في نموذج HashTag .
params do
requires :hashtag , type : String , values : -> { Hashtag . all . map ( & :tag ) }
endبدلاً من ذلك ، يمكن استخدام Proc with Arity One (أي أخذ وسيطة واحدة) للتحقق من صحة كل قيمة معلمة بشكل صريح. في هذه الحالة ، من المتوقع أن تقوم Proc بإرجاع قيمة الحقيقة إذا كانت قيمة المعلمة صالحة. ستعتبر المعلمة غير صالحة إذا قام PROC بإرجاع قيمة falsy أو إذا كانت ترفع قياسيًا.
params do
requires :number , type : Integer , values : -> ( v ) { v . even? && v < 25 }
endعلى الرغم من أن PROCs مريحة للحالات الفردية ، فكر في استخدام مصادقة مخصصة في الحالات التي يتم فيها استخدام التحقق من الصحة أكثر من مرة.
لاحظ أن المدقق المسموح به left_blank ينطبق أثناء استخدام :values . في المثال التالي ، لا يمنع غياب :allow_blank :state من تلقي قيم فارغة لأن :allow_blank الافتراضيات إلى true .
params do
requires :state , type : Symbol , values : [ :active , :inactive ]
end except_values يمكن تقييد المعلمات من وجود مجموعة محددة من القيم مع خيار :except_values .
يتصرف مدقق except_values بشكل مشابه لمقحة values من حيث أنه يقبل إما صفيف أو نطاق أو proc. على عكس المدقق values ، باستثناء except_values يقبل فقط procs مع arity Zero.
params do
requires :browser , except_values : [ 'ie6' , 'ie7' , 'ie8' ]
requires :port , except_values : { value : 0 .. 1024 , message : 'is not allowed' }
requires :hashtag , except_values : -> { Hashtag . FORBIDDEN_LIST }
end same_as يمكن إعطاء خيار same_as لضمان تطابق قيم المعلمات.
params do
requires :password
requires :password_confirmation , same_as : :password
end length يمكن تقييد المعلمات ذات الأنواع التي تدعم طريقة #length على طول محدد مع خيار :length .
يقبل المدقق :min أو :max أو كلا الخيارين أو فقط :is التحقق من صحة أن قيمة المعلمة ضمن الحدود المحددة.
params do
requires :code , type : String , length : { is : 2 }
requires :str , type : String , length : { min : 3 }
requires :list , type : [ Integer ] , length : { min : 3 , max : 5 }
requires :hash , type : Hash , length : { max : 5 }
end regexp يمكن أن تقتصر المعلمات على مطابقة تعبير منتظم محدد مع خيار :regexp . إذا كانت القيمة لا تتطابق مع التعبير العادي ، فسيتم إرجاع خطأ. لاحظ أن هذا صحيح لكليهما requires والمعلمات optional .
params do
requires :email , regexp : /.+@.+/
end سيتم تمرير المدقق إذا تم إرسال المعلمة بدون قيمة. للتأكد من أن المعلمة تحتوي على قيمة ، استخدم allow_blank: false .
params do
requires :email , allow_blank : false , regexp : /.+@.+/
end mutually_exclusive يمكن تعريف المعلمات على أنها mutually_exclusive ، مما يضمن عدم وجودها في نفس الوقت في طلب ما.
params do
optional :beer
optional :wine
mutually_exclusive :beer , :wine
endيمكن تعريف مجموعات متعددة:
params do
optional :beer
optional :wine
mutually_exclusive :beer , :wine
optional :scotch
optional :aquavit
mutually_exclusive :scotch , :aquavit
endتحذير : لا تحدد أبدًا مجموعات حصرية متبادلة مع أي معاملات مطلوبة. سوف يعني اثنان من المعايير المطلوبة للطرفين أن المعايير ليست صالحة أبدًا ، مما يجعل نقطة النهاية عديمة الفائدة. واحد مطلوب param بشكل متبادل مع param اختياري سوف يعني أن الأخير ليس صالحا أبدا.
exactly_one_ofيمكن تعريف المعلمات على أنها "بالضبط _one_of" ، مما يضمن تحديد معلمة واحدة بالضبط.
params do
optional :beer
optional :wine
exactly_one_of :beer , :wine
end لاحظ أن استخدام :default مع mutually_exclusive سيؤدي إلى وجود معلمات متعددة دائمًا لها قيمة افتراضية ورفع Grape::Exceptions::Validation استثناء حصري بشكل متبادل.
at_least_one_ofيمكن تعريف المعلمات على أنها "AT_LEAST_ON_OF" ، مما يضمن تحديد معلمة واحدة على الأقل.
params do
optional :beer
optional :wine
optional :juice
at_least_one_of :beer , :wine , :juice
end all_or_none_ofيمكن تعريف المعلمات على أنها "all_or_none_of" ، مما يضمن تحديد جميع المعلمات أو لا شيء.
params do
optional :beer
optional :wine
optional :juice
all_or_none_of :beer , :wine , :juice
end mutually_exclusive ، exactly_one_of ، at_least_one_of ، all_or_none_ofكل هذه الطرق يمكن استخدامها على أي مستوى متداخل.
params do
requires :food , type : Hash do
optional :meat
optional :fish
optional :rice
at_least_one_of :meat , :fish , :rice
end
group :drink , type : Hash do
optional :beer
optional :wine
optional :juice
exactly_one_of :beer , :wine , :juice
end
optional :dessert , type : Hash do
optional :cake
optional :icecream
mutually_exclusive :cake , :icecream
end
optional :recipe , type : Hash do
optional :oil
optional :meat
all_or_none_of :oil , :meat
end
endتسمح مساحات الأسماء بتعريفات المعلمة وتطبق على كل طريقة داخل مساحة الاسم.
namespace :statuses do
params do
requires :user_id , type : Integer , desc : 'A user ID.'
end
namespace ':user_id' do
desc "Retrieve a user's status."
params do
requires :status_id , type : Integer , desc : 'A status ID.'
end
get ':status_id' do
User . find ( params [ :user_id ] ) . statuses . find ( params [ :status_id ] )
end
end
end تحتوي طريقة namespace على عدد من الأسماء المستعارة ، بما في ذلك: group ، resource ، resources ، segment . استخدم أيهما يقرأ الأفضل في واجهة برمجة التطبيقات الخاصة بك.
يمكنك تحديد معلمة الطريق بسهولة كمساحة اسم باستخدام route_param .
namespace :statuses do
route_param :id do
desc 'Returns all replies for a status.'
get 'replies' do
Status . find ( params [ :id ] ) . replies
end
desc 'Returns a status.'
get do
Status . find ( params [ :id ] )
end
end
end يمكنك أيضًا تحديد نوع معلمة الطريق عن طريق تمرير خيارات route_param .
namespace :arithmetic do
route_param :n , type : Integer do
desc 'Returns in power'
get 'power' do
params [ :n ] ** params [ :n ]
end
end
end class AlphaNumeric < Grape :: Validations :: Validators :: Base
def validate_param! ( attr_name , params )
unless params [ attr_name ] =~ / A [[:alnum:]]+ z /
raise Grape :: Exceptions :: Validation . new params : [ @scope . full_name ( attr_name ) ] , message : 'must consist of alpha-numeric characters'
end
end
end params do
requires :text , alpha_numeric : true
endيمكنك أيضًا إنشاء فئات مخصصة تأخذ المعلمات.
class Length < Grape :: Validations :: Validators :: Base
def validate_param! ( attr_name , params )
unless params [ attr_name ] . length <= @option
raise Grape :: Exceptions :: Validation . new params : [ @scope . full_name ( attr_name ) ] , message : "must be at the most #{ @option } characters long"
end
end
end params do
requires :text , length : 140
endيمكنك أيضًا إنشاء التحقق المخصص الذي يستخدم طلب التحقق من صحة السمة. على سبيل المثال ، إذا كنت ترغب في الحصول على معلمات متاحة للمسؤولين فقط ، فيمكنك القيام بما يلي.
class Admin < Grape :: Validations :: Validators :: Base
def validate ( request )
# return if the param we are checking was not in request
# @attrs is a list containing the attribute we are currently validating
# in our sample case this method once will get called with
# @attrs being [:admin_field] and once with @attrs being [:admin_false_field]
return unless request . params . key? ( @attrs . first )
# check if admin flag is set to true
return unless @option
# check if user is admin or not
# as an example get a token from request and check if it's admin or not
raise Grape :: Exceptions :: Validation . new params : @attrs , message : 'Can not set admin-only field.' unless request . headers [ 'X-Access-Token' ] == 'admin'
end
endواستخدمه في تعريف نقطة النهاية الخاصة بك على النحو التالي:
params do
optional :admin_field , type : String , admin : true
optional :non_admin_field , type : String
optional :admin_false_field , type : String , admin : false
endسيكون لكل التحقق مثيله الخاص للمقحة ، مما يعني أن المدقق يمكن أن يكون له حالة.
يتم جمع أخطاء التحقق من الصحة والإكراه واستثناء من النوع Grape::Exceptions::ValidationErrors . إذا كان الاستثناء غير معلوم ، فسيستجيب بحالة 400 ورسالة خطأ. يتم تجميع أخطاء التحقق من صحة اسم المعلمة ويمكن الوصول إليها عبر Grape::Exceptions::ValidationErrors#errors .
الاستجابة الافتراضية من Grape::Exceptions::ValidationErrors هي سلسلة قابلة للقراءة بشكل إنساني ، مثل "البيرة ، النبيذ حصري بشكل متبادل" ، في المثال التالي.
params do
optional :beer
optional :wine
optional :juice
exactly_one_of :beer , :wine , :juice
end يمكنك إنقاذ Grape::Exceptions::ValidationErrors والرد مع استجابة مخصصة أو تحويل الاستجابة إلى JSON المنسقة جيدًا لاتحاد JSON API الذي يفصل بين المعلمات الفردية ورسائل الخطأ المقابلة. ينتج مثال rescue_from التالي [{"params":["beer","wine"],"messages":["are mutually exclusive"]}] .
format :json
subject . rescue_from Grape :: Exceptions :: ValidationErrors do | e |
error! e , 400
end Grape::Exceptions::ValidationErrors#full_messages إرجاع رسائل التحقق من الصحة كصفيف. Grape::Exceptions::ValidationErrors#message الرسائل إلى سلسلة واحدة.
للرد مع مجموعة من رسائل التحقق من الصحة ، يمكنك استخدام Grape::Exceptions::ValidationErrors#full_messages .
format :json
subject . rescue_from Grape :: Exceptions :: ValidationErrors do | e |
error! ( { messages : e . full_messages } , 400 )
end يعيد العنب جميع أخطاء التحقق من الصحة والإكراه الموجودة بشكل افتراضي. لتخطي جميع عمليات التحقق من الصحة اللاحقة عند العثور على معاملة محددة غير صالحة ، استخدم fail_fast: true .
المثال التالي لن يتحقق من :wine موجود ما لم يجد :beer .
params do
required :beer , fail_fast : true
required :wine
end ستكون نتيجة المعاملات الفارغة عبارة عن Grape::Exceptions::ValidationErrors
وبالمثل ، لن يتم إجراء أي اختبار تعبير منتظم إذا :blah فارغ في المثال التالي.
params do
required :blah , allow_blank : false , regexp : /blah/ , fail_fast : true
endيدعم Grape I18N لرسائل الخطأ المتعلقة بالمعلمة ، ولكن سيتم الاحتفاظ بالإنجليزية إذا لم يتم تقديم ترجمات للمحطة الافتراضية. انظر en.yml للحصول على مفاتيح الرسائل.
في حالة قيام تطبيقك بتطبيق اللغات المتاحة فقط و: EN غير مدرج في أماكنك المتاحة ، لا يمكن أن يعود العنب إلى اللغة الإنجليزية وسيعود مفتاح الترجمة لرسالة الخطأ. لتجنب هذا السلوك ، إما تقديم ترجمة لموقعك الافتراضي أو إضافة: en إلى أماكنك المتاحة.
يدعم العنب رسائل التحقق من الصحة المخصصة لرسائل الخطأ المتعلقة بالمعلمة والمرتبطة بالمعلمة.
presence ، allow_blank ، values ، regexp params do
requires :name , values : { value : 1 .. 10 , message : 'not in range from 1 to 10' } , allow_blank : { value : false , message : 'cannot be blank' } , regexp : { value : /^[a-z]+$/ , message : 'format is invalid' } , message : 'is required'
end same_as params do
requires :password
requires :password_confirmation , same_as : { value : :password , message : 'not match' }
end length params do
requires :code , type : String , length : { is : 2 , message : 'code is expected to be exactly 2 characters long' }
requires :str , type : String , length : { min : 5 , message : 'str is expected to be atleast 5 characters long' }
requires :list , type : [ Integer ] , length : { min : 2 , max : 3 , message : 'list is expected to have between 2 and 3 elements' }
end all_or_none_of params do
optional :beer
optional :wine
optional :juice
all_or_none_of :beer , :wine , :juice , message : "all params are required or none is required"
end mutually_exclusive params do
optional :beer
optional :wine
optional :juice
mutually_exclusive :beer , :wine , :juice , message : "are mutually exclusive cannot pass both params"
end exactly_one_of params do
optional :beer
optional :wine
optional :juice
exactly_one_of :beer , :wine , :juice , message : { exactly_one : "are missing, exactly one parameter is required" , mutual_exclusion : "are mutually exclusive, exactly one parameter is required" }
end at_least_one_of params do
optional :beer
optional :wine
optional :juice
at_least_one_of :beer , :wine , :juice , message : "are missing, please specify at least one param"
end Coerce params do
requires :int , type : { value : Integer , message : "type cast is invalid" }
end With Lambdas params do
requires :name , values : { value : -> { ( 1 .. 10 ) . to_a } , message : 'not in range from 1 to 10' }
end Pass symbols for i18n translationsيمكنك تمرير رمز إذا كنت تريد ترجمات I18N لرسائل التحقق من الصحة المخصصة.
params do
requires :name , message : :name_required
end # en.yml
en :
grape :
errors :
format : ! '%{attributes} %{message}'
messages :
name_required : 'must be present' يمكنك أيضًا تجاوز أسماء السمات.
# en.yml
en :
grape :
errors :
format : ! '%{attributes} %{message}'
messages :
name_required : 'must be present'
attributes :
name : 'Oops! Name'سوف تنتج عفوًا! يجب أن يكون الاسم موجودًا
لا يمكنك تعيين خيار رسالة مخصصة للإعداد لأنه يتطلب interpolation %{option1}: %{value1} is incompatible with %{option2}: %{value2} . يمكنك تغيير رسالة الخطأ الافتراضية للإعداد الافتراضي عن طريق تغيير مفتاح رسالة incompatible_option_values داخل en.yml
params do
requires :name , values : { value : -> { ( 1 .. 10 ) . to_a } , message : 'not in range from 1 to 10' } , default : 5
enddry-validation أو dry-schema كبديل لـ params DSL الموضحة أعلاه ، يمكنك استخدام مخطط أو عقد dry-validation لوصف معلمات نقطة النهاية. يمكن أن يكون هذا مفيدًا بشكل خاص إذا كنت تستخدم ما سبق بالفعل في بعض الأجزاء الأخرى من التطبيق الخاص بك. إذا لم يكن الأمر كذلك ، فستحتاج إلى إضافة dry-validation أو dry-schema إلى Gemfile .
ثم استدعاء contract مع عقد أو مخطط محدد سابقًا:
CreateOrdersSchema = Dry :: Schema . Params do
required ( :orders ) . array ( :hash ) do
required ( :name ) . filled ( :string )
optional ( :volume ) . maybe ( :integer , lt? : 9 )
end
end
# ...
contract CreateOrdersSchemaأو مع كتلة ، باستخدام بناء جملة تعريف المخطط:
contract do
required ( :orders ) . array ( :hash ) do
required ( :name ) . filled ( :string )
optional ( :volume ) . maybe ( :integer , lt? : 9 )
end
end هذا الأخير سيحدد مخطط الإكراه ( Dry::Schema.Params ). عند استخدام النهج السابق ، فإن الأمر متروك لك لتقرير ما إذا كانت المدخلات ستحتاج إلى الإكراه.
يمكن أيضًا استخدام params and contract Contractions معًا في نفس واجهة برمجة التطبيقات ، على سبيل المثال لوصف أجزاء مختلفة من مساحة الاسم المتداخلة لنقطة نهاية.
تتوفر رؤوس الطلبات من خلال headers Helper أو من env في شكلها الأصلي.
get do
error! ( 'Unauthorized' , 401 ) unless headers [ 'Secret-Password' ] == 'swordfish'
end get do
error! ( 'Unauthorized' , 401 ) unless env [ 'HTTP_SECRET_PASSWORD' ] == 'swordfish'
end ربما تم طلب المثال أعلاه على النحو التالي:
curl -H " secret_PassWord: swordfish " ...سيتم تطبيع اسم الرأس لك.
header Helper سيتم إجبارها على قضية Kebab المعلنة ككلمة secret-password إذا كنت تستخدم Rack 3.header Helper سيتم إجبارها على قضية Kebab ذات الرسملة ككلمة Secret-PassWord إذا كنت تستخدم Rack <3.env ، تظهر في جميع الأحرف الكبيرة ، في حالة الثعبان ، وسباقها بـ "http_" كـ HTTP_SECRET_PASSWORDسيتم تطبيع اسم الرأس لكل معايير HTTP المحددة في RFC2616 القسم 4.2 بغض النظر عن ما يتم إرساله من قبل العميل.
يمكنك تعيين رأس استجابة مع header داخل واجهة برمجة التطبيقات.
header 'X-Robots-Tag' , 'noindex' عند رفع error! ، تمرير رؤوس إضافية كحجيلات. سيتم دمج رؤوس إضافية مع رؤوس محددة قبل error! يتصل.
error! 'Unauthorized' , 401 , 'X-Error-Detail' => 'Invalid token.' لتحديد الطرق ، يمكنك استخدام طريقة route أو الاختزال لأفعال HTTP. لتحديد مسار يقبل أي مسار تم تعيينه إلى :any . سيتم تفسير أجزاء من المسار الذي يتم الإشارة إليه مع القولون على أنه معلمات الطريق.
route :get , 'status' do
end
# is the same as
get 'status' do
end
# is the same as
get :status do
end
# is NOT the same as
get ':status' do # this makes params[:status] available
end
# This will make both params[:status_id] and params[:id] available
get 'statuses/:status_id/reviews/:id' do
end لإعلان مساحة الاسم التي تسبق جميع الطرق داخلها ، استخدم طريقة namespace . group resource resources segment هي أسماء مستعارة لهذه الطريقة. ستشارك أي نقاط نهاية داخل سياق الوالدين وأي تكوين يتم في سياق مساحة الاسم.
طريقة route_param هي طريقة مريحة لتحديد شريحة مسار المعلمة. إذا حددت نوعًا ما ، فسيضيف التحقق من صحة هذه المعلمة.
route_param :id , type : Integer do
get 'status' do
end
end
# is the same as
namespace ':id' do
params do
requires :id , type : Integer
end
get 'status' do
end
endاختياريا ، يمكنك تحديد متطلبات معلمات الطريق المسماة باستخدام تعبيرات منتظمة على مساحة الاسم أو نقطة النهاية. لن يتطابق المسار إلا إذا تم استيفاء جميع المتطلبات.
get ':id' , requirements : { id : /[0-9]*/ } do
Status . find ( params [ :id ] )
end
namespace :outer , requirements : { id : /[0-9]*/ } do
get :id do
end
get ':id/edit' do
end
end يمكنك تحديد طرق المساعد التي يمكن أن تستخدمها نقاط النهاية الخاصة بك مع ماكرو helpers إما عن طريق إعطاء كتلة أو مجموعة من الوحدات النمطية.
module StatusHelpers
def user_info ( user )
" #{ user } has statused #{ user . statuses } status(s)"
end
end
module HttpCodesHelpers
def unauthorized
401
end
end
class API < Grape :: API
# define helpers with a block
helpers do
def current_user
User . find ( params [ :user_id ] )
end
end
# or mix in an array of modules
helpers StatusHelpers , HttpCodesHelpers
before do
error! ( 'Access Denied' , unauthorized ) unless current_user
end
get 'info' do
# helpers available in your endpoint and filters
user_info ( current_user )
end
end يمكنك تحديد params القابلة لإعادة الاستخدام باستخدام helpers .
class API < Grape :: API
helpers do
params :pagination do
optional :page , type : Integer
optional :per_page , type : Integer
end
end
desc 'Get collection'
params do
use :pagination # aliases: includes, use_scope
end
get do
Collection . page ( params [ :page ] ) . per ( params [ :per_page ] )
end
end يمكنك أيضًا تحديد params القابلة لإعادة الاستخدام باستخدام المساعدين المشتركين.
module SharedParams
extend Grape :: API :: Helpers
params :period do
optional :start_date
optional :end_date
end
params :pagination do
optional :page , type : Integer
optional :per_page , type : Integer
end
end
class API < Grape :: API
helpers SharedParams
desc 'Get collection.'
params do
use :period , :pagination
end
get do
Collection
. from ( params [ :start_date ] )
. to ( params [ :end_date ] )
. page ( params [ :page ] )
. per ( params [ :per_page ] )
end
end كتل دعم المساعدين التي يمكن أن تساعد في تعيين القيم الافتراضية. يمكن لـ API التالية إرجاع مجموعة تم فرزها بواسطة id أو created_at بترتيب asc أو desc .
module SharedParams
extend Grape :: API :: Helpers
params :order do | options |
optional :order_by , type : Symbol , values : options [ :order_by ] , default : options [ :default_order_by ]
optional :order , type : Symbol , values : %i( asc desc ) , default : options [ :default_order ]
end
end
class API < Grape :: API
helpers SharedParams
desc 'Get a sorted collection.'
params do
use :order , order_by : %i( id created_at ) , default_order_by : :created_at , default_order : :asc
end
get do
Collection . send ( params [ :order ] , params [ :order_by ] )
end
end إذا كنت بحاجة إلى طرق لتوليد مسارات داخل نقاط النهاية الخاصة بك ، فيرجى الاطلاع على جوهرة العنب-Route-Helpers.
يمكنك إرفاق وثائق إضافية إلى params باستخدام تجزئة documentation .
params do
optional :first_name , type : String , documentation : { example : 'Jim' }
requires :last_name , type : String , documentation : { example : 'Smith' }
endإذا لم تكن الوثائق مطلوبة (على سبيل المثال ، فهي واجهة برمجة تطبيقات داخلية) ، فيمكن تعطيل الوثائق.
class API < Grape :: API
do_not_document!
# endpoints...
endفي هذه الحالة ، لن ينشئ العنب كائنات تتعلق بالوثائق التي يتم الاحتفاظ بها في ذاكرة الوصول العشوائي إلى الأبد.
يمكنك ضبط ملفات تعريف الارتباط والحصول عليها وحذفها ببساطة باستخدام طريقة cookies .
class API < Grape :: API
get 'status_count' do
cookies [ :status_count ] ||= 0
cookies [ :status_count ] += 1
{ status_count : cookies [ :status_count ] }
end
delete 'status_count' do
{ status_count : cookies . delete ( :status_count ) }
end
endاستخدم بناء جملة قائم على التجزئة لتعيين أكثر من قيمة واحدة.
cookies [ :status_count ] = {
value : 0 ,
expires : Time . tomorrow ,
domain : '.twitter.com' ,
path : '/'
}
cookies [ :status_count ] [ :value ] += 1 حذف ملف تعريف ارتباط مع delete .
cookies . delete :status_countتحديد مسار اختياري.
cookies . delete :status_count , path : '/' بشكل افتراضي ، يقوم العنب بإرجاع 201 لـ POST -requests ، و 204 لـ DELETE -requests التي لا تُرجع أي محتوى ، و 200 رمز حالة لجميع الطلبات الأخرى. يمكنك استخدام status للاستعلام وتعيين رمز حالة HTTP الفعلي
post do
status 202
if status == 200
# do some thing
end
endYou can also use one of status codes symbols that are provided by Rack utils
post do
status :no_content
end You can redirect to a new url temporarily (302) or permanently (301).
redirect '/statuses' redirect '/statuses' , permanent : true You can recognize the endpoint matched with given path.
This API returns an instance of Grape::Endpoint .
class API < Grape :: API
get '/statuses' do
end
end
API . recognize_path '/statuses' Since version 2.1.0 , the recognize_path method takes into account the parameters type to determine which endpoint should match with given path.
class Books < Grape :: API
resource :books do
route_param :id , type : Integer do
# GET /books/:id
get do
#...
end
end
resource :share do
# POST /books/share
post do
# ....
end
end
end
end
API . recognize_path '/books/1' # => /books/:id
API . recognize_path '/books/share' # => /books/share
API . recognize_path '/books/other' # => nil When you add a GET route for a resource, a route for the HEAD method will also be added automatically. You can disable this behavior with do_not_route_head! .
class API < Grape :: API
do_not_route_head!
get '/example' do
# only responds to GET
end
end When you add a route for a resource, a route for the OPTIONS method will also be added. The response to an OPTIONS request will include an "Allow" header listing the supported methods. If the resource has before and after callbacks they will be executed, but no other callbacks will run.
class API < Grape :: API
get '/rt_count' do
{ rt_count : current_user . rt_count }
end
params do
requires :value , type : Integer , desc : 'Value to add to the rt count.'
end
put '/rt_count' do
current_user . rt_count += params [ :value ] . to_i
{ rt_count : current_user . rt_count }
end
end curl -v -X OPTIONS http://localhost:3000/rt_count
> OPTIONS /rt_count HTTP/1.1
>
< HTTP/1.1 204 No Content
< Allow: OPTIONS, GET, PUT You can disable this behavior with do_not_route_options! .
If a request for a resource is made with an unsupported HTTP method, an HTTP 405 (Method Not Allowed) response will be returned. If the resource has before callbacks they will be executed, but no other callbacks will run.
curl -X DELETE -v http://localhost:3000/rt_count/
> DELETE /rt_count/ HTTP/1.1
> Host: localhost:3000
>
< HTTP/1.1 405 Method Not Allowed
< Allow: OPTIONS, GET, PUT You can abort the execution of an API method by raising errors with error! .
error! 'Access Denied' , 401 Anything that responds to #to_s can be given as a first argument to error! .
error! :not_found , 404You can also return JSON formatted objects by raising error! and passing a hash instead of a message.
error! ( { error : 'unexpected error' , detail : 'missing widget' } , 500 ) You can set additional headers for the response. They will be merged with headers set before error! يتصل.
error! ( 'Something went wrong' , 500 , 'X-Error-Detail' => 'Invalid token.' )You can present documented errors with a Grape entity using the the grape-entity gem.
module API
class Error < Grape :: Entity
expose :code
expose :message
end
end The following example specifies the entity to use in the http_codes definition.
desc 'My Route' do
failure [ [ 408 , 'Unauthorized' , API :: Error ] ]
end
error! ( { message : 'Unauthorized' } , 408 )The following example specifies the presented entity explicitly in the error message.
desc 'My Route' do
failure [ [ 408 , 'Unauthorized' ] ]
end
error! ( { message : 'Unauthorized' , with : API :: Error } , 408 ) By default Grape returns a 500 status code from error! . You can change this with default_error_status .
class API < Grape :: API
default_error_status 400
get '/example' do
error! 'This should have http status code 400'
end
endFor Grape to handle all the 404s for your API, it can be useful to use a catch-all. In its simplest form, it can be like:
route :any , '*path' do
error! # or something else
endIt is very crucial to define this endpoint at the very end of your API , as it literally accepts every request.
Grape can be told to rescue all StandardError exceptions and return them in the API format.
class Twitter :: API < Grape :: API
rescue_from :all
end This mimics default rescue behaviour when an exception type is not provided. Any other exception should be rescued explicitly, see below.
Grape can also rescue from all exceptions and still use the built-in exception handing. This will give the same behavior as rescue_from :all with the addition that Grape will use the exception handling defined by all Exception classes that inherit Grape::Exceptions::Base .
The intent of this setting is to provide a simple way to cover the most common exceptions and return any unexpected exceptions in the API format.
class Twitter :: API < Grape :: API
rescue_from :grape_exceptions
end If you want to customize the shape of grape exceptions returned to the user, to match your :all handler for example, you can pass a block to rescue_from :grape_exceptions .
rescue_from :grape_exceptions do | e |
error! ( e , e . status )
endYou can also rescue specific exceptions.
class Twitter :: API < Grape :: API
rescue_from ArgumentError , UserDefinedError
end In this case UserDefinedError must be inherited from StandardError .
Notice that you could combine these two approaches (rescuing custom errors takes precedence). For example, it's useful for handling all exceptions except Grape validation errors.
class Twitter :: API < Grape :: API
rescue_from Grape :: Exceptions :: ValidationErrors do | e |
error! ( e , 400 )
end
rescue_from :all
endThe error format will match the request format. See "Content-Types" below.
Custom error formatters for existing and additional types can be defined with a proc.
class Twitter :: API < Grape :: API
error_formatter :txt , -> ( message , backtrace , options , env , original_exception ) {
"error: #{ message } from #{ backtrace } "
}
endYou can also use a module or class.
module CustomFormatter
def self . call ( message , backtrace , options , env , original_exception )
{ message : message , backtrace : backtrace }
end
end
class Twitter :: API < Grape :: API
error_formatter :custom , CustomFormatter
end You can rescue all exceptions with a code block. The error! wrapper automatically sets the default error code and content-type.
class Twitter :: API < Grape :: API
rescue_from :all do | e |
error! ( "rescued from #{ e . class . name } " )
end
endOptionally, you can set the format, status code and headers.
class Twitter :: API < Grape :: API
format :json
rescue_from :all do | e |
error! ( { error : 'Server error.' } , 500 , { 'Content-Type' => 'text/error' } )
end
endYou can also rescue all exceptions with a code block and handle the Rack response at the lowest level.
class Twitter :: API < Grape :: API
rescue_from :all do | e |
Rack :: Response . new ( [ e . message ] , 500 , { 'Content-type' => 'text/error' } )
end
endOr rescue specific exceptions.
class Twitter :: API < Grape :: API
rescue_from ArgumentError do | e |
error! ( "ArgumentError: #{ e . message } " )
end
rescue_from NoMethodError do | e |
error! ( "NoMethodError: #{ e . message } " )
end
end By default, rescue_from will rescue the exceptions listed and all their subclasses.
Assume you have the following exception classes defined.
module APIErrors
class ParentError < StandardError ; end
class ChildError < ParentError ; end
end Then the following rescue_from clause will rescue exceptions of type APIErrors::ParentError and its subclasses (in this case APIErrors::ChildError ).
rescue_from APIErrors :: ParentError do | e |
error! ( {
error : " #{ e . class } error" ,
message : e . message
} , e . status )
end To only rescue the base exception class, set rescue_subclasses: false . The code below will rescue exceptions of type RuntimeError but not its subclasses.
rescue_from RuntimeError , rescue_subclasses : false do | e |
error! ( {
status : e . status ,
message : e . message ,
errors : e . errors
} , e . status )
end Helpers are also available inside rescue_from .
class Twitter :: API < Grape :: API
format :json
helpers do
def server_error!
error! ( { error : 'Server error.' } , 500 , { 'Content-Type' => 'text/error' } )
end
end
rescue_from :all do | e |
server_error!
end
end The rescue_from handler must return a Rack::Response object, call error! , or raise an exception (either the original exception or another custom one). The exception raised in rescue_from will be handled outside Grape. For example, if you mount Grape in Rails, the exception will be handle by Rails Action Controller.
Alternately, use the with option in rescue_from to specify a method or a proc .
class Twitter :: API < Grape :: API
format :json
helpers do
def server_error!
error! ( { error : 'Server error.' } , 500 , { 'Content-Type' => 'text/error' } )
end
end
rescue_from :all , with : :server_error!
rescue_from ArgumentError , with : -> { Rack :: Response . new ( 'rescued with a method' , 400 ) }
end Inside the rescue_from block, the environment of the original controller method( .self receiver) is accessible through the #context method.
class Twitter :: API < Grape :: API
rescue_from :all do | e |
user_id = context . params [ :user_id ]
error! ( "error for #{ user_id } " )
end
end You could put rescue_from clauses inside a namespace and they will take precedence over ones defined in the root scope:
class Twitter :: API < Grape :: API
rescue_from ArgumentError do | e |
error! ( "outer" )
end
namespace :statuses do
rescue_from ArgumentError do | e |
error! ( "inner" )
end
get do
raise ArgumentError . new
end
end
end Here 'inner' will be result of handling occurred ArgumentError .
Grape::Exceptions::InvalidVersionHeader , which is raised when the version in the request header doesn't match the currently evaluated version for the endpoint, will never be rescued from a rescue_from block (even a rescue_from :all ) This is because Grape relies on Rack to catch that error and try the next versioned-route for cases where there exist identical Grape endpoints with different versions.
Any exception that is not subclass of StandardError should be rescued explicitly. Usually it is not a case for an application logic as such errors point to problems in Ruby runtime. This is following standard recommendations for exceptions handling.
Grape::API provides a logger method which by default will return an instance of the Logger class from Ruby's standard library.
To log messages from within an endpoint, you need to define a helper to make the logger available in the endpoint context.
class API < Grape :: API
helpers do
def logger
API . logger
end
end
post '/statuses' do
logger . info " #{ current_user } has statused"
end
endTo change the logger level.
class API < Grape :: API
self . logger . level = Logger :: INFO
endYou can also set your own logger.
class MyLogger
def warning ( message )
puts "this is a warning: #{ message } "
end
end
class API < Grape :: API
logger MyLogger . new
helpers do
def logger
API . logger
end
end
get '/statuses' do
logger . warning " #{ current_user } has statused"
end
endFor similar to Rails request logging try the grape_logging or grape-middleware-logger gems.
Your API can declare which content-types to support by using content_type . If you do not specify any, Grape will support XML , JSON , BINARY , and TXT content-types. The default format is :txt ; you can change this with default_format . Essentially, the two APIs below are equivalent.
class Twitter :: API < Grape :: API
# no content_type declarations, so Grape uses the defaults
end
class Twitter :: API < Grape :: API
# the following declarations are equivalent to the defaults
content_type :xml , 'application/xml'
content_type :json , 'application/json'
content_type :binary , 'application/octet-stream'
content_type :txt , 'text/plain'
default_format :txt
end If you declare any content_type whatsoever, the Grape defaults will be overridden. For example, the following API will only support the :xml and :rss content-types, but not :txt , :json , or :binary . Importantly, this means the :txt default format is not supported! So, make sure to set a new default_format .
class Twitter :: API < Grape :: API
content_type :xml , 'application/xml'
content_type :rss , 'application/xml+rss'
default_format :xml
end Serialization takes place automatically. For example, you do not have to call to_json in each JSON API endpoint implementation. The response format (and thus the automatic serialization) is determined in the following order:
format parameter in the query string, if specified.format option, if specified.Accept header.default_format option.:txt .For example, consider the following API.
class MultipleFormatAPI < Grape :: API
content_type :xml , 'application/xml'
content_type :json , 'application/json'
default_format :json
get :hello do
{ hello : 'world' }
end
endGET /hello (with an Accept: */* header) does not have an extension or a format parameter, so it will respond with JSON (the default format).GET /hello.xml has a recognized extension, so it will respond with XML.GET /hello?format=xml has a recognized format parameter, so it will respond with XML.GET /hello.xml?format=json has a recognized extension (which takes precedence over the format parameter), so it will respond with XML.GET /hello.xls (with an Accept: */* header) has an extension, but that extension is not recognized, so it will respond with JSON (the default format).GET /hello.xls with an Accept: application/xml header has an unrecognized extension, but the Accept header corresponds to a recognized format, so it will respond with XML.GET /hello.xls with an Accept: text/plain header has an unrecognized extension and an unrecognized Accept header, so it will respond with JSON (the default format). You can override this process explicitly by calling api_format in the API itself. For example, the following API will let you upload arbitrary files and return their contents as an attachment with the correct MIME type.
class Twitter :: API < Grape :: API
post 'attachment' do
filename = params [ :file ] [ :filename ]
content_type MIME :: Types . type_for ( filename ) [ 0 ] . to_s
api_format :binary # there's no formatter for :binary, data will be returned "as is"
header 'Content-Disposition' , "attachment; filename*=UTF-8'' #{ CGI . escape ( filename ) } "
params [ :file ] [ :tempfile ] . read
end
end You can have your API only respond to a single format with format . If you use this, the API will not respond to file extensions other than specified in format . For example, consider the following API.
class SingleFormatAPI < Grape :: API
format :json
get :hello do
{ hello : 'world' }
end
endGET /hello will respond with JSON.GET /hello.json will respond with JSON.GET /hello.xml , GET /hello.foobar , or any other extension will respond with an HTTP 404 error code.GET /hello?format=xml will respond with an HTTP 406 error code, because the XML format specified by the request parameter is not supported.GET /hello with an Accept: application/xml header will still respond with JSON, since it could not negotiate a recognized content-type from the headers and JSON is the effective default. The formats apply to parsing, too. The following API will only respond to the JSON content-type and will not parse any other input than application/json , application/x-www-form-urlencoded , multipart/form-data , multipart/related and multipart/mixed . All other requests will fail with an HTTP 406 error code.
class Twitter :: API < Grape :: API
format :json
end When the content-type is omitted, Grape will return a 406 error code unless default_format is specified. The following API will try to parse any data without a content-type using a JSON parser.
class Twitter :: API < Grape :: API
format :json
default_format :json
end If you combine format with rescue_from :all , errors will be rendered using the same format. If you do not want this behavior, set the default error formatter with default_error_formatter .
class Twitter :: API < Grape :: API
format :json
content_type :txt , 'text/plain'
default_error_formatter :txt
endCustom formatters for existing and additional types can be defined with a proc.
class Twitter :: API < Grape :: API
content_type :xls , 'application/vnd.ms-excel'
formatter :xls , -> ( object , env ) { object . to_xls }
endYou can also use a module or class.
module XlsFormatter
def self . call ( object , env )
object . to_xls
end
end
class Twitter :: API < Grape :: API
content_type :xls , 'application/vnd.ms-excel'
formatter :xls , XlsFormatter
endBuilt-in formatters are the following.
:json : use object's to_json when available, otherwise call MultiJson.dump:xml : use object's to_xml when available, usually via MultiXml:txt : use object's to_txt when available, otherwise to_s:serializable_hash : use object's serializable_hash when available, otherwise fallback to :json:binary : data will be returned "as is"If a body is present in a request to an API, with a Content-Type header value that is of an unsupported type a "415 Unsupported Media Type" error code will be returned by Grape.
Response statuses that indicate no content as defined by Rack here will bypass serialization and the body entity - though there should be none - will not be modified.
Grape supports JSONP via Rack::JSONP, part of the rack-contrib gem. Add rack-contrib to your Gemfile .
require 'rack/contrib'
class API < Grape :: API
use Rack :: JSONP
format :json
get '/' do
'Hello World'
end
end Grape supports CORS via Rack::CORS, part of the rack-cors gem. Add rack-cors to your Gemfile , then use the middleware in your config.ru file.
require 'rack/cors'
use Rack :: Cors do
allow do
origins '*'
resource '*' , headers : :any , methods : :get
end
end
run Twitter :: API Content-type is set by the formatter. You can override the content-type of the response at runtime by setting the Content-Type header.
class API < Grape :: API
get '/home_timeline_js' do
content_type 'application/javascript'
"var statuses = ...;"
end
end Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters section above. It also supports custom data formats. You must declare additional content-types via content_type and optionally supply a parser via parser unless a parser is already available within Grape to enable a custom format. Such a parser can be a function or a class.
With a parser, parsed data is available "as-is" in env['api.request.body'] . Without a parser, data is available "as-is" and in env['api.request.input'] .
The following example is a trivial parser that will assign any input with the "text/custom" content-type to :value . The parameter will be available via params[:value] inside the API call.
module CustomParser
def self . call ( object , env )
{ value : object . to_s }
end
end content_type :txt , 'text/plain'
content_type :custom , 'text/custom'
parser :custom , CustomParser
put 'value' do
params [ :value ]
endYou can invoke the above API as follows.
curl -X PUT -d 'data' 'http://localhost:9292/value' -H Content-Type:text/custom -v
You can disable parsing for a content-type with nil . For example, parser :json, nil will disable JSON parsing altogether. The request data is then available as-is in env['api.request.body'] .
Grape uses JSON and ActiveSupport::XmlMini for JSON and XML parsing by default. It also detects and supports multi_json and multi_xml. Adding those gems to your Gemfile and requiring them will enable them and allow you to swap the JSON and XML back-ends.
Grape supports a range of ways to present your data with some help from a generic present method, which accepts two arguments: the object to be presented and the options associated with it. The options hash may include :with , which defines the entity to expose.
Add the grape-entity gem to your Gemfile. Please refer to the grape-entity documentation for more details.
The following example exposes statuses.
module API
module Entities
class Status < Grape :: Entity
expose :user_name
expose :text , documentation : { type : 'string' , desc : 'Status update text.' }
expose :ip , if : { type : :full }
expose :user_type , :user_id , if : -> ( status , options ) { status . user . public? }
expose :digest do | status , options |
Digest :: MD5 . hexdigest ( status . txt )
end
expose :replies , using : API :: Status , as : :replies
end
end
class Statuses < Grape :: API
version 'v1'
desc 'Statuses index' do
params : API :: Entities :: Status . documentation
end
get '/statuses' do
statuses = Status . all
type = current_user . admin? ? :full : :default
present statuses , with : API :: Entities :: Status , type : type
end
end
end You can use entity documentation directly in the params block with using: Entity.documentation .
module API
class Statuses < Grape :: API
version 'v1'
desc 'Create a status'
params do
requires :all , except : [ :ip ] , using : API :: Entities :: Status . documentation . except ( :id )
end
post '/status' do
Status . create! params
end
end
endYou can present with multiple entities using an optional Symbol argument.
get '/statuses' do
statuses = Status . all . page ( 1 ) . per ( 20 )
present :total_page , 10
present :per_page , 20
present :statuses , statuses , with : API :: Entities :: Status
endThe response will be
{
total_page: 10,
per_page: 20,
statuses: []
}
In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.
class Status
def entity
Entity . new ( self )
end
class Entity < Grape :: Entity
expose :text , :user_id
end
end If you organize your entities this way, Grape will automatically detect the Entity class and use it to present your models. In this example, if you added present Status.new to your endpoint, Grape will automatically detect that there is a Status::Entity class and use that as the representative entity. This can still be overridden by using the :with option or an explicit represents call.
You can present hash with Grape::Presenters::Presenter to keep things consistent.
get '/users' do
present { id : 10 , name : :dgz } , with : Grape :: Presenters :: Presenter
endThe response will be
{
id : 10 ,
name : 'dgz'
}It has the same result with
get '/users' do
present :id , 10
present :name , :dgz
end You can use Roar to render HAL or Collection+JSON with the help of grape-roar, which defines a custom JSON formatter and enables presenting entities with Grape's present keyword.
You can use Rabl templates with the help of the grape-rabl gem, which defines a custom Grape Rabl formatter.
You can use Active Model Serializers serializers with the help of the grape-active_model_serializers gem, which defines a custom Grape AMS formatter.
In general, use the binary format to send raw data.
class API < Grape :: API
get '/file' do
content_type 'application/octet-stream'
File . binread 'file.bin'
end
end You can set the response body explicitly with body .
class API < Grape :: API
get '/' do
content_type 'text/plain'
body 'Hello World'
# return value ignored
end
end Use body false to return 204 No Content without any data or content-type.
If you want to empty the body with an HTTP status code other than 204 No Content , you can override the status code after specifying body false as follows
class API < Grape :: API
get '/' do
body false
status 304
end
end You can also set the response to a file with sendfile . This works with the Rack::Sendfile middleware to optimally send the file through your web server software.
class API < Grape :: API
get '/' do
sendfile '/path/to/file'
end
end To stream a file in chunks use stream
class API < Grape :: API
get '/' do
stream '/path/to/file'
end
end If you want to stream non-file data use the stream method and a Stream object. This is an object that responds to each and yields for each chunk to send to the client. Each chunk will be sent as it is yielded instead of waiting for all of the content to be available.
class MyStream
def each
yield 'part 1'
yield 'part 2'
yield 'part 3'
end
end
class API < Grape :: API
get '/' do
stream MyStream . new
end
end Grape has built-in Basic authentication (the given block is executed in the context of the current Endpoint ). Authentication applies to the current namespace and any children, but not parents.
http_basic do | username , password |
# verify user's password here
# IMPORTANT: make sure you use a comparison method which isn't prone to a timing attack
end Grape can use custom Middleware for authentication. How to implement these Middleware have a look at Rack::Auth::Basic or similar implementations.
For registering a Middleware you need the following options:
label - the name for your authenticator to use it laterMiddlewareClass - the MiddlewareClass to use for authenticationoption_lookup_proc - A Proc with one Argument to lookup the options at runtime (return value is an Array as Parameter for the Middleware).مثال:
Grape :: Middleware :: Auth :: Strategies . add ( :my_auth , AuthMiddleware , -> ( options ) { [ options [ :realm ] ] } )
auth :my_auth , { realm : 'Test Api' } do | credentials |
# lookup the user's password here
{ 'user1' => 'password1' } [ username ]
endUse Doorkeeper, warden-oauth2 or rack-oauth2 for OAuth2 support.
You can access the controller params, headers, and helpers through the context with the #context method inside any auth middleware inherited from Grape::Middleware::Auth::Base .
Grape routes can be reflected at runtime. This can notably be useful for generating documentation.
Grape exposes arrays of API versions and compiled routes. Each route contains a prefix , version , namespace , method and params . You can add custom route settings to the route metadata with route_setting .
class TwitterAPI < Grape :: API
version 'v1'
desc 'Includes custom settings.'
route_setting :custom , key : 'value'
get do
end
endExamine the routes at runtime.
TwitterAPI :: versions # yields [ 'v1', 'v2' ]
TwitterAPI :: routes # yields an array of Grape::Route objects
TwitterAPI :: routes [ 0 ] . version # => 'v1'
TwitterAPI :: routes [ 0 ] . description # => 'Includes custom settings.'
TwitterAPI :: routes [ 0 ] . settings [ :custom ] # => { key: 'value' } Note that Route#route_xyz methods have been deprecated since 0.15.0 and removed since 2.0.1.
Please use Route#xyz instead.
Note that difference of Route#options and Route#settings .
The options can be referred from your route, it should be set by specifing key and value on verb methods such as get , post and put . The settings can also be referred from your route, but it should be set by specifing key and value on route_setting .
It's possible to retrieve the information about the current route from within an API call with route .
class MyAPI < Grape :: API
desc 'Returns a description of a parameter.'
params do
requires :id , type : Integer , desc : 'Identity.'
end
get 'params/:id' do
route . params [ params [ :id ] ] # yields the parameter description
end
end The current endpoint responding to the request is self within the API block or env['api.endpoint'] elsewhere. The endpoint has some interesting properties, such as source which gives you access to the original code block of the API implementation. This can be particularly useful for building a logger middleware.
class ApiLogger < Grape :: Middleware :: Base
def before
file = env [ 'api.endpoint' ] . source . source_location [ 0 ]
line = env [ 'api.endpoint' ] . source . source_location [ 1 ]
logger . debug "[api] #{ file } : #{ line } "
end
end Blocks can be executed before or after every API call, using before , after , before_validation and after_validation . If the API fails the after call will not be triggered, if you need code to execute for sure use the finally .
Before and after callbacks execute in the following order:
beforebefore_validationafter_validation (upon successful validation)after (upon successful validation and API call)finally (always)Steps 4, 5 and 6 only happen if validation succeeds.
If a request for a resource is made with an unsupported HTTP method (returning HTTP 405) only before callbacks will be executed. The remaining callbacks will be bypassed.
If a request for a resource is made that triggers the built-in OPTIONS handler, only before and after callbacks will be executed. The remaining callbacks will be bypassed.
For example, using a simple before block to set a header.
before do
header 'X-Robots-Tag' , 'noindex'
end You can ensure a block of code runs after every request (including failures) with finally :
finally do
# this code will run after every request (successful or failed)
endNamespaces
Callbacks apply to each API call within and below the current namespace:
class MyAPI < Grape :: API
get '/' do
"root - #{ @blah } "
end
namespace :foo do
before do
@blah = 'blah'
end
get '/' do
"root - foo - #{ @blah } "
end
namespace :bar do
get '/' do
"root - foo - bar - #{ @blah } "
end
end
end
endThe behavior is then:
GET / # 'root - '
GET /foo # 'root - foo - blah'
GET /foo/bar # 'root - foo - bar - blah' Params on a namespace (or whichever alias you are using) will also be available when using before_validation or after_validation :
class MyAPI < Grape :: API
params do
requires :blah , type : Integer
end
resource ':blah' do
after_validation do
# if we reach this point validations will have passed
@blah = declared ( params , include_missing : false ) [ :blah ]
end
get '/' do
@blah . class
end
end
endThe behavior is then:
GET /123 # 'Integer'
GET /foo # 400 error - 'blah is invalid'الإصدار
When a callback is defined within a version block, it's only called for the routes defined in that block.
class Test < Grape :: API
resource :foo do
version 'v1' , :using => :path do
before do
@output ||= 'v1-'
end
get '/' do
@output += 'hello'
end
end
version 'v2' , :using => :path do
before do
@output ||= 'v2-'
end
get '/' do
@output += 'hello'
end
end
end
endThe behavior is then:
GET /foo/v1 # 'v1-hello'
GET /foo/v2 # 'v2-hello'Altering Responses
Using present in any callback allows you to add data to a response:
class MyAPI < Grape :: API
format :json
after_validation do
present :name , params [ :name ] if params [ :name ]
end
get '/greeting' do
present :greeting , 'Hello!'
end
endThe behavior is then:
GET /greeting # {"greeting":"Hello!"}
GET /greeting ? name=Alan # {"name":"Alan","greeting":"Hello!"} Instead of altering a response, you can also terminate and rewrite it from any callback using error! , including after . This will cause all subsequent steps in the process to not be called. This includes the actual api call and any callbacks
Grape by default anchors all request paths, which means that the request URL should match from start to end to match, otherwise a 404 Not Found is returned. However, this is sometimes not what you want, because it is not always known upfront what can be expected from the call. This is because Rack-mount by default anchors requests to match from the start to the end, or not at all. Rails solves this problem by using a anchor: false option in your routes. In Grape this option can be used as well when a method is defined.
For instance when your API needs to get part of an URL, for instance:
class TwitterAPI < Grape :: API
namespace :statuses do
get '/(*:status)' , anchor : false do
end
end
end This will match all paths starting with '/statuses/'. There is one caveat though: the params[:status] parameter only holds the first part of the request url. Luckily this can be circumvented by using the described above syntax for path specification and using the PATH_INFO Rack environment variable, using env['PATH_INFO'] . This will hold everything that comes after the '/statuses/' part.
You can use instance variables to pass information across the various stages of a request. An instance variable set within a before validator is accessible within the endpoint's code and can also be utilized within the rescue_from handler.
class TwitterAPI < Grape :: API
before do
@var = 1
end
get '/' do
puts @var # => 1
raise
end
rescue_from :all do
puts @var # => 1
end
endThe values of instance variables cannot be shared among various endpoints within the same API. This limitation arises due to Grape generating a new instance for each request made. Consequently, instance variables set within an endpoint during one request differ from those set during a subsequent request, as they exist within separate instances.
class TwitterAPI < Grape :: API
get '/first' do
@var = 1
puts @var # => 1
end
get '/second' do
puts @var # => nil
end
end You can make a custom middleware by using Grape::Middleware::Base . It's inherited from some grape official middlewares in fact.
For example, you can write a middleware to log application exception.
class LoggingError < Grape :: Middleware :: Base
def after
return unless @app_response && @app_response [ 0 ] == 500
env [ 'rack.logger' ] . error ( "Raised error on #{ env [ 'PATH_INFO' ] } " )
end
endYour middleware can overwrite application response as follows, except error case.
class Overwriter < Grape :: Middleware :: Base
def after
[ 200 , { 'Content-Type' => 'text/plain' } , [ 'Overwritten.' ] ]
end
end You can add your custom middleware with use , that push the middleware onto the stack, and you can also control where the middleware is inserted using insert , insert_before and insert_after .
class CustomOverwriter < Grape :: Middleware :: Base
def after
[ 200 , { 'Content-Type' => 'text/plain' } , [ @options [ :message ] ] ]
end
end
class API < Grape :: API
use Overwriter
insert_before Overwriter , CustomOverwriter , message : 'Overwritten again.'
insert 0 , CustomOverwriter , message : 'Overwrites all other middleware.'
get '/' do
end
end You can access the controller params, headers, and helpers through the context with the #context method inside any middleware inherited from Grape::Middleware::Base .
Note that when you're using Grape mounted on Rails you don't have to use Rails middleware because it's already included into your middleware stack. You only have to implement the helpers to access the specific env variable.
If you are using a custom application that is inherited from Rails::Application and need to insert a new middleware among the ones initiated via Rails, you will need to register it manually in your custom application class.
class Company :: Application < Rails :: Application
config . middleware . insert_before ( Rack :: Attack , Middleware :: ApiLogger )
end By default you can access remote IP with request.ip . This is the remote IP address implemented by Rack. Sometimes it is desirable to get the remote IP Rails-style with ActionDispatch::RemoteIp .
Add gem 'actionpack' to your Gemfile and require 'action_dispatch/middleware/remote_ip.rb' . Use the middleware in your API and expose a client_ip helper. See this documentation for additional options.
class API < Grape :: API
use ActionDispatch :: RemoteIp
helpers do
def client_ip
env [ 'action_dispatch.remote_ip' ] . to_s
end
end
get :remote_ip do
{ ip : client_ip }
end
end Use rack-test and define your API as app .
You can test a Grape API with RSpec by making HTTP requests and examining the response.
describe Twitter :: API do
include Rack :: Test :: Methods
def app
Twitter :: API
end
context 'GET /api/statuses/public_timeline' do
it 'returns an empty array of statuses' do
get '/api/statuses/public_timeline'
expect ( last_response . status ) . to eq ( 200 )
expect ( JSON . parse ( last_response . body ) ) . to eq [ ]
end
end
context 'GET /api/statuses/:id' do
it 'returns a status by id' do
status = Status . create!
get "/api/statuses/ #{ status . id } "
expect ( last_response . body ) . to eq status . to_json
end
end
endThere's no standard way of sending arrays of objects via an HTTP GET, so POST JSON data and specify the correct content-type.
describe Twitter :: API do
context 'POST /api/statuses' do
it 'creates many statuses' do
statuses = [ { text : '...' } , { text : '...' } ]
post '/api/statuses' , statuses . to_json , 'CONTENT_TYPE' => 'application/json'
expect ( last_response . body ) . to eq 201
end
end
end You can test with other RSpec-based frameworks, including Airborne, which uses rack-test to make requests.
require 'airborne'
Airborne . configure do | config |
config . rack_app = Twitter :: API
end
describe Twitter :: API do
context 'GET /api/statuses/:id' do
it 'returns a status by id' do
status = Status . create!
get "/api/statuses/ #{ status . id } "
expect_json ( status . as_json )
end
end
end require 'test_helper'
class Twitter :: APITest < MiniTest :: Test
include Rack :: Test :: Methods
def app
Twitter :: API
end
def test_get_api_statuses_public_timeline_returns_an_empty_array_of_statuses
get '/api/statuses/public_timeline'
assert last_response . ok?
assert_equal [ ] , JSON . parse ( last_response . body )
end
def test_get_api_statuses_id_returns_a_status_by_id
status = Status . create!
get "/api/statuses/ #{ status . id } "
assert_equal status . to_json , last_response . body
end
end describe Twitter :: API do
context 'GET /api/statuses/public_timeline' do
it 'returns an empty array of statuses' do
get '/api/statuses/public_timeline'
expect ( response . status ) . to eq ( 200 )
expect ( JSON . parse ( response . body ) ) . to eq [ ]
end
end
context 'GET /api/statuses/:id' do
it 'returns a status by id' do
status = Status . create!
get "/api/statuses/ #{ status . id } "
expect ( response . body ) . to eq status . to_json
end
end
end In Rails, HTTP request tests would go into the spec/requests group. You may want your API code to go into app/api - you can match that layout under spec by adding the following in spec/rails_helper.rb .
RSpec . configure do | config |
config . include RSpec :: Rails :: RequestExampleGroup , type : :request , file_path : /spec / api/
end class Twitter :: APITest < ActiveSupport :: TestCase
include Rack :: Test :: Methods
def app
Rails . application
end
test 'GET /api/statuses/public_timeline returns an empty array of statuses' do
get '/api/statuses/public_timeline'
assert last_response . ok?
assert_equal [ ] , JSON . parse ( last_response . body )
end
test 'GET /api/statuses/:id returns a status by id' do
status = Status . create!
get "/api/statuses/ #{ status . id } "
assert_equal status . to_json , last_response . body
end
end Because helpers are mixed in based on the context when an endpoint is defined, it can be difficult to stub or mock them for testing. The Grape::Endpoint.before_each method can help by allowing you to define behavior on the endpoint that will run before every request.
describe 'an endpoint that needs helpers stubbed' do
before do
Grape :: Endpoint . before_each do | endpoint |
allow ( endpoint ) . to receive ( :helper_name ) . and_return ( 'desired_value' )
end
end
after do
Grape :: Endpoint . before_each nil
end
it 'stubs the helper' do
end
end Use grape-reload.
Add API paths to config/application.rb .
# Auto-load API and its subdirectories
config . paths . add File . join ( 'app' , 'api' ) , glob : File . join ( '**' , '*.rb' )
config . autoload_paths += Dir [ Rails . root . join ( 'app' , 'api' , '*' ) ] Create config/initializers/reload_api.rb .
if Rails . env . development?
ActiveSupport :: Dependencies . explicitly_unloadable_constants << 'Twitter::API'
api_files = Dir [ Rails . root . join ( 'app' , 'api' , '**' , '*.rb' ) ]
api_reloader = ActiveSupport :: FileUpdateChecker . new ( api_files ) do
Rails . application . reload_routes!
end
ActionDispatch :: Callbacks . to_prepare do
api_reloader . execute_if_updated
end
endFor Rails >= 5.1.4, change this:
ActionDispatch :: Callbacks . to_prepare do
api_reloader . execute_if_updated
endto this:
ActiveSupport :: Reloader . to_prepare do
api_reloader . execute_if_updated
endSee StackOverflow #3282655 for more information.
Grape has built-in support for ActiveSupport::Notifications which provides simple hook points to instrument key parts of your application.
The following are currently supported:
The main execution of an endpoint, includes filters and rendering.
The execution of the main content block of the endpoint.
The execution of validators.
Serialization or template rendering.
Grape::Formatter::Json )See the ActiveSupport::Notifications documentation for information on how to subscribe to these events.
Grape integrates with following third-party tools:
Grape is work of hundreds of contributors. You're encouraged to submit pull requests, propose features and discuss issues.
See CONTRIBUTING.
See SECURITY for details.
MIT License. See LICENSE for details.
Copyright (c) 2010-2020 Michael Bleigh, Intridea Inc. and Contributors.