Skip to content

Response Formats JSON and XML in REST API Design

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Response Formats JSON and XML in REST API Design. We cover key concepts, practical examples, and best practices to help you master this topic.

JSON and XML are the primary response formats in REST APIs, with JSON being the dominant choice for modern APIs due to its lightweight syntax, native JavaScript support, and simpler structure compared to verbose XML.

flowchart TD
  A[Response Formats] --> B[JSON]
  A --> C[XML]
  B --> B1[Lightweight]
  B --> B2[Native parsing]
  B --> B3[Nested objects]
  C --> C1[Verbose]
  C --> C2[Namespaces]
  C --> C3[Attributes vs elements]
  style B fill:#c8e6c9
  style C fill:#fff9c4

JSON uses key-value pairs, arrays, and nested objects to represent data. It is compact and maps directly to programming language data structures. XML uses tags, attributes, and namespaces. It is more verbose but supports features like namespaces that JSON lacks.

Think of JSON like a neatly organized shopping list with categories and items. XML is like a legal document with tags defining every piece of information. Both convey the same data, but JSON is quicker to read and write.

Example: Same Data in JSON and XML

import json
import xml.etree.ElementTree as ET

# JSON format
user_json = {
    "id": 42,
    "name": "Alice",
    "email": "alice@example.com",
    "roles": ["admin", "editor"],
    "address": {
        "city": "New York",
        "zip": "10001"
    }
}
print("JSON:", json.dumps(user_json, indent=2))

Expected output:

JSON: {
  "id": 42,
  "name": "Alice",
  "email": "alice@example.com",
  "roles": ["admin", "editor"],
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

Example: Parsing API Responses

import requests

# JSON response
response = requests.get("https://api.example.com/users/42")
user = response.json()
print(f"Name: {user['name']}")
print(f"Roles: {', '.join(user['roles'])}")
print(f"City: {user['address']['city']}")

Expected output:

Name: Alice
Roles: admin, editor
City: New York

Example: Envelope Pattern

import requests

# API with envelope pattern
response = requests.get("https://api.example.com/users?page=1")
envelope = response.json()
print(f"Status: {envelope['status']}")
print(f"Count: {envelope['count']}")
print(f"Data: {envelope['data']}")
print(f"Next page: {envelope['links']['next']}")

Expected output:

Status: success
Count: 10
Data: [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
Next page: /users?page=2

Common Mistakes

  1. Inconsistent field naming — Mixing camelCase (userName) and snake_case (user_name) confuses clients. Choose one convention and stick with it across all responses.
  2. Returning null vs omitting fields — Decide whether to include optional fields with null values or omit them entirely. Be consistent.
  3. Deeply nested JSON — Nesting beyond 3-4 levels makes responses hard to navigate. Flatten where possible or use Composite identifiers.
  4. Not including a top-level envelope for collections — Returning a raw array without count, pagination, or links forces clients to guess the structure.
  5. XML without proper namespaces — Missing namespace declarations can cause parsing failures in XML-savvy clients.

Practice Questions

  1. Why is JSON preferred over XML for most modern REST APIs?
  2. What is the envelope pattern and when should you use it?
  3. What are the pros and cons of camelCase vs snake_case in API responses?
  4. How do you represent dates in JSON responses?
  5. Challenge: Design a JSON response schema for a blog API that includes posts with authors, comments, tags, and pagination metadata. Write out an example response with at least 3 posts.

FAQ

Should I use camelCase or snake_case in JSON responses?

Either is fine, but be consistent. camelCase is common in JavaScript APIs. snake_case is common in Python APIs. Use what matches your ecosystem.

{{< faq "How do I return errors in JSON?" "Use a consistent error envelope: {"error": {"code": "VALIDATION_ERROR", "message": "Email is required", "details": [...]}}." >}}

What is the difference between JSON and JSONP?

JSON is pure data. JSONP wraps JSON in a callback function for cross-origin requests in browsers. Use CORS instead of JSONP for modern APIs.

How should I format timestamps in JSON?

Use ISO 8601 format: 2026-06-28T14:30:00Z. It is human-readable, timezone-aware, and widely supported by programming languages.

Can I use YAML for API responses?

Technically yes, but JSON is more widely supported. YAML is more common for configuration files than API responses.

Mini Project

Create a Python script that takes a Python dictionary and renders it as both JSON and XML. The script should handle nested objects, arrays, strings, numbers, booleans, and null values. Compare the size of JSON vs XML output.

What's Next

Now learn about filtering in REST API Design.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro