JSONly Viewer

Professional JSON validation, formatting, and visualization for developers

JSON API Documentation Guide: Best Practices & Examples

JSON APIs are the backbone of modern web applications. This comprehensive guide covers everything you need to know about working with JSON APIs, from understanding request/response formats to implementing proper error handling and testing strategies.

Understanding JSON APIs

A JSON API is a web service that accepts requests and returns responses in JSON format. Most modern REST APIs use JSON as their primary data exchange format due to its simplicity, readability, and universal support across programming languages.

💡 Why JSON for APIs?

  • Lightweight - Smaller payload than XML
  • Human-readable - Easy to debug and understand
  • Native JavaScript support - No parsing needed in browsers
  • Language agnostic - Supported by all modern languages

REST API Fundamentals

HTTP Methods and JSON

GET - Retrieve Data

GET /api/users/123
Accept: application/json

Response:
{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2024-01-15T10:30:00Z"
}

POST - Create Data

POST /api/users
Content-Type: application/json

Request Body:
{
  "name": "Jane Smith",
  "email": "jane@example.com",
  "password": "securepassword123"
}

Response:
{
  "id": 124,
  "name": "Jane Smith",
  "email": "jane@example.com",
  "created_at": "2024-01-15T11:00:00Z",
  "message": "User created successfully"
}

PUT - Update Data

PUT /api/users/123
Content-Type: application/json

Request Body:
{
  "name": "John Smith",
  "email": "johnsmith@example.com"
}

Response:
{
  "id": 123,
  "name": "John Smith",
  "email": "johnsmith@example.com",
  "updated_at": "2024-01-15T12:00:00Z",
  "message": "User updated successfully"
}

DELETE - Remove Data

DELETE /api/users/123

Response:
{
  "message": "User deleted successfully",
  "deleted_id": 123,
  "timestamp": "2024-01-15T13:00:00Z"
}

JSON API Response Formats

Standard Success Response

{
  "status": "success",
  "data": {
    "id": 123,
    "name": "Product Name",
    "price": 29.99,
    "category": "Electronics"
  },
  "meta": {
    "timestamp": "2024-01-15T10:30:00Z",
    "version": "1.0",
    "request_id": "req_abc123"
  }
}

Paginated Response

{
  "status": "success",
  "data": [
    {
      "id": 1,
      "name": "User 1"
    },
    {
      "id": 2,
      "name": "User 2"
    }
  ],
  "pagination": {
    "current_page": 1,
    "per_page": 20,
    "total_pages": 5,
    "total_items": 100,
    "has_next": true,
    "has_previous": false
  },
  "links": {
    "first": "/api/users?page=1",
    "last": "/api/users?page=5",
    "next": "/api/users?page=2",
    "previous": null
  }
}

Error Response Format

{
  "status": "error",
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request data is invalid",
    "details": [
      {
        "field": "email",
        "code": "INVALID_FORMAT",
        "message": "Email format is invalid"
      },
      {
        "field": "password",
        "code": "TOO_SHORT",
        "message": "Password must be at least 8 characters"
      }
    ]
  },
  "meta": {
    "timestamp": "2024-01-15T10:30:00Z",
    "request_id": "req_def456"
  }
}

HTTP Status Codes with JSON APIs

Success Codes (2xx)

Client Error Codes (4xx)

Server Error Codes (5xx)

Authentication in JSON APIs

API Key Authentication

GET /api/users
Authorization: Bearer your-api-key-here
Accept: application/json

JWT Token Authentication

POST /api/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "password123"
}

Response:
{
  "status": "success",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expires_in": 3600,
    "user": {
      "id": 123,
      "name": "John Doe"
    }
  }
}

Using JWT Token

GET /api/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json

API Versioning

URL Path Versioning

GET /api/v1/users
GET /api/v2/users

Header Versioning

GET /api/users
Accept: application/vnd.api+json;version=1

Query Parameter Versioning

GET /api/users?version=1

Rate Limiting

Rate Limit Headers

HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
Content-Type: application/json

