API – Trailing Slash in RESTful API

apihttprest

I have been having a debate about what to do with a trailing slash in a RESTful API.

Lets say I have a resource called dogs and subordinate resources for individual dogs. We can therefore do the following:

GET/PUT/POST/DELETE http://example.com/dogs
GET/PUT/POST/DELETE http://example.com/dogs/{id}

But what do we do with the following special case:

GET/PUT/POST/DELETE http://example.com/dogs/

My personal view is that this is saying send a request to an individual dog resource with id = null. I think the API should return a 404 for this case.

Others say the request is accessing the dogs resource i.e. the trailing slash is ignored.

Does anyone know the definitive answer?

Best Answer

None of this is authoritative (as REST has no exact meaning). But from the original paper on REST a full (not ending in /) URL names a resource, while one ending in a slash '/' is a resource group (probably not worded like that).

A GET of a URL with a slash on the end is supposed to list the resources available.

GET http://example.com/dogs/          /* List all the dogs resources */

A PUT on a URL with a slash is supposed to replace all the resources.

PUT http://example.com/dogs/          /* Replace all the dogs resources */

A DELETE on a URL with a slash is supposed to delete all the resources

DELETE http://example.com/dogs/       /* Deletes all the dogs resources */

A POST on a URL with a slash is supposed to create a new resource can then be subsequently accessed. To be conformant the new resource should be in this directory (though lots of RESTful architectures cheat here).

POST http://example.com/dogs/        /* Creates a new dogs resource (notice singular) */

etc.

The wiki page on the subject seems to explain it well:

See example https://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_Web_services.