Should an API Return Numbers as Strings?
From the earlier reference collection. Read the current software blog.
Return quantities as numeric values for calculation, while reserving strings for identifiers and values whose exact formatting matters.
Use types that match the meaning
If a field represents a measurable or countable quantity, return it as a number. A JSON payload with "temperature": 14.6 lets software compare the value, calculate a mean, or convert units without first parsing text. Returning "14.6" shifts that conversion burden to every client and creates opportunities for inconsistent parsing.
The same applies to a count such as the number of active notices. A numeric type communicates that arithmetic is meaningful. Document whether fractional values are possible and what unit or scale applies.
Identifiers are not quantities
A string is usually appropriate for identifiers even when they contain only digits. A stop code like 00421 may need its leading zero preserved, and adding two stop codes has no useful meaning. Treating it as a number could silently change its identity to 421.
Strings also suit values whose exact presentation is significant, such as a formatted account reference or a decimal amount that must preserve a specified number of digits. In those cases, document the format and do not suggest that ordinary arithmetic applies.
Handle precision with care
Some numeric values cannot be represented exactly by common binary floating-point types. This matters when exact decimal arithmetic is required, such as financial amounts. An API may choose integer minor units, like cents, or a decimal string with a documented scale. Explain the choice so clients know whether rounding is expected.
For measurements, reasonable precision depends on the instrument and use. Returning many decimal places does not make a reading more accurate. State the resolution or rounding policy when it matters, and avoid converting a source value into a display-formatted string that clients must reverse-engineer.
Give clients a simple contract
Show example payloads that distinguish a quantity, an identifier, and a formatted value. For example, a record could use a numeric distance_meters, a string stop_id, and a string amount_decimal if exact decimal text is part of the contract.
Then validate types consistently across records. A field that is sometimes 12 and sometimes "12" forces clients to branch on representation before they can use the data. Consistent types make both software and documentation easier to trust.