Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 42 ยท Projects

Project: A REST Integration Endpoint

Build a custom Magento REST endpoint: a service contract, webapi.xml routes, ACL resources, validation and error handling, with a runnable dispatcher stand-in to test the ideas.

External systems such as a warehouse, a shipping partner or a mobile app often need to talk to your store over HTTP. Magento's REST API lets you publish your own endpoints, and the framework does a lot of the work for you: it turns JSON into PHP objects, checks permissions and converts exceptions into HTTP status codes. What you provide is a service contract (PHP interfaces), a webapi.xml file that connects URLs to those interfaces, and an acl.xml that names the permissions.

In this project you build a small fulfillment status API. A partner can POST a status (such as shipped, with a tracking number) for an order and GET the current status. You will cover routes, ACL, validation and error handling. Magento cannot run on this site, so the real PHP and XML are read-only; runnable stand-ins in plain PHP imitate the dispatcher so you can try requests and see status codes. The stand-in is not Magento's Webapi framework, and each section says which is which.

What you will build

Request Permission Result
POST /V1/acme/fulfillments Acme_Fulfillment::fulfillment_write Saves a status, returns it
GET /V1/acme/fulfillments/:incrementId Acme_Fulfillment::fulfillment_read Returns the status, or 404
flowchart LR
    C["Partner<br/>Bearer token"] --> W["Webapi framework"]
    W --> A["ACL check<br/>from webapi.xml resource"]
    A --> D["JSON to data object<br/>(from interface types)"]
    D --> S["Repository method<br/>validates and saves"]
    S --> R["Data object to JSON"]
    S -->|"exception"| X["HTTP status<br/>and error message"]

Webapi sits around your code: it authorizes, converts data and maps exceptions. Your repository holds the business rules.

Step 1: the service contract

Webapi works from interfaces, not controllers. This is the same pattern from Service Contracts and Repositories. A data interface describes the JSON body, and a repository interface describes the operations.

PHP
<?php
declare(strict_types=1);

namespace Acme\Fulfillment\Api\Data;

interface FulfillmentInterface
{
    /**
     * @return string
     */
    public function getIncrementId(): string;

    /**
     * @param string $incrementId
     * @return $this
     */
    public function setIncrementId(string $incrementId): static;

    /**
     * @return string
     */
    public function getStatus(): string;

    /**
     * @param string $status
     * @return $this
     */
    public function setStatus(string $status): static;

    /**
     * @return string|null
     */
    public function getTrackingNumber(): ?string;

    /**
     * @param string|null $trackingNumber
     * @return $this
     */
    public function setTrackingNumber(?string $trackingNumber): static;
}
PHP
<?php
declare(strict_types=1);

namespace Acme\Fulfillment\Api;

use Acme\Fulfillment\Api\Data\FulfillmentInterface;

