REST vs GraphQL Overview
REST in Magento 2
// REST API endpoint
// GET /rest/V1/products/:sku
// POST /rest/V1/carts/mine/items
// PUT /rest/V1/carts/mine/items/:itemId
// Magento REST implementation
class ProductController implements
\Magento\Framework\Api\SearchCriteriaInterface
{
public function get($sku)
{
return $this->productRepository->get($sku);
}
}
GraphQL in Magento 2
# GraphQL query
query {
products(filter: { sku: { eq: "24-WB04" } }) {
items {
name
sku
price_range {
minimum_price {
regular_price { value currency }
}
}
description { html }
}
}
}
Core Difference
REST: Resource-oriented
├── /products/123
├── /orders/456
└── /customers/789
GraphQL: Query-oriented
{
product(id: 123) { name price }
order(id: 456) { status items }
}
Performance Analysis
Network Efficiency
REST (multiple endpoints):
GET /products/123 → 2KB response
GET /products/123/attrs → 5KB response
GET /products/123/stock → 1KB response
Total: 3 requests, 8KB
GraphQL (single query):
query { product(id: 123) {
name price attributes { name value }
stock { quantity }
}}
Total: 1 request, 6KB
Over-fetching Problem
// REST: Fixed response structure
// GET /products/123 returns ALL fields
{
"id": 123,
"name": "Widget",
"price": 29.99,
"description": "Long HTML...", // Not needed
"categories": [...], // Not needed
"related_products": [...] // Not needed
}
// GraphQL: Request only what you need
query {
product(id: 123) {
name
price_range {
minimum_price { regular_price { value } }
}
}
}
Under-fetching (N+1 Problem)
REST: Multiple round trips needed
GET /orders/456 → order with customer_id
GET /customers/789 → customer details
GET /addresses/101 → shipping address
GraphQL: Single query with resolution
query {
order(id: 456) {
customer { name email }
shipping_address { city zip }
}
}
Caching Comparison
REST Caching
// HTTP caching headers
// GET /rest/V1/products/123
// Cache-Control: max-age=3600
// ETag: "abc123"
// Last-Modified: Wed, 01 Jan 2025 00:00:00 GMT
// Varnish cache keys
cache_key = http_host + request_uri
// Easy to cache at HTTP level
// CDN-friendly
// Redis cache for REST
$cacheKey = 'rest_product_' . $sku;
$this->cache->save($response, $cacheKey, [], 3600);
GraphQL Caching Challenges
# Different queries, same data
query { product(id: 123) { name price } }
query { product(id: 123) { name description } }
# Cache key = entire query string
# Same product cached multiple times
# Solution: Normalized cache
{
"Product:123": {
"name": "Widget",
"price": 29.99,
"description": "Long HTML..."
}
}
Cache Strategy Comparison
| Aspect | REST | GraphQL |
|---|---|---|
| HTTP Cache | Easy (GET requests) | Complex (POST queries) |
| CDN | Native support | Needs persisted queries |
| Client Cache | Simple URL-based | Normalized/Apollo |
| Invalidation | URL-based | Query-based |
| Persistence | Not needed | Persisted queries helpful |
Complexity Analysis
Implementation Complexity
// REST: Simple, well-understood
// routes/api.php
Route::get('/products/{id}', 'ProductController@show');
Route::post('/orders', 'OrderController@store');
// GraphQL: Schema design required
type Product {
id: ID!
name: String!
sku: String!
price: Money!
stock: StockLevel
}
type Query {
product(id: ID!): Product
products(filter: ProductFilterInput): ProductConnection
}
Client Complexity
// REST client
const product = await fetch('/api/products/123');
const data = await product.json();
// GraphQL client (Apollo)
const { data } = await client.query({
query: GET_PRODUCT,
variables: { id: 123 }
});
// GraphQL requires schema knowledge
// REST is self-documenting via endpoints
Maintenance Overhead
REST:
+ Endpoints are self-contained
+ Easy to version (v1, v2)
+ Simple to debug (URL-based)
- Many endpoints to maintain
- Versioning creates duplication
GraphQL:
+ Single endpoint
+ Schema evolution without versioning
+ Strong typing
- Schema complexity grows
- Resolver performance issues
- Harder to debug
Practice Problems
Design an API strategy for a Magento store with mobile app, web frontend, and third-party integrations.
Solution
// Strategy:
// 1. Mobile app: GraphQL (flexible queries, fewer requests)
// 2. Web frontend: REST (HTTP caching, CDN)
// 3. Third-party: REST (standard, well-documented)
// 4. Admin: REST (Magento admin patterns)
// 5. Shared authentication layer Quiz
1. When is REST preferred over GraphQL?
2. What problem does GraphQL solve that REST struggles with?
3. What is the main caching challenge with GraphQL?
4. How does Magento 2 handle GraphQL caching?
Flashcards
Question
REST main advantage?
Click to reveal answer
Answer
Simple HTTP caching, CDN-friendly, self-documenting
Question
GraphQL main advantage?
Click to reveal answer
Answer
Flexible queries, no over/under-fetching, single endpoint
Question
GraphQL caching challenge?
Click to reveal answer
Answer
Different queries for same data create cache duplication
Question
REST versioning approach?
Click to reveal answer
Answer
URL-based: /rest/V1/, /rest/V2/
Question
GraphQL versioning approach?
Click to reveal answer
Answer
Schema evolution without versioning, deprecation fields
Revision Notes
Key Takeaways
- 1. REST: Better for caching, CDNs, simple CRUD, standard HTTP patterns
- 2. GraphQL: Better for flexible queries, mobile apps, complex data needs
- 3. REST over-fetches: fixed response structure returns all fields
- 4. GraphQL caching requires normalized cache or persisted queries
- 5. Choose based on client needs and team expertise
Interview Tips
- • Explain over-fetching and under-fetching problems
- • Compare caching strategies for each approach
- • Discuss when to use each API style
- • Know Magento 2's implementation of both
Cheat Sheet
REST vs GraphQL
- REST: Cache-friendly, CDN, simple
- GraphQL: Flexible, single endpoint, typed
- REST: Over-fetching risk
- GraphQL: Under-fetching solved
- GraphQL caching: Normalized/persisted
- Magento: Uses both REST and GraphQL