Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 42 ยท Admin, APIs and Backend Services

The REST API

Learn Magento's REST API: webapi.xml routes mapped to service contracts, authentication with tokens and integrations, custom endpoints and searchCriteria queries.

A modern shop rarely lives alone. The mobile app, the ERP, the warehouse system and a marketing tool all need to read products and create orders. Magento ships a REST API for this, and it is not a separate piece of code written by hand. The API is generated from the same PHP interfaces that your modules already use internally. You publish a method by adding one line of XML, and Magento handles URL matching, JSON conversion, authentication and permission checks.

In this lesson you will learn how webapi.xml maps URLs to service methods, how callers authenticate, how to build a custom endpoint, and how the searchCriteria query format works. The real Magento code is read-only here, because Magento cannot run on this site. The runnable examples are stand-ins: a tiny router that dispatches URLs to service classes and a parser for searchCriteria query strings. If service interfaces are new to you, read Service Contracts and Repositories first.

Routes are services

The idea behind the Magento API is the service contract. A module exposes a PHP interface, and the REST layer is only another way to call it. The mapping lives in etc/webapi.xml. This example publishes a read-only endpoint for a made-up badge repository (read-only code):

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-badges/:badgeId" method="GET">
        <service class="Acme\Badge\Api\BadgeRepositoryInterface" method="getById"/>
        <resources>
            <resource ref="Acme_Badge::badges"/>
        </resources>
    </route>
    <route url="/V1/acme-badges" method="POST">
        <service class="Acme\Badge\Api\BadgeRepositoryInterface" method="save"/>
        <resources>
            <resource ref="Acme_Badge::badge_save"/>
        </resources>
    </route>
</routes>

Four things to notice:

  • The url starts with a version, /V1/. Published URLs are a public contract. Never change the behavior of a V1 route; add V2 if you must break compatibility.
  • :badgeId is a URL parameter. Magento passes it to the method argument with the same name, $badgeId.
  • method is the HTTP verb. For POST and PUT the JSON body is converted into the method's arguments.
  • resources holds the ACL resource the caller needs. The special refs anonymous (no login at all) and self (a customer accessing their own data) exist too. Use anonymous very sparingly. The ACL ids are the same ones from Admin Controllers, Menus and ACL.

The full URL a client calls is https://shop.example/rest/V1/acme-badges/5. A store view code can be inserted after rest, as in /rest/default/V1/..., to read store-specific data.

The interface has to be documented

Magento reads the PHP docblocks of the interface to know the types of parameters and the return value, so they are not just comments here. They drive both the JSON conversion and the generated API documentation (read-only):

PHP
namespace Acme\Badge\Api;

interface BadgeRepositoryInterface
{
    /**
     * Get a badge by id.
     *
     * @param int $badgeId
     * @return \Acme\Badge\Api\Data\BadgeInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getById($badgeId);

    /**
     * Save a badge.
     *
     * @param \Acme\Badge\Api\Data\BadgeInterface $badge
     * @return \Acme\Badge\Api\Data\BadgeInterface
     */
    public function save(\Acme\Badge\Api\Data\BadgeInterface $badge);
}

Use fully qualified class names in @param and @return, and give the data interface getters and setters with @return types, since the converter walks them to build the JSON. If a type is missing or relative, the request fails with a type error at runtime. When the method throws NoSuchEntityException, the client gets a 404 with a JSON message instead of a stack trace, because Magento maps its exception classes to HTTP codes.

A dispatcher you can run

The stand-in below mimics the dispatcher's core: it holds a route table, matches the method and URL with :param placeholders, checks that the caller's token carries the needed resource, then calls the service method with arguments mapped by name. The "services" are plain classes. Errors become status codes and a JSON-shaped message.

PHP A route-to-service dispatcher

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 status codes tell the story. Anonymous calls are refused with 401, a valid token without the right resource gets 403, a missing entity returns 404, and only a token that holds badge_save can create a badge. The real framework also validates types, converts nested data into objects and supports PUT and DELETE, but the shape is the same: match, authorize, map arguments, call, convert.

sequenceDiagram
    participant C as Client
    participant W as Webapi router
    participant A as Authorization
    participant S as Service (repository)
    C->>W: GET /rest/V1/acme-badges/5 + Bearer token
    W->>A: token has Acme_Badge::badges?
    A-->>W: yes
    W->>S: getById(5)
    S-->>W: BadgeInterface
    W-->>C: 200 JSON

The REST layer matches the route, checks the ACL resource, then calls the service method and converts the result to JSON.

Authentication

