Add JSON sideloading support to your Grape API so you can deliver multiple resources under one endpoint.
- What is Grape?
- What is Sideloading JSON?
- Why do I need this gem?
- Installation
- Usage
- Contributing
- License
Grape is a ruby framework for creating APIs grape
Sideloading allows you to deliver related records as part of a single request.
For example, normally a request to /tickets.json
returns ticket resources with a structure similar to:
{
"tickets": [
{
"requester_id": 7,
...
},
...
]
}
To fetch the requester's data, your consumer then needs to make another request to /users/7.json
.
Using sideloading, you can deliver a the user resource along with the ticket in a single request.
The response will include a top-level array of associated data under the appropriate resource key.
{
"tickets": [
{
"requester_id": 7,
...
},
...
],
"users": [
{
"id": 7,
"name": "Bob Bobberson",
...
}
]
}
The Grape framework doesn't offer support for sideloading the resources you deliver with your API's response, this gem will help you doing exactly that in a simple manner.
Add this line to your application's Gemfile:
gem 'grape-sideload'
then execute:
$ bundle
And add to your app.rb
require 'grape-sideload'
example for sideloading with present_many
:
resources :tickets do
get do
present_many({ present: current_user.tickets, with: Ticket::Entity },
{ present: current_user, with: User::Entity})
end
end
example for sideloading with merge_payloads
to sideload using grape's present syntax:
resource :tickets do
get do
merge_payloads(present(current_user.tickets, with: Ticket::Entity),
present(current_user, with: User::Entity))
end
end
Bug reports and pull requests are welcome on GitHub at https://github.com/4xposed/grape-sideload. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.