SyntaxStudy
Sign Up
REST API API Response Envelopes and JSON:API
REST API Beginner 1 min read

API Response Envelopes and JSON:API

A response envelope wraps the primary data in a consistent top-level structure alongside metadata and links. This avoids the security vulnerability of returning a bare JSON array as the top-level response (which is exploitable via Array prototype overrides in older browsers) and provides a stable structure for adding metadata without breaking clients. JSON:API is a specification for building APIs in JSON that standardises the envelope format, resource identification, relationships, and error objects. Libraries like Fractal (PHP) and jsonapi-serializer (Node.js) generate spec-compliant responses from your models.
Example
// Standard envelope (custom)
{
  "data": [ ... ],
  "meta": { "total": 200, "page": 1, "perPage": 20 },
  "links": { "self": "/products?page=1", "next": "/products?page=2" }
}

// JSON:API format (spec-compliant)
{
  "data": [
    {
      "type": "products",
      "id": "42",
      "attributes": {
        "name": "Running Shoes",
        "price": 89.99,
        "status": "active"
      },
      "relationships": {
        "category": {
          "data": { "type": "categories", "id": "5" }
        }
      },
      "links": { "self": "/products/42" }
    }
  ],
  "included": [
    {
      "type": "categories",
      "id": "5",
      "attributes": { "name": "Footwear" }
    }
  ],
  "meta": { "totalCount": 200 },
  "links": { "self": "/products", "next": "/products?page[number]=2" }
}

// Error envelope
{
  "errors": [
    {
      "status": "422",
      "code":   "VALIDATION_FAILED",
      "title":  "Validation Error",
      "detail": "The price must be a positive number.",
      "source": { "pointer": "/data/attributes/price" }
    }
  ]
}