Skip to content

Instantly share code, notes, and snippets.

@acotie
Last active August 29, 2015 14:04
Show Gist options
  • Save acotie/0e7e079286ddd30cdb19 to your computer and use it in GitHub Desktop.
Save acotie/0e7e079286ddd30cdb19 to your computer and use it in GitHub Desktop.
REST API sample by Grape & Grape::Entity. return nested items.
module TEST::Entities
class Post < Grape::Entity
expose :id
expose :title
expose :description
expose(:image_url) do |post, options|
if post.image.url.present? # else is return null
"http://#{options[:env]['HTTP_HOST']}"+"#{post.image.url}"
end
end
expose(:like_count) do |post, options|
post.likes.size
end
expose(:comment_count) do |post, options|
post.comments.size
end
expose(:tags) {|post| post.tag_list || [] }
expose :user, :using => TEST::Entities::UserBasic
end
class UserBasic < Grape::Entity
expose :id
expose :username
expose :description
end
class UserDetail < UserBasic
expose :email
end
end
class TEST::Posts < Grape::API
resource "posts" do
desc "returns all posts"
params do
optional :page, type: Integer, desc: "page", default:1
optional :per_page, type: Integer, desc: "per page" ,default:30
end
get do
posts = Post.page(params[:page]).per(params[:per_page])
present :total_count, posts.size
present :total_page_count, posts.total_pages
present :page, posts.current_page
present :posts, posts, with: Proj::Entities::Post
end
end
end
{
"total_count": 50,
"total_page_count": 2,
"page": 1,
"per_page": 30,
"posts": [
{
"id": 10,
"title": null,
"description": null,
"image_url": "http://test.dev/uploads/post/image/10/hoge.png",
"like_count": 0,
"comment_count": 0,
"tags": [
"aaaa",
"bbbb"
],
"user": {
"id": 1,
"username": "user1",
"description": "description1",
}
},
.........
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment