Magento 2 REST API: Guida Completa con Esempi

Le REST API di Magento 2 rappresentano uno strumento fondamentale per l'integrazione e l'estensione delle funzionalità dell'e-commerce platform. Questa guida completa ti accompagnerà attraverso tutti gli aspetti essenziali delle Magento API, fornendo esempi pratici e best practices per sviluppatori e professionisti IT.

Introduzione alle REST API di Magento 2

Magento 2 offre un sistema di API REST robusto e ben strutturato che consente di interagire programmaticamente con tutte le funzionalità del sistema. Le API seguono i principi REST (Representational State Transfer) e utilizzano il formato JSON per lo scambio di dati, rendendo l'integrazione semplice e intuitiva per gli sviluppatori.

L'architettura API di Magento 2 si basa su diversi componenti chiave:

  • Service Contracts: Definiscono le interfacce per le operazioni business
  • Repository Pattern: Gestisce la persistenza dei dati
  • Data Objects: Rappresentano le entità del sistema
  • Authentication: Sistema di autenticazione basato su token

Configurazione e Autenticazione

Tipi di Autenticazione

Magento 2 supporta diversi metodi di autenticazione per le API REST:

1. Token-based Authentication (Admin)

Per ottenere un token di autenticazione admin, effettua una richiesta POST all'endpoint di login:

curl -X POST "https://your-magento-store.com/rest/V1/integration/admin/token" \
     -H "Content-Type: application/json" \
     -d '{
       "username": "admin_username",
       "password": "admin_password"
     }'

La risposta conterrà il token da utilizzare nelle successive richieste:

"4hoioi5cu7gdkx1ovd20a8k9kdl1ip2q"

2. Token-based Authentication (Customer)

Per l'autenticazione customer, utilizza l'endpoint dedicato:

curl -X POST "https://your-magento-store.com/rest/V1/integration/customer/token" \
     -H "Content-Type: application/json" \
     -d '{
       "username": "customer@email.com",
       "password": "customer_password"
     }'

3. OAuth-based Authentication

OAuth è il metodo raccomandato per applicazioni di terze parti. Prima di utilizzarlo, è necessario creare un'integrazione nel pannello admin di Magento.

Utilizzo del Token nelle Richieste

Una volta ottenuto il token, includilo nell'header Authorization di ogni richiesta:

curl -X GET "https://your-magento-store.com/rest/V1/products" \
     -H "Authorization: Bearer your_token_here" \
     -H "Content-Type: application/json"

Struttura degli Endpoint API

Gli endpoint delle Magento API seguono una struttura logica e prevedibile:

https://your-domain.com/rest/[store_code]/V1/[module]/[interface_name]/[parameters]

Dove:

  • store_code: Codice del negozio (opzionale, default se omesso)
  • V1: Versione dell'API
  • module: Modulo Magento (es. products, customers, orders)
  • interface_name: Nome dell'interfaccia del service contract
  • parameters: Parametri specifici dell'endpoint

Gestione dei Prodotti tramite API

Recuperare Prodotti

Per ottenere l'elenco dei prodotti con filtri e paginazione:

curl -X GET "https://your-magento-store.com/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=status&searchCriteria[filterGroups][0][filters][0][value]=1&searchCriteria[pageSize]=20" \
     -H "Authorization: Bearer your_token" \
     -H "Content-Type: application/json"

Creare un Nuovo Prodotto

Esempio di creazione di un prodotto semplice:

curl -X POST "https://your-magento-store.com/rest/V1/products" \
     -H "Authorization: Bearer your_token" \
     -H "Content-Type: application/json" \
     -d '{
       "product": {
         "sku": "test-product-001",
         "name": "Test Product",
         "attribute_set_id": 4,
         "price": 29.99,
         "status": 1,
         "visibility": 4,
         "type_id": "simple",
         "weight": 1.5,
         "extension_attributes": {
           "stock_item": {
             "qty": 100,
             "is_in_stock": true
           }
         }
       }
     }'

Aggiornare un Prodotto Esistente

curl -X PUT "https://your-magento-store.com/rest/V1/products/test-product-001" \
     -H "Authorization: Bearer your_token" \
     -H "Content-Type: application/json" \
     -d '{
       "product": {
         "sku": "test-product-001",
         "name": "Updated Test Product",
         "price": 34.99
       }
     }'

Gestione Clienti e Ordini

Operazioni sui Clienti

Recuperare informazioni di un cliente specifico:

curl -X GET "https://your-magento-store.com/rest/V1/customers/123" \
     -H "Authorization: Bearer your_token" \
     -H "Content-Type: application/json"

Creare un nuovo cliente:

curl -X POST "https://your-magento-store.com/rest/V1/customers" \
     -H "Authorization: Bearer your_token" \
     -H "Content-Type: application/json" \
     -d '{
       "customer": {
         "email": "newcustomer@example.com",
         "firstname": "John",
         "lastname": "Doe",
         "website_id": 1
       },
       "password": "SecurePassword123"
     }'

Gestione degli Ordini

Recuperare gli ordini con criteri di ricerca:

curl -X GET "https://your-magento-store.com/rest/V1/orders?searchCriteria[filterGroups][0][filters][0][field]=status&searchCriteria[filterGroups][0][filters][0][value]=complete" \
     -H "Authorization: Bearer your_token" \
     -H "Content-Type: application/json"

Gestione del Carrello e Checkout

Creare un Carrello

Per creare un nuovo carrello per un cliente:

curl -X POST "https://your-magento-store.com/rest/V1/customers/123/carts" \
     -H "Authorization: Bearer your_token" \
     -H "Content-Type: application/json"

Aggiungere Prodotti al Carrello

curl -X POST "https://your-magento-store.com/rest/V1/carts/mine/items" \
     -H "Authorization: Bearer customer_token" \
     -H "Content-Type: application/json" \
     -d '{
       "cartItem": {
         "sku": "test-product-001",
         "qty": 2,
         "quote_id": "cart_id"
       }
     }'

Implementazione in PHP

Ecco un esempio di classe PHP per interagire con le Magento API:

baseUrl = rtrim($baseUrl, '/');
        $this->token = $this->getAdminToken($username, $password);
    }
    
    private function getAdminToken($username, $password)
    {
        $url = $this->baseUrl . '/rest/V1/integration/admin/token';
        $data = json_encode([
            'username' => $username,
            'password' => $password
        ]);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
    
    public function getProducts($searchCriteria = [])
    {
        $url = $this->baseUrl . '/rest/V1/products';
        if (!empty($searchCriteria)) {
            $url .= '?' . http_build_query($searchCriteria);
        }
        
        return $this->makeRequest('GET', $url);
    }
    
    public function createProduct($productData)
    {
        $url = $this->baseUrl . '/rest/V1/products';
        return $this->makeRequest('POST', $url, $productData);
    }
    
    private function makeRequest($method, $url, $data = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->token,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return [
            'status_code' => $httpCode,
            'data' => json_decode($response, true)
        ];
    }
}

Gestione degli Errori e Best Practices

Codici di Risposta HTTP

Le API di Magento utilizzano i codici di stato HTTP standard:

Codice Significato Descrizione
200 OK Richiesta completata con successo
201 Created Risorsa creata con successo
400 Bad Request Richiesta malformata o parametri non validi
401 Unauthorized Token di autenticazione non valido o scaduto
404 Not Found Risorsa non trovata
500 Internal Server Error Errore interno del server

Best Practices per l'Utilizzo delle API

  • Rate Limiting: Implementa meccanismi di throttling per evitare di sovraccaricare il server
  • Caching: Utilizza strategie di caching per ridurre il numero di chiamate API
  • Error Handling: Implementa una gestione robusta degli errori con retry logic
  • Pagination: Utilizza sempre la paginazione per dataset di grandi dimensioni
  • Filtering: Applica filtri appropriati per ridurre il payload delle risposte
  • Token Management: Implementa un sistema di refresh automatico dei token

Esempi Avanzati e Casi d'Uso

Sincronizzazione Inventario

Esempio di script per aggiornare l'inventario in batch:

 $quantity) {
        $stockData = [
            'stockItem' => [
                'qty' => $quantity,
                'is_in_stock' => $quantity > 0
            ]
        ];
        
        $response = $apiClient->makeRequest(
            'PUT', 
            "/rest/V1/products/{$sku}/stockItems/1", 
            $stockData
        );
        
        if ($response['status_code'] !== 200) {