Callers prove who they are in one of these ways:

  • Admin tokens. POST /rest/V1/integration/admin/token with a JSON body of username and password returns a token string. The client then sends Authorization: Bearer <token>. The token acts with that admin user's role. Tokens can expire, so clients must be ready to fetch a new one.
  • Customer tokens. POST /rest/V1/integration/customer/token with the customer's username (email) and password does the same for a shopper. Routes with resource ref="self" serve this caller, and the data returned is about that customer only.
  • Integrations. In the admin under System > Extensions > Integrations you create an integration, choose which resources it may use, and Magento issues OAuth credentials and an access token. This is the right choice for server-to-server connections such as an ERP, because it has its own named permissions and can be revoked without touching a person's account.
  • Anonymous. Routes marked anonymous need nothing, for example some read-only catalog data. The default for new routes should never be anonymous.

Always call the API over HTTPS. Never put tokens in URLs, because URLs end up in logs. Give integrations the narrowest set of resources they need, for the same reason a role in the admin should be narrow.

Searching with searchCriteria

Listing endpoints such as GET /V1/products or GET /V1/orders accept a query format called searchCriteria. It is the HTTP form of the same objects you use in PHP (see Collections, Filters and SearchCriteria). Filters in the same group are combined with OR, and different groups with AND. This read-only example finds enabled products whose name starts with "Tee":

TEXT
GET /rest/V1/products
  ?searchCriteria[filter_groups][0][filters][0][field]=name
  &searchCriteria[filter_groups][0][filters][0][value]=Tee%25
  &searchCriteria[filter_groups][0][filters][0][condition_type]=like
  &searchCriteria[filter_groups][1][filters][0][field]=status
  &searchCriteria[filter_groups][1][filters][0][value]=1
  &searchCriteria[filter_groups][1][filters][0][condition_type]=eq
  &searchCriteria[pageSize]=20
  &searchCriteria[currentPage]=1

Sorting uses searchCriteria[sortOrders][0][field]=price with a direction of ASC or DESC. Common condition types are eq, neq, like, in, gt, gteq, lt, lteq, from, to and null. The response contains items, search_criteria and total_count.

The stand-in below parses such a query array into groups and applies it to an in-memory list. PHP turns the bracketed query string into a nested array for us with parse_str, the same way the real framework receives it.

PHP Parse and apply searchCriteria

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 first group keeps names starting with "Tee", the second keeps status 1, and the result is sorted by price descending. "Tee Blue" has status 2, so it drops out and "Mug" does not match the name. Note the default condition: if you leave out condition_type, the filter uses eq.

Building a custom endpoint

The recipe for a custom endpoint in a real module is short:

  1. Write an API interface with complete docblocks and a data interface for the payload.
  2. Write the implementation class and add a preference for the interface in etc/di.xml (see Preferences and Interfaces in di.xml).
  3. Declare the route in etc/webapi.xml with a specific ACL resource.
  4. Declare that resource in etc/acl.xml.
  5. Clear the cache and call the endpoint with a token that has the resource.

Throw Magento exceptions (NoSuchEntityException, InputException, LocalizedException) from your service rather than generic ones, so clients get meaningful status codes. The end-to-end version of this recipe is built in Project: A REST Integration Endpoint.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In webapi.xml, what does a route's service element refer to?

    The REST layer is a thin mapping from URL and HTTP method to a method of a service interface, which is why the same logic can be used from PHP, REST and GraphQL.
  2. 2. A client calls a route with a valid token that lacks the route's ACL resource. What is the expected result?

    The caller is known (so not 401) but not permitted to use the resource.
  3. 3. In searchCriteria, how are filters inside one filter group combined, and how are separate groups combined?

    Put alternatives for the same field in one group (OR). Use separate groups for independent requirements (AND).
  4. 4. Why must service interface docblocks have fully qualified @param and @return types?

    The docblock types drive the conversion of request data and responses. Missing or wrong types cause errors when the endpoint is called.

Summary

  • etc/webapi.xml maps a versioned URL and HTTP method to a method of a service interface, and lists the ACL resource the caller needs.
  • URL parameters like :badgeId map to method arguments of the same name; the JSON body maps to the object parameter.
  • Docblock types on the interface drive conversion, so write them fully qualified.
  • Authenticate with admin or customer tokens, or create an integration for server-to-server access; use HTTPS and narrow resources.
  • 401 means unknown caller, 403 means not permitted, and Magento exceptions map to meaningful codes.
  • searchCriteria query parameters express filters (OR inside a group, AND between groups), sorting and paging.

Next: GraphQL in Magento