ARTICLE

Magento 2 Custom REST API Endpoints: webapi.xml, Service Contracts, Data Interfaces, and ACL Resources

Magento 2 Custom REST API Endpoints: webapi.xml, Service Contracts, Data Interfaces, and ACL Resources

A custom REST endpoint in Magento 2 is a PHP interface exposed through etc/webapi.xml. You write a service interface in Api/, a data interface in Api/Data/ for anything structured it accepts or returns, bind both to implementations in di.xml, then map a URL and HTTP method to the interface method and declare who may call it with a resource.

There is no controller. The web API framework reads your interface’s docblocks, builds the request parser and the response serializer from them, checks authorization, and calls your method. That design is why a missing @return breaks an endpoint and why the same interface can also be called from PHP. This guide builds one endpoint end to end and explains the rules the framework enforces.

The files you need

File Purpose
Api/DeliveryEstimateInterface.php Service interface: the methods you expose
Api/Data/EstimateInterface.php Data interface: the shape of the response object
Model/DeliveryEstimate.php Implementation of the service interface
Model/Data/Estimate.php Implementation of the data interface
etc/di.xml Preferences that bind interfaces to implementations
etc/webapi.xml Routes: URL, HTTP method, service method, resources
etc/acl.xml The permission resource, if the route is not public

Adobe’s custom REST API tutorial walks through the same set: module registration, ACL entries, and a route in etc/webapi.xml.

Step 1: the service interface

<?php
declare(strict_types=1);

namespace Acme\Delivery\Api;

interface DeliveryEstimateInterface
{
    /**
     * Estimate delivery for a SKU to a postcode.
     *
     * @param string $sku
     * @param string $postcode
     * @return \Acme\Delivery\Api\Data\EstimateInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function estimate(string $sku, string $postcode);
}

The docblock is not documentation here. It is configuration. Adobe’s guide to configuring services as web APIs sets the rules:

  • Every exposed method needs @param type $name for each argument and an @return type.
  • Object types must be fully qualified. Adobe is explicit that even inside the same namespace or with a use statement, the fully qualified name must be used or the web API throws an exception.
  • Arrays are written with [], for example string[] or \Acme\Delivery\Api\Data\EstimateInterface[].
  • Scalar types are limited to string, int, float, bool, and mixed.
  • Do not name an argument item. Adobe notes that item nodes are removed during SOAP request processing.

A plain @return array does not work. The framework treats array as a class name and fails. Use a typed array such as string[], or better, a data interface.

Step 2: the data interface

<?php
declare(strict_types=1);

namespace Acme\Delivery\Api\Data;

interface EstimateInterface
{
    /**
     * @return string
     */
    public function getSku();

    /**
     * @param string $sku
     * @return $this
     */
    public function setSku($sku);

    /**
     * @return string|null
     */
    public function getEarliestDate();

    /**
     * @param string|null $date
     * @return $this
     */
    public function setEarliestDate($date);

    /**
     * @return bool
     */
    public function getIsExpressAvailable();

    /**
     * @param bool $flag
     * @return $this
     */
    public function setIsExpressAvailable($flag);
}

The serializer walks the getters and converts each name to snake case. getEarliestDate() becomes earliest_date in the JSON, and getIsExpressAvailable() becomes is_express_available. On input the reverse happens through the setters.

Adobe’s service contract design patterns require data interfaces to live in Api/Data and service interfaces in the top level Api directory. One naming rule from that page saves a confusing bug: avoid underscores between letters and digits in field names (use default_shipping1, not default_shipping_1), because the camel case to snake case conversion cannot round trip them.

Why bother with a data interface when you could return a nested array? Three reasons. Associative arrays are serialized unpredictably, and keys can be lost. A typed interface appears in the generated schema, so the consumer gets a real contract. And extension attributes only work on data interfaces. Our guide to Magento 2 extension attributes shows how other modules add fields to your object without editing it.

Step 3: implement and bind

