10

This has been puzzling me for a while.

For example, we have a REST API that provides basic content to a system, consuming and producing JSON. At this endpoint it produces a URL to a picture and a description, and is found like thus: //localhost/myApi/pictures/1

{
    id: 1,
    description: "This is a pretty picture of a daisy",
    URL: <OUR URL>
}

Now the OUR_URL should this point to a location on the API for example //localhost/myApi/files/pictures/1 which returns a JPG (the application behind the API reads the physical content of the file and then streams it back to the client). This is obviously different to the rest of the API which is producing JSON responses and there will be overhead from the reading and streaming of the actual file.

Alternatively should OUR_URL point to a URL outside the scope of the REST service, so //localhost/files/pictures/1.jpg where it reads the file directly.

So the question is:

Should a RESTful API be able to return files, or just a location?

  • 1
    You do realize that the general description of what REST is amounts to "clients make requests to a URL and the server returns stuff", right? The whole idea is that REST is very loosely-defined and able to be adapted to almost any URL-based retrieval scheme. – user22815 Dec 31 '15 at 18:13
16

A RESTful service should provide resources to the users of the API. Resources can have various formats, which ranges from JSON or XML to JPEG and HTML.

There is not even a requirement, or even expectation, that a single API serves only resources of a single format. There is nothing wrong with serving a JSON document on the URI /myApi/pictures/1 and a JPEG file form the URI /myApi/files/pictures/1.
In a more extreme case, it is even possible to serve both the JSON description and the JPEG file from the same URL, depending on the format that the requester asks for.

7

One problem you'll have in just returning URIs is that a plain old file server can't do security. So if you need to do any sort of limitation on who can access a file, then you're going to need to be able to return it in the REST API directly (or not, if the user does not have rights, the file is not in the correct state, etc.).

Otherwise, returning the plain old URI and letting that go to a dedicated CDN has a lot of benefits around provisioning, simplicity, and scalability - assuming that's all you need to do.

  • The auth aspect is a very good point, something I had never considered. – Crazy Dino Jan 1 '16 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.