Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest API best practice returning a single string vs wrap it in JSON object?

Tags:

json

rest

I have an endpoint that can return one of several states, e.g. 'Active', 'Cancelled' etc.

Is it bad practice to just return this as a string in the response, like:

"Active"

or should I wrap it in a JSON object, like:

{
    "status": "Active"
}
like image 533
rmf Avatar asked Nov 17 '25 10:11

rmf


1 Answers

The currently registered reference for JSON is RFC 8259

A JSON value MUST be an object, array, number, or string, or one of the following three literal names:

  • false
  • null
  • true

So returning a quoted string is fine when that's the natural representation of your resource.


Where things have the potential to get complicated: discovering later that the natural representation of your resource is a message, rather than a string.

The justification for using an object is that it gives us the flexibility to introduce backwards compatible changes to the schema so that we can include more information, without breaking clients that only know about the original schema. That's a lot harder to do when your representation is "just" a string.

But it is a tradeoff: what you pay for the future flexibility is slightly less convenient handling when the one string is all you need.

If you control all of the API consumers, and can change the consumers in lock step with the schema, then you can start with the simple answer, and put in the work to fix everything if it turns out that you need the more complicated representation.

This plan isn't nearly as appealing when you don't control the clients, or when making a lockstep change is expensive.

If you are creating an externally exposed API, then it is unlikely that you control all of the clients.

That said, with careful design you will also have the option of just introducing new resources to cover the cases where you actually need messages with multiple values.

My strongest recommendation here: whatever path you take, leave a paper trail. Document everything you know when you make your choice, and what you expect the risks and complications to be going forward. That way, future you will be able to recover the context of your decision.

like image 79
VoiceOfUnreason Avatar answered Nov 19 '25 02:11

VoiceOfUnreason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!