interface FulfillmentRepositoryInterface
{
    /**
     * Save the fulfillment status of an order.
     *
     * @param \Acme\Fulfillment\Api\Data\FulfillmentInterface $fulfillment
     * @return \Acme\Fulfillment\Api\Data\FulfillmentInterface
     * @throws \Magento\Framework\Exception\InputException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function save(FulfillmentInterface $fulfillment): FulfillmentInterface;

    /**
     * Get the fulfillment status of an order.
     *
     * @param string $incrementId
     * @return \Acme\Fulfillment\Api\Data\FulfillmentInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getByIncrementId(string $incrementId): FulfillmentInterface;
}

The docblocks are not decoration. Webapi reads the @param and @return annotations to learn the types of the JSON fields, so they must use fully qualified class names and be accurate. Methods named getX/setX become the JSON property x in snake case, so getTrackingNumber() appears as tracking_number. The @throws lines document what callers can expect.

You must also connect the interfaces to implementation classes with a preference in etc/di.xml (see Preferences and Interfaces in di.xml):

XML
<preference for="Acme\Fulfillment\Api\FulfillmentRepositoryInterface"
            type="Acme\Fulfillment\Model\FulfillmentRepository"/>
<preference for="Acme\Fulfillment\Api\Data\FulfillmentInterface"
            type="Acme\Fulfillment\Model\Fulfillment"/>

Step 2: webapi.xml and ACL

etc/webapi.xml maps URLs to service methods and names the permission each one needs:

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/fulfillments" method="POST">
        <service class="Acme\Fulfillment\Api\FulfillmentRepositoryInterface" method="save"/>
        <resources>
            <resource ref="Acme_Fulfillment::fulfillment_write"/>
        </resources>
    </route>
    <route url="/V1/acme/fulfillments/:incrementId" method="GET">
        <service class="Acme\Fulfillment\Api\FulfillmentRepositoryInterface" method="getByIncrementId"/>
        <resources>
            <resource ref="Acme_Fulfillment::fulfillment_read"/>
        </resources>
    </route>
</routes>

The :incrementId part of the URL is bound to the method parameter with the same name. For the POST, the JSON body is converted into the $fulfillment argument, and the body is wrapped in a key named after the parameter:

JSON
{
  "fulfillment": {
    "increment_id": "000000101",
    "status": "shipped",
    "tracking_number": "TRK-5521"
  }
}

The wrapper key is a classic stumbling block for newcomers: the partner sends the parameter name, not a bare object. Document it in your API description.

Resources refer to ACL entries. etc/acl.xml defines them under the admin tree (this is the same ACL you use for Admin Controllers, Menus and ACL):

XML
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Acme_Fulfillment::fulfillment" title="Fulfillment API" sortOrder="200">
                    <resource id="Acme_Fulfillment::fulfillment_read" title="Read fulfillment status" sortOrder="10"/>
                    <resource id="Acme_Fulfillment::fulfillment_write" title="Update fulfillment status" sortOrder="20"/>
                </resource>
            </resource>
        </resources>
    </acl>
</config>

Create an integration in the admin (System, Extensions, Integrations), tick only the resources the partner needs, and activate it to get an access token. The partner sends Authorization: Bearer <token>. Give read-only partners only the read permission: least privilege is the whole point of splitting the resources. Alternatives are anonymous (no authentication at all, rarely right) and self (a signed-in customer's own data). Never use anonymous for anything that changes data.

Step 3: the repository, with validation and errors

The repository is where the rules live. Webapi converts exceptions to HTTP responses, so the right exception class gives the partner the right status. The usual mapping: NoSuchEntityException becomes 404, InputException and other LocalizedException subclasses become 400, authorization problems become 401, and unexpected errors become 500 with a generic message. Check the exact behavior in your version when you need precision.

PHP
<?php
declare(strict_types=1);

namespace Acme\Fulfillment\Model;

use Acme\Fulfillment\Api\Data\FulfillmentInterface;
use Acme\Fulfillment\Api\FulfillmentRepositoryInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Api\OrderRepositoryInterface;

class FulfillmentRepository implements FulfillmentRepositoryInterface
{
    private const STATUSES = ['processing', 'shipped', 'delivered'];

    public function __construct(
        private readonly FulfillmentResource $resource,
        private readonly OrderLookup $orders
    ) {
    }

    public function save(FulfillmentInterface $fulfillment): FulfillmentInterface
    {
        $exception = new InputException();

        if (!in_array($fulfillment->getStatus(), self::STATUSES, true)) {
            $exception->addError(__('Invalid status "%1".', $fulfillment->getStatus()));
        }
        if ($fulfillment->getStatus() === 'shipped' && !$fulfillment->getTrackingNumber()) {
            $exception->addError(__('A tracking number is required when the status is "shipped".'));
        }
        if ($exception->wasErrorAdded()) {
            throw $exception;
        }

        if (!$this->orders->exists($fulfillment->getIncrementId())) {
            throw NoSuchEntityException::singleField('incrementId', $fulfillment->getIncrementId());
        }

        $this->resource->saveFor($fulfillment);

        return $fulfillment;
    }

    public function getByIncrementId(string $incrementId): FulfillmentInterface
    {
        $fulfillment = $this->resource->findByIncrementId($incrementId);
        if ($fulfillment === null) {
            throw new NoSuchEntityException(__('No fulfillment status for order "%1".', $incrementId));
        }

        return $fulfillment;
    }
}

FulfillmentResource and OrderLookup are your own classes (an order lookup would use the order repository from Magento Sales). Four habits make the API pleasant:

  • Validate everything, not just the first problem. InputException can collect several errors so the partner fixes them in one round trip.
  • Use placeholders (%1) in __() messages instead of gluing user input into the string. Magento fills the placeholder when it builds the response.
  • Never leak internals. Do not return stack traces or SQL errors; unexpected exceptions should surface as a generic server error and be logged.
  • Check the order exists before writing, so a typo in the increment id is a 404 and not stray data.

Step 4: a dispatcher stand-in

The first stand-in is a mini Webapi: a route table, a token with permissions, and a dispatcher that calls a repository. It handles authentication (401), authorization (403 here for simplicity), unknown routes (404) and a small JSON-to-object step. It does not use Magento classes, and real Webapi differs in many details; the point is to see the flow.

PHP A route-to-service dispatcher with ACL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The table of results shows what the ACL achieves: a reader token can fetch data but cannot change it, and each failure produces a distinct status. In real Magento, a token without permission usually gets a 401 whose message says the consumer is not authorized for that resource; check the behavior in your version if clients depend on exact codes.

Step 5: validation and error mapping in a stand-in

The second stand-in focuses on the repository: collecting all validation errors at once, mapping exceptions to statuses, and hiding unexpected errors behind a generic message.

PHP Collecting validation errors and mapping exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Every case picks its own status code, and the unexpected failure never exposes the internal message. Real Magento does this mapping for you based on exception classes; here it is spelled out so you can see the logic.

Testing and documenting the endpoint

With a real store, call the endpoint with any HTTP client, for example curl -X POST -H "Authorization: Bearer <token>" -H "Content-Type: application/json" -d '{...}' https://shop.example/rest/V1/acme/fulfillments. Magento also publishes a Swagger description of all endpoints under /swagger (in developer mode and when enabled), generated from your docblocks, which is another reason to keep them correct. See Testing Magento Code for API-functional tests.

Checklist before you ship an endpoint:

  • Every route names a specific ACL resource; none is anonymous unless it is meant to be public.
  • Write routes validate all input and use POST, PUT or DELETE, never GET.
  • Response types are data interfaces, not raw arrays, so the shape is documented.
  • Errors use typed exceptions with translatable messages and placeholders.
  • Security basics from Performance and Security are applied: prepared statements and no sensitive data in logs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Webapi learn the types of the JSON fields in a request body?

    Webapi reads the docblock types of service and data interfaces, so they must be accurate and fully qualified.
  2. 2. What does a route's <resource ref="..."/> element control?

    The ref points to an ACL resource from acl.xml. Integration tokens only work on routes whose resources they were granted.
  3. 3. A partner asks for an order that does not exist. Which exception gives a 404?

    NoSuchEntityException is the standard way to report a missing entity, and Webapi maps it to a not-found response.
  4. 4. Why does the repository collect several errors in one InputException?

    Returning all validation problems at once avoids a frustrating fix-one-resend loop.

Summary

  • A custom endpoint is a service contract (interfaces with accurate docblocks), a di.xml preference, webapi.xml routes and acl.xml resources.
  • The body of a POST is wrapped in a key named after the method parameter; URL placeholders bind to parameters by name.
  • Create an integration with only the needed resources; never expose data-changing routes as anonymous.
  • Validate fully in the repository and throw typed exceptions with placeholder messages: missing entities become 404, bad input 400, surprises 500 without internals.
  • Test with a real HTTP client and API-functional tests; keep the interface docblocks correct because they generate the API description.

Time to practice what you have learned across the whole track in Practice Exercises with Solutions.