Skip to content

Framework API

  • Service contracts exist to improve upgrades, decouple modules and formalise customisations
  • They exist in the form of interfaces implemented by classes
  • They allow an interface to stay the same while changing the implementation
  • Developers should rely only on classes' public methods

API Types

  • Data APIs
    • Provice access to modules' entity data through CRUD methods
    • Found in the module's Api/Data folder
  • Operational APIs
    • Provides both entity data and allows for actions and operations
    • Found in the module's Api folder
  • Repositories are the API equivalent to collections
  • Business Logic API provides actual business operations
  • The Framework API provides the interfaces and class implementations
  • (Model)Repository implements \Magento\Catalog\Api\ProductRespositoryInterface
  • Respository interfaces may extend Framework\Api\SearchCriteria and implement ::getList($criteria)

AbstractSimpleObject

  • Similar to Magento 1's Varien_Object
  • Has a data property, but no public magic getters or setters
  • Provides
    • An array $data constructor parameter and $data property
    • _get($key)
    • setData($key, $value)
    • __toArray()

SimpleBuilderInterface

  • Defines two methods
    • create()
    • getData()
  • AbstractSimpleObjectBuilder implements this by instantiating the object with the $data

AbstractServiceCollection

  • Service Collections are collections that get items from respositories rather than the ORM
  • Allows for converting filters and sorts into a SearchCriteria instance
  • Admin Grids often use Service Collections as a data source
  • Provides:
    • __construct(EntityFactoryInterface, FilterBuilder, SearchCriteriaBuilder, SortOrderBuilder)
    • addFieldToFilter($field, $condition)
    • getSearchCriteria()
    • createFilterData($field, $condition)

Repositories

  • Extend Magento\Framework\SearchCriteria
  • Exist to provide access to data sources
  • Allows the sourcing to be decoupled from data sources
  • Are services, so can be relied upon to be stable, where collections can not
  • Deal with data objects rather than models
  • Use SearchCriteria for filtering
  • Have a getList() method, expecting Magento\Framework\SearchCriteriaInterface

Magento\Customer\Api\CustomerRepositoryInterface example

  • Provides
    • save(\Magento\Customer\Api\Data\CustomerInterface $customer, $passwordHash)
    • get($email, $websiteId)
    • getById($customerId)
    • getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
    • delete(\Magento\Customer\Api\Data\CustomerInterface $customer)
    • deleteById($customerId)

SearchCriteria

  • Filters are added using $this->searchCriteriaBuilder->addFilters() calls followed by a create() call
  • SearchCriteriaInterface defines:
    • getFilterGroups()
    • setFilterGroups(array $filterGroups = null)
    • getSortOrders()
    • setSortOrders(array $sortOrders = null)
    • getPageSize()
    • setPageSize($pageSize)
    • getCurrentPage()
    • setCurrentPage($currentPage)

Architecture

  • SearchCriteriaBuilder
    • Extends AbstractSimpleObjectBuilder
    • create() creates
      • SearchCriteria
        • Extends AbstractSimpleObject
        • Implements SearchCriteriaInterface
        • Uses Search\FilterGroup
          • Uses Filter

Filter object

  • Extends AbstractSimpleObject
  • Adds methods to get/set the $data field
    • get/setField()
    • get/setValue()
    • get/setConditionType()

Builder Relationships

  • Filters
    • FilterGroup extends AbstractSimpleObject
    • FilterGroupBuilder extends AbstractSimpleObjectBuilder
    • Filters are set using FilterGroupBuilder::setFilters()
    • FilterGroupBuilder::create() instantiates the FilterGroups
  • SortOrders
    • SortOrder extends AbstractSimpleObject
    • SortOrderBuilder extends AbstractSimpleObjectBuilder
    • SortOrderBuilder creates the SortOrders based on setField() and setDirection()

