BigJobbies BigJobbies - 6 months ago 35
PHP Question

Laravel 5.2 Dingo API returning no records

I was wondering if someone could give me a bit of guidance.

Im following a tutorial on building an API with Laravel which is found here

which is working well, but the problem im having is error responses and best practices.

If there are records in the DB then a simple

return $records;

works great, but what about when there are no records found?

In the tutorial, when no records are found it throws a http exception

throw new NotFoundHttpException;

but this returns a 404, which im not sure is relevant for no records in a DB, a 404 is more a page not found sort of thing isnt it?

So, i guess what im asking is, what is the best practice for returning a no records found in an API?

Any help would be greatly appreciated.



You should handle it depending on the type of resource that is requested.

Single Resource

When the requested resource is a single record, like for example /api/v1/posts/1, and there is no record with that id (1 in the example), you should return a 404 Not Found. The requested location does not exists.

Resource Collection

When the requested resource is a collection of records, for example 'all posts' (/api/v1/posts) and there are no records for that type of resource, you return a 200 OK with an empty collection in the body. The requested location does exist, so it would be inappropriate to respond with a 404 here.

A JSON response body to a request for a collection with no records could for example look like so:

    "posts": []