{
  "data": "response data"
}

Rate Limit Exceeded Response

HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640995200
Retry-After: 3600

{
  "status": "error",
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests. Please try again later.",
    "retry_after": 3600
  }
}

Testing JSON APIs

🛠️ Essential API Testing Tools

  • Postman - GUI-based API testing
  • curl - Command-line HTTP client
  • HTTPie - User-friendly command-line tool
  • JSONly Viewer - Validate and format API responses

Testing with curl

# GET request
curl -X GET "https://api.example.com/users" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer your-token"

# POST request
curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com"
  }'

Testing with HTTPie

# GET request
http GET api.example.com/users \
  Authorization:"Bearer your-token"

# POST request
http POST api.example.com/users \
  Authorization:"Bearer your-token" \
  name="John Doe" \
  email="john@example.com"

API Documentation Best Practices

Essential Documentation Elements

OpenAPI/Swagger Specification

openapi: 3.0.0
info:
  title: User API
  version: 1.0.0
paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string

Common API Patterns

Filtering

GET /api/users?status=active&role=admin
GET /api/products?category=electronics&price_min=100&price_max=500

Sorting

GET /api/users?sort=name&order=asc
GET /api/products?sort=price&order=desc

Field Selection

GET /api/users?fields=id,name,email
GET /api/products?fields=id,name,price

Search

GET /api/users?search=john
GET /api/products?q=laptop&category=electronics

Error Handling Strategies

Validation Error Response

{
  "status": "error",
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "value": "invalid-email",
        "code": "INVALID_EMAIL",
        "message": "Please provide a valid email address"
      }
    ]
  }
}

Not Found Error

{
  "status": "error",
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "User with ID 999 not found",
    "resource": "user",
    "resource_id": 999
  }
}

Server Error Response

{
  "status": "error",
  "error": {
    "code": "INTERNAL_SERVER_ERROR",
    "message": "An unexpected error occurred. Please try again later.",
    "request_id": "req_abc123"
  }
}

Performance Optimization

Caching Headers

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
ETag: "abc123"
Last-Modified: Mon, 15 Jan 2024 10:30:00 GMT

Compression

GET /api/users
Accept-Encoding: gzip, deflate

HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Type: application/json

Pagination for Large Datasets

GET /api/users?page=1&limit=50

{
  "data": [...],
  "pagination": {
    "current_page": 1,
    "per_page": 50,
    "total": 1000,
    "total_pages": 20
  }
}

Security Best Practices

🔒 Security Checklist

  • Use HTTPS - Always encrypt API communications
  • Validate input - Sanitize all incoming data
  • Implement rate limiting - Prevent abuse
  • Use proper authentication - JWT, OAuth, or API keys
  • Log security events - Monitor for suspicious activity

Input Validation

{
  "name": {
    "type": "string",
    "minLength": 1,
    "maxLength": 100,
    "pattern": "^[a-zA-Z\s]+$"
  },
  "email": {
    "type": "string",
    "format": "email"
  },
  "age": {
    "type": "integer",
    "minimum": 0,
    "maximum": 150
  }
}

Monitoring and Analytics

Key Metrics to Track

Logging Best Practices

{
  "timestamp": "2024-01-15T10:30:00Z",
  "level": "INFO",
  "method": "GET",
  "path": "/api/users/123",
  "status_code": 200,
  "response_time": 45,
  "user_id": 456,
  "ip_address": "192.168.1.1",
  "user_agent": "Mozilla/5.0..."
}

Conclusion

Building robust JSON APIs requires attention to detail in design, implementation, and documentation. By following these best practices and patterns, you can create APIs that are reliable, secure, and easy to use.

Remember to always validate your JSON responses and test your APIs thoroughly. Use JSONly Viewer to validate, format, and explore your API responses during development and testing.

📚 Additional Resources

  • Complete JSON Guide - Master JSON syntax and validation
  • JSON Tools - Discover the best JSON utilities
  • REST API Design Guidelines - Industry standards
  • OpenAPI Specification - API documentation standard