SearchResultsInterface

  • Is the base interface returned by repositories' getList() methods
  • Provides
    • getItems()
    • setItems()
    • getSearchCritera()
    • setSearchCriteria(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
    • getTotalCount()
    • setTotalCount($totalCount)
  • Extends AbstractSimpleObject

Business Logic API

  • Is responsible for all logic not contained in Repositories or the Data API
  • Is responsible for basically all the actions a module can take
  • Example is Magento\Customer\Api\AccountManagementInterface
    • Provides validate(), authenticate(), resendConfirmation()
    • Implemented by Magento\Customer\Model\AccountManagement

Data API

  • Simplifies the SOAP API
  • Defines an internal API for accessing the Data Models
    • Defines the getters and setters for fields
  • Should implement the API interface rather than plain data models
  • Can be implemented using one of two methods
    • Create specific data objects that only contain data, with getters/setters. This is the preferred approach.
    • Use normal models that implement Data API interfaces, but also contain business logic

Extensible Objects and Extension Attributes

Extensible Objects

  • Should extend Magento\Framework\Api\AbstractExtensibleObject
    • Implements Magento\Framework\Api\CustomAttributesDataInterface
      • Defines
        • const CUSTOM_ATTRIBUTES
        • getCustomAttribute($attributeCode)
        • setCustomAttribute($attributeCode, $attributeValue)
        • getCustomAttributes()
        • setCustomAttributes(array $attributes)
      • Extends Magento\Framework\Api\ExtensibleDataInterface
        • Defines
          • const EXTENSION_ATTRIBUTES_KEY
  • Can call get- and setExtensionAttributes()
  • Api Data model interface defines attributes as constants
  • Data model implements the getters and setters

  • AbstractExtensibleObject accepts a constructor argument of ExtensionAttributesFactory or AttributeValueFactory, added in DI

  • Customer Example
    • Customer\Api\Data\CustomerInterface defines attributes as constants, and defines the getters and setters
    • Customer\Model\Data\Customer provides the getters and setters

Configuration

extension_attributes.xml:

1
2
3
4
5
6
7
/config/extension_attributes/
                             @for -- Path\To\Api\Data\Interface
                             attribute/
                                       @code
                                       @type
                                       resources/
                                                 @ref

Metadata Objects

  • Metadata objects are used to obtain a list of attributes
  • DefaultMetadataService implements MetadataServiceInterface
    • Implements the public function getCustomAttributes($dataObjectClassName = null)
  • AttributeMetadata implements MetadataServiceInterface
  • MetadataObjectInterface defines get/setAttributeCode()

Customer Module Example

  • Magento\Customer\Model\Data\AttributeMetadata implements AttributeMetadataInterface
  • The Interface provides constants fpr the attribute metata keys such as attribute_code, frontend_input etc
  • The concretion extends AbstractSimpleObject and implements the getters for the Interface's constants

Web API

  • Exposes the module's Service Contract API through the Web API
  • Extends the Magento 1 API
  • Respositories and APIs can be made accessible through Web APIs
  • REST APIs define methods in webapi.xml
  • Has Areas for webapi_rest and webapi_soap, with their own di.xml files
  • API Calls are processed:
    1. A URL is called
    2. webapi.xml maps verbs and URLs to Service Class Interfaces and Methods
    3. webapi.xml also defines the ACL groups
    4. webapi_rest|soap/di.xml defines concretions for the Interfaces
    5. The class/method is called

Configuration

webapi.xml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
/routes/
        route/
              @url
              @method -- GET or POST
              service/
                      @class -- \Path\To\Api\RepositoryInterface
                      @method -- class method to call
                      resources/
                                resource/
                                         @ref -- for ACL

Authentication

  • ACLs exist as self, anonynmous and a Magento ACL resource
  • Can be authenticated using OAuth for SOAP, tokens for REST or Sessions

SOAP

  • Tokens are created in the Admin at System > Integration
  • SOAP Wsdls are automatically generated based on Service Interfaces
    • Accessible at /soap?wdsl&services=ModuleInterfaceV1,Module2InterfaceV1
    • CustomerRespoitoryInterface::getList() would be specified as customerCustomerRepositoryV1getList

REST

  • Token requests look like /index.php/rest/V1/integration/admin/token, submitting username and password
  • API calls index.php/rest/V1/resource/id with a header Authorization:Bearer(_TOKEN_)