RESTful API – Should It Return Files or Just a Location?

patterns-and-practicesrest

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?

Best Answer

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.

Related Topic