Skip to content
advanced Phase 100 · Senior Practices

API Design Principles

API design principles including RESTful design, API versioning, documentation, and governance for Magento APIs

1h
0 problems
Topic Progress 0%

RESTful API Design

Resource Naming

# Good: nouns, plural, hierarchical
GET /api/v1/orders
GET /api/v1/orders/123
GET /api/v1/orders/123/items
GET /api/v1/customers/456/orders

# Bad: verbs, singular, flat
GET /api/getOrders
GET /api/order/123
POST /api/createOrder

HTTP Methods

# CRUD operations
GET    /api/v1/orders          # List orders
GET    /api/v1/orders/123      # Get order
POST   /api/v1/orders          # Create order
PUT    /api/v1/orders/123      # Update order (full)
PATCH  /api/v1/orders/123      # Update order (partial)
DELETE /api/v1/orders/123      # Delete order

# Non-CRUD operations
POST   /api/v1/orders/123/cancel
POST   /api/v1/orders/123/invoice
POST   /api/v1/orders/123/ship

Response Format

{
    "status": "success",
    "data": {
        "order_id": 123,
        "status": "processing",
        "total": 100.00,
        "items": [
            {
                "item_id": 1,
                "name": "Product A",
                "quantity": 2,
                "price": 50.00
            }
        ]
    },
    "meta": {
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T10:30:00Z"
    }
}

Error Response

{
    "status": "error",
    "error": {
        "code": "VALIDATION_ERROR",
        "message": "Invalid input data",
        "details": [
            {
                "field": "email",
                "message": "Invalid email format"
            }
        ]
    }
}

Pagination

GET /api/v1/orders?page=2&per_page=20

# Response headers
X-Total-Count: 150
X-Total-Pages: 8
Link: </api/v1/orders?page=1>; rel="prev", </api/v1/orders?page=3>; rel="next"

Key Takeaway

Use resource-based URLs with HTTP verbs. Return consistent response formats with proper status codes. Implement pagination for collections.

API Versioning

Versioning Strategies

# URL path versioning (recommended)
GET /api/v1/orders
GET /api/v2/orders

# Header versioning
GET /api/orders
Accept: application/vnd.store.v1+json

# Query parameter versioning
GET /api/orders?version=1

Magento REST API Versioning

// Webapi.xml versioning
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    
    <!-- V1 API -->
    <route url="/V1/orders/:orderId" method="GET">
        <service class="Magento\Sales\Api\OrderRepositoryInterface" method="getById"/>
        <resources>
            <resource ref="Magento_Sales::actions_view"/>
        </resources>
    </route>
    
    <!-- V2 API -->
    <route url="/V2/orders/:orderId" method="GET">
        <service class="Vendor\Api\V2\OrderRepositoryInterface" method="getById"/>
        <resources>
            <resource ref="Magento_Sales::actions_view"/>
        </resources>
    </route>
</routes>

Version Deprecation

// Deprecation header
header('Deprecation: true');
header('Sunset: Sat, 01 Jan 2025 00:00:00 GMT');
header('Link: </api/v2/orders>; rel="successor-version"');

Versioning Strategy

## API Versioning Rules

1. Major version for breaking changes
2. Minor version for new features
3. Never remove deprecated endpoints immediately
4. Support at least 2 major versions
5. Document deprecation timeline

## Breaking Changes

- Remove field from response
- Change field type
- Change URL structure
- Change authentication method
- Remove endpoint

Key Takeaway

Use URL path versioning for clarity. Support multiple versions with deprecation notices. Never make breaking changes without a new major version.

API Documentation

OpenAPI/Swagger Documentation

openapi: 3.0.0
info:
  title: Magento REST API
  version: 1.0.0
paths:
  /api/v1/orders:
    get:
      summary: List orders
      parameters:
        - name: page
          in: query
          schema:
            type: integer
        - name: per_page
          in: query
          schema:
            type: integer
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderList'

Magento GraphQL Documentation

