Designing a REST API: Unix time vs ISO-8601
cowboy: If you ever need to convince a colleague that ISO8601 is better for an API than unix time… http://t.co/bi8rwwBE38 http://t.co/MboZhcV4Ss
Friday February 22 2013
In what format should a REST API return and accept timestamps? The two most popular ways are Unix time (or a slight variation thereof) or ISO-8601. Both have their strengths and weaknesses and both are equally popular as we shall see. A sample of 20 APIs yielded nearly a 50/50 split. Therefore, no matter if this holds any persuasion or not, one can walk away knowing that their method of choice given Unix time or ISO-8601, is common knowledge and shouldn’t present a steep learning curve to other developers.
Unix time is completely unambiguous. It’s the number of seconds since January 1st, 1970. It’s a number and is extremely simple to convert to and from various formats. For more information, visit unix4lyfe, but in short, there are a lot of benefits to working with just a number. The nice thing about Unix time is that there is often little error checking and it is often a timestamp is stored in the database, so no conversion is necessary.
The downfall of Unix time is that it is not human readable. Until the response or request has been converted, the timestamp is essentially unintelligible. While the conversion isn’t hard for a computer, it is for a human, and we want to write an API that other humans consume. To fix this is ISO-8601. It presents the data in a well defined, human readable string format. This allows for easier development as one can curl or issue an HTTP GET request against the API and verify the timestamps.
It is in my opinion that a REST API should implement ISO-8601. The only advantages that Unix time has is that there is little conversion to and from the database. I find this advantage to be minimal at best. Conversion to and from a string in the format of yyyy-MM-dd'T'HH:mm:ssZ
to an integer only adds a few cycles in the worse case. The human readability benefit of ISO-8601 cannot be measured. When I’m developing with a REST API and I start crafting my queries, I write them by hand and the time alone from not worrying about converting timestamps into Unix time is probably more than the time saved if I had used Unix time.
Data from sampled REST APIs:
Note: flattr was the only API that had both Unix time and ISO-8601 in the response. Unix time was denoted by appending “_in_seconds” to the field.