No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace

Working with REST API in OpenCart 4

Complete guide to OpenCart 4 REST API: authentication, endpoints, request examples, and creating custom APIs.

15 min read
3,946
5
1
7
Working with REST API in OpenCart 4

OpenCart 4 has a built-in REST API that allows you to integrate the store with external systems: mobile apps, CRM, ERP, and other services.

API Setup

To start working with the API, you need to:

  1. Enable API in admin panel: System → Users → API
  2. Create an API user
  3. Generate API key
  4. Configure allowed IPs (optional)

Authentication

OpenCart 4 uses token-based authentication:

// Getting token
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'https://your-store.com/index.php?route=api/account/login',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'username' => 'api_user',
        'key' => 'your_api_key'
    ]
]);

$response = curl_exec($curl);
$data = json_decode($response, true);
$token = $data['api_token'];
Tip: Store the token and use it for subsequent requests. The token has a limited lifetime.

Main Endpoints

Products

// Get product list
GET /index.php?route=api/product&api_token={token}

// Get single product
GET /index.php?route=api/product&api_token={token}&product_id=123

// Search products
GET /index.php?route=api/product&api_token={token}&search=laptop

Cart

// Add product to cart
POST /index.php?route=api/cart/add&api_token={token}
{
    "product_id": 123,
    "quantity": 2,
    "option": {
        "226": "red"
    }
}

// Get cart contents
GET /index.php?route=api/cart/products&api_token={token}

// Remove from cart
POST /index.php?route=api/cart/remove&api_token={token}
{
    "key": "cart_item_key"
}

Orders

// Create order
POST /index.php?route=api/order/add&api_token={token}
{
    "customer_id": 1,
    "payment_address": {...},
    "shipping_address": {...},
    "payment_method": "cod",
    "shipping_method": "flat.flat"
}

// Order history
GET /index.php?route=api/order/history&api_token={token}&order_id=100

API is a contract between systems. Document all endpoints and version your API for backward compatibility.

— Best Practice

Creating Custom API Endpoint

<?php
// catalog/controller/api/custom.php
namespace Opencart\Catalog\Controller\Api;

class Custom extends \Opencart\System\Engine\Controller {
    public function index(): void {
        $this->load->language('api/custom');

        $json = [];

        if (!isset($this->session->data['api_id'])) {
            $json['error'] = 'Unauthorized';
        } else {
            // Your logic
            $json['success'] = true;
            $json['data'] = [
                'message' => 'Custom API works!'
            ];
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

Error Handling

// Standard response structure
{
    "success": true,
    "data": {...}
}

// Error
{
    "error": "Product not found",
    "error_code": 404
}
Security: Always validate input data, use HTTPS, and implement rate limiting for the API.

Example: Mobile App

// JavaScript/React Native example
const API_URL = 'https://your-store.com/index.php';
let apiToken = null;

async function login() {
    const response = await fetch(`${API_URL}?route=api/account/login`, {
        method: 'POST',
        body: JSON.stringify({
            username: 'api_user',
            key: 'api_key'
        })
    });
    const data = await response.json();
    apiToken = data.api_token;
}

async function getProducts() {
    const response = await fetch(
        `${API_URL}?route=api/product&api_token=${apiToken}`
    );
    return response.json();
}

Conclusion

REST API opens many possibilities for integrating OpenCart with other systems. Start by learning the built-in endpoints, then create your own for your business's specific needs.

DEV Тестовий

DEV Тестовий

Привіт! Я досвідчений розробник з OpenCart екосистеми з понад 10 роками практики. Технічний стек включає PHP (core мова для OpenCart), MySQL/MariaDB для баз даних, JavaScript/jQuery для фронтенду, HTML5/CSS3/Bootstrap для верстки. Маю глибокий досвід роботи з архітектурою OpenCart (MVC, Event System, OCMOD), інтеграцією платіжних систем та API, оптимізацією продуктивності магазинів. Окрім розробки, займаюся серверним адмініструванням — Linux (Ubuntu/Debian), Apache/Nginx, налаштування VPS/Dedicated серверів, DNS менеджмент, SSL сертифікати, email. Обслуговую понад 5000 інтернет-магазинів по всьому світу, надаючи комплексні рішення від розробки до технічної підтримки.

articles
12
views
53,922
likes
63
followers
3

Related Posts

Email Marketing for E-commerce Marketing

Email Marketing for E-commerce

How to build an effective email strategy for an online store: automation, segmentation, and best practices.

Email Marketing E-commerce Conversion
6,605 6 19 min
15 Jan 2026

Comments (7)

Replying to

Please log in to leave a comment

Log In
a
What about versioning the API endpoints?
m
Is there a way to use GraphQL instead of REST?
o
Як обмежити кількість запитів до API?
o
Чи є готові SDK для роботи з цим API?
o
Дякую! Нарешті розібрався з автентифікацією.
DEV Тестовий
Гарне питання! Розгляну в наступних статтях.

We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.