The implementation is ordinary PHP. Keep it thin and delegate to existing repositories where you can. Our article on repositories and SearchCriteriaBuilder covers the lookup side.

<!-- etc/di.xml -->
<preference for="Acme\Delivery\Api\DeliveryEstimateInterface"
            type="Acme\Delivery\Model\DeliveryEstimate"/>
<preference for="Acme\Delivery\Api\Data\EstimateInterface"
            type="Acme\Delivery\Model\Data\Estimate"/>

Both preferences are required. The first lets the framework instantiate your service. The second lets it build the data object when one appears in a request body.

Step 4: the route in webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/acme/delivery-estimate/:sku" method="GET">
        <service class="Acme\Delivery\Api\DeliveryEstimateInterface" method="estimate"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

How the request reaches your arguments:

  • URL placeholders with a colon prefix map to arguments of the same name. :sku fills $sku.
  • Query string values fill the remaining scalar arguments on GET, so ?postcode=11201 fills $postcode.
  • JSON body keys fill arguments on POST and PUT. The top level key is the argument name in camel case, and a data interface argument is a nested object with snake case fields.

Adobe requires the URL to begin with /V1 or another version integer. Version it from day one: when the contract has to change in a breaking way, add /V2 with a new interface and leave /V1 working for existing consumers.

The full URL includes the store code: /rest/default/V1/acme/delivery-estimate/ABC-123?postcode=11201. The store code sets the store context your code runs in, which matters for prices, stock, and scoped configuration. Use all only for admin style operations.

curl -s "https://example.com/rest/default/V1/acme/delivery-estimate/ABC-123?postcode=11201"

Step 5: who can call it

The <resource ref> decides authorization. There are three kinds.

ref value Who can call Token needed Use for
anonymous Anyone, including guests None Public read data such as estimates or store locators
self A logged in customer, for their own data Customer token Account data, the customer’s cart, their orders
An ACL resource such as Acme_Delivery::manage Admin users and integrations granted that resource Admin or integration token Back office operations, ERP and warehouse integrations

For an ACL resource, declare it in etc/acl.xml under Magento_Backend::admin. It then appears as a checkbox in admin role permissions and in the API tab of an integration, so access can be granted per consumer.

self routes must force the customer ID

A self route proves the caller is a logged in customer. It does not prove which customer’s data they are asking for. If your method takes $customerId and you leave it to the caller, any customer can pass someone else’s ID. The framework solves this with a forced parameter:

<route url="/V1/acme/delivery-preferences/mine" method="GET">
    <service class="Acme\Delivery\Api\PreferenceRepositoryInterface" method="getByCustomerId"/>
    <resources>
        <resource ref="self"/>
    </resources>
    <data>
        <parameter name="customerId" force="true">%customer_id%</parameter>
    </data>
</route>

%customer_id% is replaced with the ID from the token and overrides anything in the request. Adobe documents that you can register your own overriders through the paramOverriders argument of Magento\Webapi\Controller\Rest\ParamsOverrider for values such as a company ID.

Treat anonymous as the open internet

An anonymous route can be called by any script, any number of times. Before you publish one, ask what it costs to run and what it reveals. An endpoint that triggers a live carrier or ERP call on each request needs caching and rate limiting at the edge. One that confirms whether an email address has an account is an information leak.

What the framework will and will not accept as input

Adobe tightened this area in the APSB25-88 security release. The services guide now states that REST payloads are only used to construct simple types and Api\Data interfaces. Models, service classes, and other complex types are not instantiated from a request. A field that does not correspond to a setter is rejected with a message such as "fieldName" is not supported. Correct the field name and try again. on 2.4.7 and later.

The practical rule: every object in your method signature should be a data interface from an Api\Data namespace, with a setter for each field you accept.

Errors and HTTP status codes

Do not build error responses by hand. Throw the right exception and the framework sets the status.

