The Lobster Den
Home to spelling errors, deprecated HTML and wholesome fun.
Nested JSON: The Root of all API Evil
2014-12-11 00:00:00 UTC
When developing an API, it is best to stay generic. This keeps your API ready for future changes and encourages API users to write clients that are flexible to change also.
One pitfall many developers fall into is making JSON endpoints that try to do everything in one request. Usually, this takes the form of deeply nested JSON structures.
An example might be a
/users endpoint that embeds all of the user’s
friends into one JSON structure.
This can create a lot of problems down the road such as:
- Unexpected circular references in your return JSON that crash your JSON encoder
- Slow request cycles and wasted bandwidth
- Slow N + 1 queries, even for simple GET requests
- JSON that is hard or impossible for humans to read
- Inability or difficulty in creating new API clients because endpoints are too specific to the needs of current API consumers
The alternative is simple: never nest more than one level deep, exercise discipline when deciding to embed resources and use hypermedia resource URLs where possible as an alternative to shipping the kitchen sink with every request.