Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return files in API JSON result?

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.

like image 511
Miguel Moura Avatar asked May 24 '16 15:05

Miguel Moura


1 Answers

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:

  1. Base64 encoding increases up to the 33% percent the size of your files
  2. You API response will become huge. Imagine you have to return even just 10 ebooks records (a small amout): this will mean that you have to encode a great amount of data (pdf, images, etc.) into Base64. A simple response from you API could lead the browser to download hundreds of MBs of data.
like image 63
Federico Dipuma Avatar answered Sep 23 '22 06:09

Federico Dipuma