https://github.com/ruby-grape/grape-entity
An API focused facade that sits on top of an object model.
https://github.com/ruby-grape/grape-entity
Keywords
api entity grape ruby
Keywords from Contributors
activerecord mvc activejob crash-reporting rubygems rubocop code-formatter static-code-analysis rack rspec
Last synced: about 4 hours ago
JSON representation
Repository metadata
An API focused facade that sits on top of an object model.
- Host: GitHub
- URL: https://github.com/ruby-grape/grape-entity
- Owner: ruby-grape
- License: mit
- Created: 2013-01-12T21:04:19.000Z (almost 13 years ago)
- Default Branch: master
- Last Pushed: 2025-11-24T13:38:58.000Z (about 2 months ago)
- Last Synced: 2025-12-14T20:59:44.310Z (26 days ago)
- Topics: api, entity, grape, ruby
- Language: Ruby
- Homepage:
- Size: 688 KB
- Stars: 731
- Watchers: 13
- Forks: 151
- Open Issues: 90
- Releases: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
README.md
Table of Contents
- Grape::Entity
Grape::Entity
Introduction
This gem adds Entity support to API frameworks, such as Grape. Grape's Entity is an API focused facade that sits on top of an object model.
Example
module API
module Entities
class Status < Grape::Entity
format_with(:iso_timestamp) { |dt| dt.iso8601 }
expose :user_name
expose :text, documentation: { type: "String", desc: "Status update text." }
expose :ip, if: { type: :full }
expose :user_type, :user_id, if: lambda { |status, options| status.user.public? }
expose :location, merge: true
expose :contact_info do
expose :phone
expose :address, merge: true, using: API::Entities::Address
end
expose :digest do |status, options|
Digest::MD5.hexdigest status.txt
end
expose :replies, using: API::Entities::Status, as: :responses
expose :last_reply, using: API::Entities::Status do |status, options|
status.replies.last
end
with_options(format_with: :iso_timestamp) do
expose :created_at
expose :updated_at
end
end
end
end
module API
module Entities
class StatusDetailed < API::Entities::Status
expose :internal_id
end
end
end
Reusable Responses with Entities
Entities are a reusable means for converting Ruby objects to API responses. Entities can be used to conditionally include fields, nest other entities, and build ever larger responses, using inheritance.
Defining Entities
Entities inherit from Grape::Entity, and define a simple DSL. Exposures can use runtime options to determine which fields should be visible, these options are available to :if, :unless, and :proc.
Basic Exposure
Define a list of fields that will always be exposed.
expose :user_name, :ip
The field lookup takes several steps
- first try
entity-instance.exposure - next try
object.exposure - next try
object.fetch(exposure) - last raise an Exception
exposure is a Symbol by default. If object is a Hash with stringified keys, you can set the hash accessor at the entity-class level to properly expose its members:
class Status < GrapeEntity
self.hash_access = :to_s
expose :code
expose :message
end
Status.represent({ 'code' => 418, 'message' => "I'm a teapot" }).as_json
#=> { code: 418, message: "I'm a teapot" }
Exposing with a Presenter
Don't derive your model classes from Grape::Entity, expose them using a presenter.
expose :replies, using: API::Entities::Status, as: :responses
Presenter classes can also be specified in string format, which helps with circular dependencies.
expose :replies, using: "API::Entities::Status", as: :responses
Conditional Exposure
Use :if or :unless to expose fields conditionally.
expose :ip, if: { type: :full }
expose :ip, if: lambda { |instance, options| options[:type] == :full } # exposed if the function evaluates to true
expose :ip, if: :type # exposed if :type is available in the options hash
expose :ip, if: { type: :full } # exposed if options :type has a value of :full
expose :ip, unless: ... # the opposite of :if
Safe Exposure
Don't raise an exception and expose as nil, even if the :x cannot be evaluated.
expose :ip, safe: true
Nested Exposure
Supply a block to define a hash using nested exposures.
expose :contact_info do
expose :phone
expose :address, using: API::Entities::Address
end
You can also conditionally expose attributes in nested exposures:
expose :contact_info do
expose :phone
expose :address, using: API::Entities::Address
expose :email, if: lambda { |instance, options| options[:type] == :full }
end
Collection Exposure
Use root(plural, singular = nil) to expose an object or a collection of objects with a root key.
root 'users', 'user'
expose :id, :name, ...
By default every object of a collection is wrapped into an instance of your Entity class.
You can override this behavior and wrap the whole collection into one instance of your Entity
class.
As example:
present_collection true, :collection_name # `collection_name` is optional and defaults to `items`
expose :collection_name, using: API::Entities::Items
Merge Fields
Use :merge option to merge fields into the hash or into the root:
expose :contact_info do
expose :phone
expose :address, merge: true, using: API::Entities::Address
end
expose :status, merge: true
This will return something like:
{ contact_info: { phone: "88002000700", city: 'City 17', address_line: 'Block C' }, text: 'HL3', likes: 19 }
It also works with collections:
expose :profiles do
expose :users, merge: true, using: API::Entities::User
expose :admins, merge: true, using: API::Entities::Admin
end
Provide lambda to solve collisions:
expose :status, merge: ->(key, old_val, new_val) { old_val + new_val if old_val && new_val }
Runtime Exposure
Use a block or a Proc to evaluate exposure at runtime. The supplied block or
Proc will be called with two parameters: the represented object and runtime options.
NOTE: A block supplied with no parameters will be evaluated as a nested exposure (see above).
expose :digest do |status, options|
Digest::MD5.hexdigest status.txt
end
expose :digest, proc: ... # equivalent to a block
You can also define a method on the entity and it will try that before trying
on the object the entity wraps.
class ExampleEntity < Grape::Entity
expose :attr_not_on_wrapped_object
# ...
private
def attr_not_on_wrapped_object
42
end
end
You always have access to the presented instance (object) and the top-level
entity options (options).
class ExampleEntity < Grape::Entity
expose :formatted_value
# ...
private
def formatted_value
"+ X #{object.value} #{options[:y]}"
end
end
Unexpose
To undefine an exposed field, use the .unexpose method. Useful for modifying inherited entities.
class UserData < Grape::Entity
expose :name
expose :address1
expose :address2
expose :address_state
expose :address_city
expose :email
expose :phone
end
class MailingAddress < UserData
unexpose :email
unexpose :phone
end
Overriding exposures
If you want to add one more exposure for the field but don't want the first one to be fired (for instance, when using inheritance), you can use the override flag. For instance:
class User < Grape::Entity
expose :name
end
class Employee < User
expose :name, as: :employee_name, override: true
end
User will return something like this { "name" : "John" } while Employee will present the same data as { "employee_name" : "John" } instead of { "name" : "John", "employee_name" : "John" }.
Returning only the fields you want
After exposing the desired attributes, you can choose which one you need when representing some object or collection by using the only: and except: options. See the example:
class UserEntity
expose :id
expose :name
expose :email
end
class Entity
expose :id
expose :title
expose :user, using: UserEntity
end
data = Entity.represent(model, only: [:title, { user: [:name, :email] }])
data.as_json
This will return something like this:
{
title: 'grape-entity is awesome!',
user: {
name: 'John Applet',
email: 'john@example.com'
}
}
Instead of returning all the exposed attributes.
The same result can be achieved with the following exposure:
data = Entity.represent(model, except: [:id, { user: [:id] }])
data.as_json
Aliases
Expose under a different name with :as.
expose :replies, using: API::Entities::Status, as: :responses
Format Before Exposing
Apply a formatter before exposing a value.
module Entities
class MyModel < Grape::Entity
format_with(:iso_timestamp) do |date|
date.iso8601
end
with_options(format_with: :iso_timestamp) do
expose :created_at
expose :updated_at
end
end
end
Defining a reusable formatter between multiples entities:
module ApiHelpers
extend Grape::API::Helpers
Grape::Entity.format_with :utc do |date|
date.utc if date
end
end
module Entities
class MyModel < Grape::Entity
expose :updated_at, format_with: :utc
end
class AnotherModel < Grape::Entity
expose :created_at, format_with: :utc
end
end
Expose Nil
By default, exposures that contain nil values will be represented in the resulting JSON as null.
As an example, a hash with the following values:
{
name: nil,
age: 100
}
will result in a JSON object that looks like:
{
"name": null,
"age": 100
}
There are also times when, rather than displaying an attribute with a null value, it is more desirable to not display the attribute at all. Using the hash from above the desired JSON would look like:
{
"age": 100
}
In order to turn on this behavior for an as-exposure basis, the option expose_nil can be used. By default, expose_nil is considered to be true, meaning that nil values will be represented in JSON as null. If false is provided, then attributes with nil values will be omitted from the resulting JSON completely.
module Entities
class MyModel < Grape::Entity
expose :name, expose_nil: false
expose :age, expose_nil: false
end
end
expose_nil is per exposure, so you can suppress exposures from resulting in null or express null values on a per exposure basis as you need:
module Entities
class MyModel < Grape::Entity
expose :name, expose_nil: false
expose :age # since expose_nil is omitted nil values will be rendered as null
end
end
It is also possible to use expose_nil with with_options if you want to add the configuration to multiple exposures at once.
module Entities
class MyModel < Grape::Entity
# None of the exposures in the with_options block will render nil values as null
with_options(expose_nil: false) do
expose :name
expose :age
end
end
end
When using with_options, it is possible to again override which exposures will render nil as null by adding the option on a specific exposure.
module Entities
class MyModel < Grape::Entity
# None of the exposures in the with_options block will render nil values as null
with_options(expose_nil: false) do
expose :name
expose :age, expose_nil: true # nil values would be rendered as null in the JSON
end
end
end
Default Value
This option can be used to provide a default value in case the return value is nil or empty.
module Entities
class MyModel < Grape::Entity
expose :name, default: ''
expose :age, default: 60
end
end
Documentation
Expose documentation with the field. Gets bubbled up when used with Grape and various API documentation systems.
expose :text, documentation: { type: "String", desc: "Status update text." }
Options Hash
The option keys :version and :collection are always defined. The :version key is defined as api.version. The :collection key is boolean, and defined as true if the object presented is an array. The options also contain the runtime environment in :env, which includes request parameters in options[:env]['grape.request.params'].
Any additional options defined on the entity exposure are included as is. In the following example user is set to the value of current_user.
class Status < Grape::Entity
expose :user, if: lambda { |instance, options| options[:user] } do |instance, options|
# examine available environment keys with `p options[:env].keys`
options[:user]
end
end
present s, with: Status, user: current_user
Passing Additional Option To Nested Exposure
Sometimes you want to pass additional options or parameters to nested a exposure. For example, let's say that you need to expose an address for a contact info and it has two different formats: full and simple. You can pass an additional full_format option to specify which format to render.
# api/contact.rb
expose :contact_info do
expose :phone
expose :address do |instance, options|
# use `#merge` to extend options and then pass the new version of options to the nested entity
API::Entities::Address.represent instance.address, options.merge(full_format: instance.need_full_format?)
end
expose :email, if: lambda { |instance, options| options[:type] == :full }
end
# api/address.rb
expose :state, if: lambda {|instance, options| !!options[:full_format]} # the new option could be retrieved in options hash for conditional exposure
expose :city, if: lambda {|instance, options| !!options[:full_format]}
expose :street do |instance, options|
# the new option could be retrieved in options hash for runtime exposure
!!options[:full_format] ? instance.full_street_name : instance.simple_street_name
end
Notice: In the above code, you should pay attention to Safe Exposure yourself. For example, instance.address might be nil and it is better to expose it as nil directly.
Attribute Path Tracking
Sometimes, especially when there are nested attributes, you might want to know which attribute
is being exposed. For example, some APIs allow users to provide a parameter to control which fields
will be included in (or excluded from) the response.
GrapeEntity can track the path of each attribute, which you can access during conditions checking
or runtime exposure via options[:attr_path].
The attribute path is an array. The last item of this array is the name (alias) of current attribute.
If the attribute is nested, the former items are names (aliases) of its ancestor attributes.
Example:
class Status < Grape::Entity
expose :user # path is [:user]
expose :foo, as: :bar # path is [:bar]
expose :a do
expose :b, as: :xx do
expose :c # path is [:a, :xx, :c]
end
end
end
Using the Exposure DSL
Grape ships with a DSL to easily define entities within the context of an existing class:
class Status
include Grape::Entity::DSL
entity :text, :user_id do
expose :detailed, if: :conditional
end
end
The above will automatically create a Status::Entity class and define properties on it according to the same rules as above. If you only want to define simple exposures you don't have to supply a block and can instead simply supply a list of comma-separated symbols.
Using Entities
With Grape, once an entity is defined, it can be used within endpoints, by calling present. The present method accepts two arguments, the object to be presented and the options associated with it. The options hash must always include :with, which defines the entity to expose (unless namespaced entity classes are used, see next section).
If the entity includes documentation it can be included in an endpoint's description.
module API
class Statuses < Grape::API
version 'v1'
desc 'Statuses.', {
params: API::Entities::Status.documentation
}
get '/statuses' do
statuses = Status.all
type = current_user.admin? ? :full : :default
present statuses, with: API::Entities::Status, type: type
end
end
end
Entity Organization
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 would 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.
Caveats
Entities with duplicate exposure names and conditions will silently overwrite one another. In the following example, when object.check equals "foo", only field_a will be exposed. However, when object.check equals "bar" both field_b and foo will be exposed.
module API
module Entities
class Status < Grape::Entity
expose :field_a, :foo, if: lambda { |object, options| object.check == "foo" }
expose :field_b, :foo, if: lambda { |object, options| object.check == "bar" }
end
end
end
This can be problematic, when you have mixed collections. Using respond_to? is safer.
module API
module Entities
class Status < Grape::Entity
expose :field_a, if: lambda { |object, options| object.check == "foo" }
expose :field_b, if: lambda { |object, options| object.check == "bar" }
expose :foo, if: lambda { |object, options| object.respond_to?(:foo) }
end
end
end
Also note that an ArgumentError is raised when unknown options are passed to either expose or with_options.
Preloading Associations
Use Grape::Entity::Preloader to preload associations and callbacks and avoid N+1 operations.
Installation
Add this line to your application's Gemfile:
gem 'grape-entity'
And then execute:
$ bundle
Or install it yourself as:
$ gem install grape-entity
Testing with Entities
Test API request/response as usual.
Also see Grape Entity Matchers.
Project Resources
- Need help? Grape Google Group
Contributing
See CONTRIBUTING.md.
License
MIT License. See LICENSE for details.
Copyright
Copyright (c) 2010-2016 Michael Bleigh, Intridea, Inc., ruby-grape and Contributors.
Owner metadata
- Name: Ruby Grape
- Login: ruby-grape
- Email: ruby-grape@googlegroups.com
- Kind: organization
- Description: An opinionated micro-framework for creating REST-like APIs in Ruby.
- Website: http://www.ruby-grape.org
- Location:
- Twitter:
- Company:
- Icon url: https://avatars.githubusercontent.com/u/13624553?v=4
- Repositories: 17
- Last ynced at: 2024-03-25T21:19:03.302Z
- Profile URL: https://github.com/ruby-grape
GitHub Events
Total
- Create event: 1
- Issues event: 3
- Watch event: 16
- Delete event: 1
- Member event: 1
- Issue comment event: 13
- Push event: 2
- Pull request event: 4
- Pull request review comment event: 3
- Pull request review event: 5
- Fork event: 3
Last Year
- Create event: 1
- Issues event: 2
- Watch event: 14
- Delete event: 1
- Member event: 1
- Issue comment event: 13
- Push event: 2
- Pull request event: 4
- Pull request review comment event: 3
- Pull request review event: 5
- Fork event: 2
Committers metadata
Last synced: 1 day ago
Total Commits: 265
Total Committers: 93
Avg Commits per committer: 2.849
Development Distribution Score (DDS): 0.804
Commits in past year: 6
Committers in past year: 4
Avg Commits per committer in past year: 1.5
Development Distribution Score (DDS) in past year: 0.667
| Name | Commits | |
|---|---|---|
| dblock | d****k@d****g | 52 |
| peter scholz | p****e@g****m | 34 |
| Vladimir Kochnev | h****e@y****u | 11 |
| Konstantin Shabanov | e****a@g****m | 10 |
| justfalter | f****r@g****m | 8 |
| Michael Bleigh | m****h@m****m | 8 |
| Mark Madsen | m****k@a****m | 8 |
| Malte Rohde | m****e@p****m | 6 |
| Joel Van Horn | j****l@j****m | 5 |
| Olle Jonsson | o****n@g****m | 4 |
| Jared Wyatt | j@w****o | 4 |
| Dmitry Tsepelev | d****v@g****m | 4 |
| Alexander Yunin | u****s@g****m | 3 |
| Joakim Antman | a****j@g****m | 3 |
| Kenichi Kamiya | k****1@g****m | 3 |
| Sergey Malyshev | j****v@g****m | 3 |
| dependabot[bot] | 4****] | 3 |
| fahchen | d****h@g****m | 3 |
| AMar4enko | a****o@g****m | 3 |
| Yannis Zhang | z****5@g****m | 3 |
| Dmitriy Budnik | d****k@g****m | 2 |
| Dan Corneanu | d****u@g****m | 2 |
| aj0strow | a****w@g****m | 2 |
| Ryunosuke SATO | t****s@g****m | 2 |
| Nerian | s****o@g****m | 2 |
| James McCarthy | j****y@g****m | 2 |
| Estevão Mascarenhas | e****m@g****m | 2 |
| Drakula2k | d****k@g****m | 2 |
| David Castillo | c****g | 2 |
| Cedric Röck | g****t@r****t | 2 |
| and 63 more... | ||
Committer domains:
- yandex.ru: 2
- dblock.org: 1
- mbleigh.com: 1
- agileanimal.com: 1
- plugintheworld.com: 1
- joelvanhorn.com: 1
- wyatt.co: 1
- roecky.net: 1
- kyru.us: 1
- hitfoxgroup.com: 1
- hush.com: 1
- clearstorydata.com: 1
- ruby-journal.com: 1
- faber.de: 1
- codefire.com: 1
- sage.com: 1
- robotct.ru: 1
- michaelxavier.net: 1
- mhenrixon.com: 1
- debian.org: 1
- qq.com: 1
- k2p-ed.com: 1
- thanx.com: 1
- petalmd.com: 1
- wwahammy.com: 1
- norydev.com: 1
- iangreenleaf.com: 1
- jmccc.com: 1
Issue and Pull Request metadata
Last synced: about 2 months ago
Total issues: 57
Total pull requests: 71
Average time to close issues: over 1 year
Average time to close pull requests: 6 months
Total issue authors: 53
Total pull request authors: 34
Average comments per issue: 2.16
Average comments per pull request: 2.68
Merged pull request: 57
Bot issues: 0
Bot pull requests: 4
Past year issues: 1
Past year pull requests: 8
Past year average time to close issues: N/A
Past year average time to close pull requests: 8 days
Past year issue authors: 1
Past year pull request authors: 3
Past year average comments per issue: 0.0
Past year average comments per pull request: 1.13
Past year merged pull request: 6
Past year bot issues: 0
Past year bot pull requests: 2
Top Issue Authors
- glaucocustodio (2)
- hay-wtag (2)
- Kukunin (2)
- dccmmtop (2)
- yilangmok-gusto (1)
- tmornini (1)
- Razer6 (1)
- bobbytables (1)
- sharkey11 (1)
- qiuxiaoj (1)
- MoroZvlg (1)
- vitoravelino (1)
- kris (1)
- olbrich (1)
- danielvdao (1)
Top Pull Request Authors
- LeFnord (20)
- olleolleolle (4)
- dependabot[bot] (4)
- numbata (4)
- OuYangJinTing (3)
- budnik (2)
- linhchauatx (2)
- magni- (2)
- fcce (2)
- ericproulx (2)
- anakinj (2)
- marshall-lee (2)
- Linell (1)
- eitoball (1)
- dnesteryuk (1)
Top Issue Labels
- question (8)
- bug? (5)
- feature (4)
- bug (1)
Top Pull Request Labels
- dependencies (4)
- github_actions (3)
- bug? (1)
Package metadata
- Total packages: 3
-
Total downloads:
- rubygems: 118,131,518 total
- Total docker downloads: 899,006,354
- Total dependent packages: 42 (may contain duplicates)
- Total dependent repositories: 3,996 (may contain duplicates)
- Total versions: 84
- Total maintainers: 5
gem.coop: grape-entity
Extracted from Grape, A Ruby framework for rapid API development with great conventions.
- Homepage: https://github.com/ruby-grape/grape-entity
- Documentation: http://www.rubydoc.info/gems/grape-entity/
- Licenses: MIT
- Latest release: 1.0.1 (published almost 2 years ago)
- Last Synced: 2026-01-08T12:49:33.138Z (1 day ago)
- Versions: 28
- Dependent Packages: 0
- Dependent Repositories: 0
- Downloads: 59,065,759 Total
- Docker Downloads: 449,503,177
-
Rankings:
- Dependent repos count: 0.0%
- Dependent packages count: 0.0%
- Average: 0.177%
- Docker downloads count: 0.249%
- Downloads: 0.457%
- Maintainers (5)
rubygems.org: grape-entity
Extracted from Grape, A Ruby framework for rapid API development with great conventions.
- Homepage: https://github.com/ruby-grape/grape-entity
- Documentation: http://www.rubydoc.info/gems/grape-entity/
- Licenses: MIT
- Latest release: 1.0.1 (published almost 2 years ago)
- Last Synced: 2026-01-08T13:19:00.811Z (1 day ago)
- Versions: 28
- Dependent Packages: 42
- Dependent Repositories: 3,996
- Downloads: 59,065,759 Total
- Docker Downloads: 449,503,177
-
Rankings:
- Docker downloads count: 0.308%
- Downloads: 0.484%
- Dependent repos count: 0.496%
- Dependent packages count: 0.656%
- Average: 1.043%
- Forks count: 2.13%
- Stargazers count: 2.186%
- Maintainers (5)
proxy.golang.org: github.com/ruby-grape/grape-entity
- Homepage:
- Documentation: https://pkg.go.dev/github.com/ruby-grape/grape-entity#section-documentation
- Licenses: mit
- Latest release: v1.0.1 (published almost 2 years ago)
- Last Synced: 2026-01-08T04:19:55.463Z (2 days ago)
- Versions: 28
- Dependent Packages: 0
- Dependent Repositories: 0
-
Rankings:
- Dependent packages count: 5.503%
- Average: 5.688%
- Dependent repos count: 5.872%
Dependencies
- coveralls_reborn >= 0 development
- growl >= 0 development
- guard >= 0 development
- guard-bundler >= 0 development
- guard-rspec >= 0 development
- rb-fsevent >= 0 development
- rubocop ~> 1.0 development
- ruby-grape-danger ~> 0.2 development
- simplecov >= 0 development
- bundler >= 0 development
- maruku >= 0 development
- rack-test >= 0 development
- rake >= 0 development
- rspec ~> 3.9 development
- yard >= 0 development
- activesupport >= 3.0.0
- multi_json >= 1.3.2
- actions/checkout v3 composite
- ruby/setup-ruby v1 composite
Score: 31.983385524207062