"""
Order management queries and mutations
"""
type Query {
    """
    Get order by ID
    Requires: sales/orders/view permission
    """
    order(order_id: Int!): Order
    
    """
    Get orders for current customer
    """
    customerOrders: CustomerOrderConnection
}

type Order {
    """
    Unique order identifier
    """
    order_id: Int!
    
    """
    Current order status
    Possible values: new, processing, complete, canceled
    """
    status: String!
    
    """
    Order total in base currency
    """
    grand_total: Float!
}

Postman Collection

{
    "info": {
        "name": "Magento API",
        "description": "Complete Magento REST API collection"
    },
    "item": [
        {
            "name": "Orders",
            "item": [
                {
                    "name": "List Orders",
                    "request": {
                        "method": "GET",
                        "url": "{{base_url}}/api/v1/orders"
                    }
                }
            ]
        }
    ]
}

Key Takeaway

Document APIs with OpenAPI/Swagger, GraphQL schema documentation, and Postman collections. Include examples, error codes, and authentication details.

API Governance

API Review Process

## API Review Checklist

### Design
- [ ] Resource naming follows conventions
- [ ] HTTP methods used correctly
- [ ] Response format consistent
- [ ] Pagination implemented
- [ ] Error handling proper

### Security
- [ ] Authentication required
- [ ] Authorization checked
- [ ] Input validation present
- [ ] Rate limiting configured
- [ ] Sensitive data not exposed

### Documentation
- [ ] OpenAPI spec updated
- [ ] Examples provided
- [ ] Error codes documented
- [ ] Authentication documented

Rate Limiting

// Rate limiting configuration
$rateLimiter = [
    'global' => ['requests' => 1000, 'window' => 60],
    'customer' => ['requests' => 100, 'window' => 60],
    'guest' => ['requests' => 50, 'window' => 60],
];

// Response headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

API Deprecation Policy

## Deprecation Policy

1. Announce deprecation 6 months before removal
2. Add deprecation headers to responses
3. Document migration guide
4. Support old version during transition
5. Monitor usage of deprecated endpoints
6. Notify API consumers before removal

API Metrics

// Track API usage
$metrics = [
    'endpoint' => '/api/v1/orders',
    'method' => 'GET',
    'status_code' => 200,
    'response_time' => 45,  // ms
    'consumer_id' => 'partner_123',
];

// Monitor:
// - Response times
// - Error rates
// - Usage by endpoint
// - Usage by consumer

Key Takeaway

Establish API governance with review process, rate limiting, deprecation policy, and usage monitoring. Ensure consistency and security across all APIs.

Quiz

1. What is the recommended versioning strategy?

Question 1 options

2. What HTTP status code for successful creation?

Question 2 options

3. What is API governance?

Question 3 options

4. What is the deprecation notice period?

Question 4 options

5. What format for API documentation?

Question 5 options

Flashcards

Question

What is RESTful naming?

Answer

Nouns, plural, hierarchical: /api/v1/orders/123/items

Question

Recommended versioning?

Answer

URL path versioning: /api/v1/, /api/v2/

Question

HTTP status for creation?

Answer

201 Created

Question

What is API governance?

Answer

Policies and processes for API management and consistency

Question

Deprecation notice period?

Answer

6 months minimum before removal

Question

API documentation format?

Answer

OpenAPI/Swagger for REST, GraphQL schema for GraphQL

Revision Notes

Key Takeaways

  • 1. Use resource-based URLs with HTTP verbs
  • 2. Implement URL path versioning
  • 3. Document with OpenAPI/Swagger
  • 4. Establish API governance with review process
  • 5. Rate limit and monitor API usage

Interview Tips

  • Explain RESTful API design principles
  • Discuss API versioning strategies
  • Describe API documentation approach
  • Explain API governance practices

Cheat Sheet

API Design

RESTful:
Nouns, plural, hierarchical
GET/POST/PUT/PATCH/DELETE

Versioning:
URL path: /api/v1/
6 month deprecation notice

Documentation:
OpenAPI/Swagger
GraphQL schema
Postman collections

Governance:
Review checklist
Rate limiting
Deprecation policy
Usage monitoring