I am working on an REST API which returns, for example, a list of ebooks. Each ebook has many photos and one PDF. I have the name and url of each image file and pdf file.
How should I include this information in a REST API response?
1. Have a property Photos and another Document?
2. Or simply one saying Files and specifying the file type?
3. Or some other way?
At the moment I have the following JSON:
{
"ebooks": [
{
"title": "ebook 1"
},
{
"title": "ebook 2"
}
]
}
I am trying to have a standard way of doing this so it is consistence across my API endpoints.
You should really return just meta-data in an API like the one you described, and inside every ebook
record insert links to the files.
A response from your API should look like the following JSON:
{
"ebooks": [
{
"title": "ebook 1",
"pictures:" [
"http://myhost/pictures/picture1.jpg",
"http://myhost/pictures/picture2.jpg",
],
"document": "http://myhost/ebooks/ebook1.pdf"
},
{
"title": "ebook 2",
"pictures:" [
"http://myhost/pictures/picture3.jpg",
"http://myhost/pictures/picture4.jpg",
],
"document": "http://myhost/ebooks/ebook2.pdf"
}
]
}
This approach is fully RESTful and is exactly what the HATEOAS constraint suggest you to do: let your resources be addressable.
You can't return both JSON and raw binary content using the same response, and I strongly suggest you to avoid converting your files into Base64 strings and returning them into the JSON response for two main reasons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With