REST API Response for Empty GUID – Best Practices

api-designiosnet

I have a .net api backend for mobile apps and the question came up (in conversation with the iOS develper) if a JSON response for an empty GUID should return:

  • 00000000-0000-0000-0000-000000000000
  • or null (by having the return type nullable Guid type (Guid?)

If the first one, the mobile developer needs to create a parse method for that and not use his regular generic null check function.

In C# you would just do

if (guid == Guid.Empty)

But the iOS developer talks about creating a parsing method (so not build in I guess).

But I canĀ“t find any discussion on what is considered "best practice" or even how native apps are dealing with empty/null Guid's.

I know what I like to do but what do you think I should do?

Best Answer

An 'empty' guid is still a valid guid, so parsing it shouldn't require any extra logic.

The question is why are you using it at all? It seems like a mistake to me to assign special meaning to a particular guid, making it a magic number.

It's a bit like saying I'll return an int id, but if it's negative then it's an error code. Don't do it!

..The reason being that in every call to your function, the user will have to remember to check for a negative return value. If they forget, disaster occurs.

Similarly, if you assign guid.empty a special meaning, everyone who calls your API has to write a special check after every call.

It's better to return null (if appropriate) or throw an exception (via an HTTP error code, assuming a REST service).

Related Topic