# Custom API endpoint in OpenCart: a JSON endpoint in a module for 3.0 and 4.1

> How to build a custom API endpoint in an OpenCart 3.0 and 4.1 module: controller, route, access key, JSON response with error codes, pagination and common pitfalls.

Джерело: https://opencartcode.com/en/wiki/dev-api/api-endpoint-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

A custom API endpoint in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) is a regular [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) in your module that returns JSON instead of an HTML page. The core does not provide a ready-made REST API for products or orders, so integrations with a CRM, accounting system, or mobile app almost always need such a controller. Below we cover where to place it, how to protect it with a key, how to return the response correctly, and the small details that break an endpoint on a live server.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## Why not the built-in API, and where should the controller go?

The core's built-in API only covers the order scenario: cart, customer, shipping and payment methods, confirmation, and status history. What it includes and how it authenticates is described in the article on the [built-in OpenCart API](https://opencartcode.com/en/wiki/dev-api/api-opencart). For a list of products, stock levels, or new orders for a period, you need your own controller.

Place it in the storefront (catalog), not in the admin. Admin controllers require an administrator session and `user_token`, so an external system cannot reach them without logging in. On the storefront, the controller is available at `index.php?route=...` without any prerequisites, and you handle the protection yourself.

|  | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| File | `catalog/controller/extension/module/mysync.php` | `extension/mysync/catalog/controller/module/mysync.php` |
| Class | `ControllerExtensionModuleMysync extends Controller` | `namespace Opencart\Catalog\Controller\Extension\Mysync\Module;`, class `Mysync` |
| Method route | `extension/module/mysync/products` | `extension/mysync/module/mysync.products` |
| When available | as soon as the file is in place | only if the extension package is installed |

The last row is important. In 4.1, the `startup/extension` controller registers namespaces only for packages listed in the `extension` table, that is, installed under "[Extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) → Extensions." Until the module is installed, the route returns a "not found" error. In 3.0, the file with `catalog/controller` is loaded directly by the route, even if nobody installed the module. Therefore, in 3.0 you must check the module status in code, otherwise the endpoint will keep working after the module is "removed" in the admin.

