How to optimize your JSON API response
JSON stands for JavaScript Object Notation and it is a lightweight format for storing and transporting data often used when data is sent from a server to a web page.
In my developer experience, sometimes, I have found very slow and heavy API responses so, in this story, I will explain some easy tips to improve the performance of any API working on JSON responses:
- Minimize data size using short and Descriptive keys with camelCase
// Inefficient
{
"first_name": "John",
"last_name": "Doe"
}
// Efficient
{
"firstName": "John",
"lastName": "Doe"
}
2. Abbreviate when it’s possible without sacrificing clarity
// Inefficient
{
"applicationVersion": "v102.3"
}
// Efficient
{
"appVer": "v102.3"
}
3. Use Arrays Wisely minimizing nesting and avoiding deeply nested arrays, as they can increase the complexity of parsing and traversing JSON.
// Inefficient
{
"product": {
"id": 123,
"name": "Acme Prod",
"colors": {
"color1": "Red",
"color2": "Blue",
"color3": "Green"
}
}
}
// Efficient
{
"productId": 123,
"productName": "Acme Prod",
"productColors": ["Red", "Blue", "Green"]
}
3. Optimize Number Representations using integers when possible
// Inefficient
{
"price": 99.90
}
// Efficient
{
"price": 9990
}
The price 9990 is 99.90 * 100 and it’s a simple example of how this could be a standard convention for Backend and Frontend communication via API.
4. Remove Redundancy avoiding repetitive data
// Inefficient
{
"product1": {
"name": "Product A",
"price": 100
},
"product2": {
"name": "Product A",
"price": 200
}
}
// Efficient
{
"products": [
{
"name": "Product A",
"price": 100
},
{
"name": "Product B",
"price": 200
}
]
}
5. Use Compression Algorithms such as Gzip or Brotli
6. Use Server-Side Caching with specific TTLs for any endpoint group