I'm using the PhoenixFramework and the library Poison.
Current I'm working on an REST API. Now I need to encode the model Book
in two different ways.
- In a list of all books with only base informations (
GET /books
) - In a detailed view with all informations (
GET /book/1
)
GET /books
{
"books": [
{
"id": 1,
"name": "Book one"
},
{
"id": 2,
"name": "Book two"
},
// ...
]
}
GET /books/1
{
"book": {
"id": 1,
"name": "Book one",
"description": "This is book one.",
"author": "Max Mustermann",
// ...
}
}
Encoder of Book
defimpl Poison.Encoder, for: MyProject.Book do
@attributes [:id, :name, :description, :author]
def encode(project, _options) do
project
|> Map.take(@attributes)
|> Poison.encode!
end
end
Snippet controller
def index(conn, _params) do
books = Repo.all(Book)
json(conn, %{books: books})
end
How to limit the fields? I search for a option like :only
or :exclude
.
Has anyone experience with this problem?
Thanks for help!