The method separator (slash in 3.0, dot in 4.1) is covered in detail in the article on [the route= parameter](https://opencartcode.com/en/wiki/dev-mvc/opencart-route), and the file layout of a package is described in [the anatomy of an extension](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-structure). The extension type is not critical: the endpoint can go into a module of type module, or into a separate package that outputs nothing on pages.

## What does a minimal endpoint look like?

The skeleton is the same in both versions: check that the module is enabled, verify the key, collect the data, and return JSON with the correct header and HTTP code.

Example: extension/mysync/catalog/controller/module/mysync.php (OpenCart 4.1)

```php
<?php
namespace Opencart\Catalog\Controller\Extension\Mysync\Module;

class Mysync extends \Opencart\System\Engine\Controller {
    public function products(): void {
        if (!$this->authorize()) {
            return;
        }

        $page  = max(1, $this->request->get('page', 'int'));
        $limit = min(500, max(1, $this->request->get('limit', 'int') ?: 100));

        $this->load->model('extension/mysync/module/mysync');

        $products = $this->model_extension_mysync_module_mysync->getProducts(($page - 1) * $limit, $limit);

        $this->json(200, [
            'page'     => $page,
            'limit'    => $limit,
            'products' => $products
        ]);
    }

    private function authorize(): bool {
        if (!$this->config->get('module_mysync_status')) {
            $this->json(404, ['error' => 'not_found']);

            return false;
        }

        $key = (string)($this->request->server['HTTP_X_API_KEY'] ?? '');

        if ($key === '' || !hash_equals((string)$this->config->get('module_mysync_key'), $key)) {
            $this->json(401, ['error' => 'unauthorized']);

            return false;
        }

        return true;
    }

    private function json(int $code, array $data): void {
        $protocol = $this->request->server['SERVER_PROTOCOL'] ?? 'HTTP/1.1';

        $this->response->addHeader($protocol . ' ' . $code);
        $this->response->addHeader('Content-Type: application/json; charset=utf-8');
        $this->response->setOutput(json_encode($data, JSON_UNESCAPED_UNICODE));
    }
}
```

The private methods `authorize()` and `json()` are not called by the route: the core dispatcher only calls public methods in both 3.0 and 4.1, and blocks names starting with `__`. The address of this endpoint is `index.php?route=extension/mysync/module/mysync.products&page=2`.

There are few differences in 3.0. The class is global (`class ControllerExtensionModuleMysync extends Controller`), without type declarations in signatures. The model is loaded as `$this->load->model('extension/module/mysync')` and is available as `$this->model_extension_module_mysync`. The `$this->request->get('page', 'int')` helper does not exist in 3.0: it appeared in Request 4.1. In 3.0, write `isset($this->request->get['page']) ? (int)$this->request->get['page'] : 1`.

Store the key and status as regular module settings with the `module_mysync_` prefix. The core loads store settings into `$this->config` at startup, so no separate query is needed. The admin form is built using the same rules as for any module; see [module settings and the setting table](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-setting).

## How do you protect the endpoint?

The storefront controller address is public, so access control is entirely your responsibility. The minimum set:

- **A long random key** from the module settings, compared with `hash_equals()` rather than `==`. You can generate it during installation, for example with `oc_token(64)` in 4.1 or `token(64)` in 3.0.
- **The key in a header, not in the URL.** GET parameters end up in web server access logs, proxies, and analytics. The `X-Api-Key` header is usually not written to them.
- **HTTPS only.** Check the request scheme, or at least store the endpoint address in the settings with https.
- **A separate key for writing.** If the endpoint also modifies data (prices, stock), give a read-only integration a different key.

Why `X-Api-Key` and not the standard `Authorization: Bearer`? On some hosts with Apache and PHP-FPM or CGI, the `Authorization` header is not passed to `$_SERVER` without an extra rule in `.htaccess`. A custom header `X-...` arrives as `HTTP_X_API_KEY` without any configuration. If a partner specifically requires Bearer, check both variants.

> In both branches, Request passes `htmlspecialchars` not only GET and POST, but also `$_SERVER` through the filter. For a key made of letters and digits this is invisible, but if the key contains `&`, quotes, or angle brackets, the value in `$this->request->server` will differ from what was sent. Generate keys from alphanumeric characters only.

For integrations with higher requirements, instead of a static key you can sign the request with HMAC and a timestamp, as `startup/api` does in 4.1: then an intercepted request cannot be replayed after a few minutes.

## How do you accept JSON in the request body?

If an external system sends `Content-Type: application/json`, PHP does not parse the body into `$_POST`. Because of this, `$this->request->post` is empty in both versions. Read the body yourself:

Example: a method that accepts JSON with stock changes (OpenCart 4.1)

```php
public function stock(): void {
    if (!$this->authorize()) {
        return;
    }

    if (($this->request->server['REQUEST_METHOD'] ?? '') !== 'POST') {
        $this->json(405, ['error' => 'method_not_allowed']);

        return;
    }

    $input = json_decode((string)file_get_contents('php://input'), true);

    if (!is_array($input) || empty($input['items']) || !is_array($input['items'])) {
        $this->json(422, ['error' => 'invalid_body']);

        return;
    }

    $this->load->model('extension/mysync/module/mysync');

    $updated = 0;

    foreach (array_slice($input['items'], 0, 1000) as $item) {
        if (isset($item['sku'], $item['quantity'])) {
            $updated += $this->model_extension_mysync_module_mysync->setQuantityBySku((string)$item['sku'], (int)$item['quantity']);
        }
    }

    $this->json(200, ['updated' => $updated]);
}
```

Data from `php://input` does not pass through `htmlspecialchars`, so it reaches the model "raw." This is good for accuracy (names with quotes are not corrupted), but every value must be cast to the right type and escaped for SQL just like form data. How to do this without injections is explained in the article on [safe SQL queries](https://opencartcode.com/en/wiki/dev-database/opencart-sql-queries). The package size limit (here 1000 items) protects against timeouts when a partner sends the entire warehouse in one request.

## Which model should you use for data?

The temptation is to call core models, for example `catalog/product` and its `getProducts()`. They suit the storefront, but often not integrations:

- they return only enabled products of the current store with an availability date in the past, while an accounting system usually needs all of them;
- prices are calculated for the [customer group](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#customer-group) from `config_customer_group_id`, that is, for a guest;
- in 3.0, `getProducts()` first selects ids and then makes a separate `getProduct()` for each one. On a page of 500 products, that is 500 extra queries.

For exports, write your own model method that selects exactly the needed columns in one query using `LIMIT`:

Example: a model method for exporting products (OpenCart 4.1)

```php
public function getProducts(int $start, int $limit): array {
    $query = $this->db->query("SELECT p.`product_id`, p.`model`, p.`sku`, p.`quantity`, p.`price`, p.`status`, pd.`name`
        FROM `" . DB_PREFIX . "product` p
        LEFT JOIN `" . DB_PREFIX . "product_description` pd ON (pd.`product_id` = p.`product_id` AND pd.`language_id` = '" . (int)$this->config->get('config_language_id') . "')
        ORDER BY p.`product_id`
        LIMIT " . (int)$start . "," . (int)$limit);

    return $query->rows;
}
```

For incremental synchronization (only changed items), add a filter on `p.date_modified` and return the time to continue from in the response. A large `OFFSET` over tens of thousands of products slows down, so for a full traversal a "cursor" by `product_id > останній` is better. There is an article on [slow queries](https://opencartcode.com/en/wiki/dev-database/slow-queries-opencart) about indexes for such queries.

## What breaks the endpoint on a live server?

### Maintenance mode

The `startup/maintenance` controller lets through only `api...` routes, and in 3.0 also `extension/payment...`. Your endpoint at `extension/module/...` or `extension/{код}/...` will receive the maintenance HTML page with code 503. The integration client must be able to handle 503 and retry the request later. You cannot name your route "under api": in 4.1, `startup/api` blocks all `api/...` except two built-in ones.

### PHP warnings in the response body

If error display is enabled in the settings, any warning is printed before the JSON, and the client receives an invalid response. The same problem is described in the article on [diagnosing payment callbacks](https://opencartcode.com/en/wiki/dev-flows/opencart-callback-not-updating-order-status). On a live site, turn off error display but keep logging enabled.

### Caching and compression

The response passes through `Response::output()`, so when compression is enabled (level set in the server settings), JSON is served as gzip if the client accepts it. This is usually a plus. However, page caching at the hosting or CDN level for `route=extension/...` addresses must be disabled: otherwise two different keys would receive the same cached response. Add the `Cache-Control: no-store` header.

### A session on every request

The core startup opens a session and sets a cookie even for a request from a partner server. With the `db` driver, this is a row in the `session` table for every call without a cookie. Sessions are cleaned up by the garbage collector, but if an integration makes thousands of requests per hour, the table grows noticeably. The client should keep the cookie between requests.

### CORS for browser clients

If the endpoint is called by JavaScript from another domain, add `Access-Control-Allow-Origin` with a specific domain and handle the `OPTIONS` request. Do not keep the secret key in browser code: for the frontend, create separate read-only endpoints for public data only. For how to return JSON for AJAX on your own site, see the article on [AJAX in OpenCart](https://opencartcode.com/en/wiki/dev-mvc/ajax-opencart).

## Summary

- An endpoint is a public method of a storefront controller in a module. In 3.0 the route is written with a slash; in 4.1 the method is separated by a dot.
- In 4.1 the route works only for an installed extension. In 3.0 the file is always available, so check the module status in code.
- Take the key from the module settings, pass it in the `X-Api-Key` header, and compare it with `hash_equals()`.
- Return JSON with `Content-Type` and the correct HTTP code: 401, 404, 405, 422, 200.
- Read the JSON body from `php://input`, cast values to types, and limit the package size.
- For exports, write a custom model with `LIMIT` instead of calling the storefront `getProducts()`.
- Prepare the client for 503 in maintenance mode, turn off error display, and disable response caching.

If there is no ready-made integration with your accounting system, look at how, for example, [OpenCart data exchange with BAS and other accounting systems](https://opencartcode.com/en/marketplace/product/integratsiia-opencart-z-bas-ta-oblikovymy-systemamy) is built. Other materials on data exchange are collected in the section ["API and integrations"](https://opencartcode.com/en/wiki/dev-api).

## FAQ

**Is it possible to get a clean URL like /api/products instead of index.php?route=...?**

Yes, with a rewrite rule in the web server that turns the path into route=... The core's seo_url table can't be used for this, because it is designed for pages with product, category and similar entity parameters.

**How do you version a custom API without breaking integrations?**

Add a version to the method name or a parameter, for example products_v2, and keep the old method until all clients have switched. Don't change the format of an existing response without warning.

**Can I call a custom endpoint from cron on the same server?**

Yes, but for background tasks in 4.1 the built-in core cron is more convenient, and in 3.0 a separate CLI script. That way the task doesn't depend on web server timeouts.

**How do you limit the number of requests from one client?**

The core has no such feature. The simplest option is to limit the rate at the web server or CDN level by endpoint address, or to keep a request counter per key in your own table.