Exception thrown HTTP status
NoSuchEntityException 404
InputException, LocalizedException, CouldNotSaveException 400
AuthorizationException, AuthenticationException 401
Magento\Framework\Webapi\Exception The code you pass to it
Any other \Exception or \Throwable 500 with a generic message in production mode

Messages on LocalizedException and its subclasses are sent to the caller, so write them for the consumer and never include internal detail. Unexpected exceptions are written to var/log/exception.log, so check there when a consumer reports a 500.

Checking your endpoint

  • Schema. /rest/all/schema?services=all returns the generated OpenAPI document, and /swagger renders it. If Swagger fails to load after you add a module, a docblock in one of your interfaces is missing a type. That single mistake breaks the document for every endpoint.
  • Caches. Routes are cached in the config cache type and reflection data in reflection. Clean both after editing webapi.xml or a docblock, and run setup:di:compile in production mode.
  • Tests. Cover the service class with unit tests and the route with an API functional test. Our article on automated testing for Magento 2 modules covers running them in CI.

You get an asynchronous version for free

Every POST, PUT, and DELETE route is also available with an async prefix, for example /rest/default/async/V1/.... The request is accepted, written to the message queue, and processed by a consumer, and the caller receives a bulk UUID to check status. That is the right choice for integrations pushing large volumes. It depends on queue consumers running, which our article on Adobe Commerce async and bulk APIs with RabbitMQ covers in detail.

REST or GraphQL for a Hyva storefront?

Both work. A Hyva component can call a REST endpoint with fetch() from Alpine.js as easily as it can post a GraphQL query. As a rule of thumb, use GraphQL for storefront reads where the client picks fields and results can be cached, and REST for system to system integration and simple action endpoints. If you are building for the storefront, the same service class can sit behind both a webapi.xml route and a resolver. Teams using our Hyva development services usually keep business logic in the service contract so either transport stays a thin wrapper.

How this compares to other platforms

The ability to add first class endpoints inside the application is specific to platforms you can extend at the code level. On Shopify and BigCommerce, custom endpoints live in a separate app or middleware service that calls the platform’s own APIs. Shopware allows custom routes inside plugins, with its own split between store and admin APIs. If an integration design assumes custom server side endpoints, confirm where they will run before choosing the platform.

Where Bemeir fits

Bemeir is a Brooklyn agency that builds and supports Magento and Adobe Commerce stores, including the ERP, CRM, and warehouse integrations that depend on well designed APIs. Custom service contracts and endpoints are a routine part of our Magento development services. Learn more about Bemeir or see our technology partners.

FAQ

How do I create a custom REST API in Magento 2?

Create a service interface in your module’s Api folder with typed docblocks, implement it, bind the interface to the implementation with a preference in etc/di.xml, and add a <route> in etc/webapi.xml that maps a URL and HTTP method to the interface method and lists the resource allowed to call it. Clean the cache and compile.

What is the difference between anonymous, self, and an ACL resource in webapi.xml?

anonymous routes are public and need no token. self routes need a customer token and are for the customer’s own data. An ACL resource such as Vendor_Module::resource restricts the route to admin users and integrations that have been granted that permission.

Why does my Magento 2 API return “Class array does not exist”?

A docblock uses array as a type. The web API framework needs a concrete type, so replace it with a typed array such as string[] or a fully qualified data interface with []. Check @param and @return on the service interface and on every getter of the data interfaces it uses.

Do I need a data interface, or can I return an array?

You can return typed arrays of scalars, but for anything structured use a data interface in Api/Data. It gives a stable snake case JSON shape, appears in the schema, supports extension attributes, and is the only kind of object the framework will construct from a request body.

Does a custom REST endpoint also work over SOAP and asynchronously?

Yes. The same webapi.xml route is exposed over SOAP, and POST, PUT, and DELETE routes are available under the async prefix, which queues the request for a message queue consumer.

Let us help you get started on a project with Magento 2 Custom REST API Endpoints: webapi.xml, Service Contracts, Data Interfaces, and ACL Resources and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.