Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return empty json on null in WebAPI

Is it possible to return { } instead of null when webApi returns a null object? This, to prevent my user from getting errors while parsing the response. And to make the response a valid Json Response?

I know that i could be setting it everywhere manually. That when null is the response, an empty Json object should be returned. But, is there a way to do it automaticly for every response?

like image 345
Spons Avatar asked Mar 31 '14 13:03

Spons


People also ask

Is an empty JSON null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types." "The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

How check JSON result is empty?

If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }

Should API return null or empty array?

If you usually return an array, and empty array is probably a good choice. But if you usually return an object, then, IMHO, null is acceptable and may be better than an empty object. If you usually return just a string or a number, then null would probably be the preferred choice.


1 Answers

If you are building a RESTful service, and have nothing to return from the resource, I believe that it would be more correct to return 404 (Not Found) than a 200 (OK) response with an empty body.

like image 68
Mark Seemann Avatar answered Oct 02 '22 00:10

Mark Seemann