JSON1

JSON API Best Practices

Complete guide to designing high-quality, maintainable, and user-friendly JSON APIs

API Design Principles

Core Principles

  • Consistency: Unified naming and structural standards
  • Predictability: Developers can anticipate API behavior
  • Simplicity: Avoid unnecessary complexity
  • Scalability: Support future feature expansion
  • Backward Compatibility: Protect existing integrations

RESTful Design Guidelines

  • • Use nouns for resources, not verbs
  • • Leverage HTTP methods semantically
  • • Design clear hierarchical resource structures
  • • Maintain statelessness
  • • Implement proper HTTP status codes

Resource Design Examples

✅ Good Design

GET    /users              # Get user list
GET    /users/123          # Get specific user
POST   /users              # Create new user
PUT    /users/123          # Update user
DELETE /users/123          # Delete user
GET    /users/123/orders   # Get user's orders

❌ Poor Design

GET    /getUsers           # Using verbs
POST   /createUser         # Inconsistent naming
GET    /user_list          # Mixed naming styles
DELETE /deleteUser/123     # Redundant verbs
GET    /getUserOrders/123  # Overly complex

Naming Conventions

URL Naming Standards

Resource Naming Rules

  • • Use lowercase letters
  • • Use hyphens for word separation
  • • Use plural nouns for collections
  • • Use singular nouns for documents
  • • Avoid file extensions in URLs

Naming Examples

/user-profiles✅ Good
/userProfiles❌ CamelCase
/api/v1/orders✅ Versioned
/user_profiles❌ Underscores

JSON Field Naming

✅ Recommended - camelCase

{
  "userId": 123,
  "firstName": "John",
  "lastName": "Doe",
  "emailAddress": "john@example.com",
  "createdAt": "2024-01-01T00:00:00Z",
  "lastLoginDate": "2024-01-15T10:30:00Z"
}

❌ Avoid - snake_case

{
  "user_id": 123,
  "first_name": "John",
  "last_name": "Doe",
  "email_address": "john@example.com",
  "created_at": "2024-01-01T00:00:00Z",
  "last_login_date": "2024-01-15T10:30:00Z"
}

HTTP Methods Usage

GET

Retrieve data

Characteristics

  • Safe
  • Idempotent
  • Cacheable

Usage Examples

  • GET /users - Get all users
  • GET /users/123 - Get specific user
  • GET /users/123/orders - Get user orders
POST

Create new resources

Characteristics

  • Not safe
  • Not idempotent
  • Not cacheable

Usage Examples

  • POST /users - Create new user
  • POST /users/123/orders - Create order for user
  • POST /auth/login - User authentication
PUT

Update/replace entire resource

Characteristics

  • Not safe
  • Idempotent
  • Not cacheable

Usage Examples

  • PUT /users/123 - Replace entire user data
  • PUT /users/123/profile - Update complete profile
  • PUT /orders/456 - Replace order data
PATCH

Partial resource updates

Characteristics

  • Not safe
  • Not idempotent
  • Not cacheable

Usage Examples

  • PATCH /users/123 - Update user fields
  • PATCH /orders/456/status - Update order status
  • PATCH /users/123/password - Change password
DELETE

Remove resources

Characteristics

  • Not safe
  • Idempotent
  • Not cacheable

Usage Examples

  • DELETE /users/123 - Delete user
  • DELETE /orders/456 - Cancel order
  • DELETE /users/123/sessions - End all sessions

Status Code Standards

2xx Success Codes

200 OK

Successful GET, PUT, PATCH, DELETE

201 Created

Successful POST - resource created

204 No Content

Successful DELETE - no response body

4xx Client Error Codes

400 Bad Request

Invalid request syntax/parameters

401 Unauthorized

Authentication required

403 Forbidden

Valid request, insufficient permissions

404 Not Found

Resource does not exist

Error Handling

Standard Error Response Format

{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "Request validation failed",
    "details": "The email field is required and must be a valid email address",
    "timestamp": "2024-01-15T10:30:00Z",
    "path": "/api/v1/users",
    "requestId": "req_123456789",
    "fields": [
      {
        "field": "email",
        "message": "Email is required",
        "code": "REQUIRED_FIELD"
      },
      {
        "field": "age",
        "message": "Age must be between 18 and 120",
        "code": "INVALID_RANGE"
      }
    ]
  }
}

Error Response Fields

  • code: Machine-readable error identifier
  • message: Human-readable error description
  • details: Additional context information
  • timestamp: Error occurrence time
  • path: API endpoint where error occurred
  • requestId: Unique request identifier

Error Handling Best Practices

  • • Use consistent error response structure
  • • Provide actionable error messages
  • • Include request IDs for debugging
  • • Map validation errors to specific fields
  • • Avoid exposing sensitive information
  • • Log errors for monitoring and debugging

Quick Reference

API Design Checklist

Use RESTful resource naming
Implement proper HTTP methods
Return appropriate status codes
Design consistent error responses
Include API versioning strategy

Read this in another language