BigJobbies
BigJobbies

Reputation: 4045

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

https://www.sitepoint.com/how-to-build-an-api-only-jwt-powered-laravel-app/

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.

Cheers

Upvotes: 0

Views: 288

Answers (1)

jsphpl
jsphpl

Reputation: 5070

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 exist.

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": []
}

Upvotes: 1

Related Questions