Magento 2 创建 API意味着帮助在线零售商生成供自己使用的应用程序编程接口。API 是一组用于设计软件应用程序的例程、协议和其他工具。因此,如果您从其他网站请求任何程序或服务,API 是连接数据的必需元素。通过在 Magento 2 中创建 API,您可以轻松获得成功启动程序的所有构建块。

Magento 2 中的 API 是什么?

API 代表应用程序编程接口,允许您从应用程序访问数据。API可以作为程序员和应用程序之间的中间人来调用。当程序员通过中间人发出请求时,如果请求被批准,正确的数据就会被返回。

作为基于 Magento 2 平台的电子商务商店,您应该关注两种架构类型的 Web API:REST(表述性状态传输)和SOAP(简单对象访问协议)。然而,在官方文档中,它们只附带原始的curl请求,没有任何示例。为了有效地连接和使用Magento 2 API,本主题将向您具体展示 PHP 示例。

片段API

文件:etc/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 method="GET" url="/V1/example-helloworld/post">
		<service class="Example\HelloWorld\Api\PostManagementInterface" method="getPost"/>
		<resources>
			<resource ref="anonymous"/>
		</resources>
	</route>
</routes>

文件:etc/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<preference for="Example\HelloWorld\Api\PostManagementInterface" type="Example\HelloWorld\Model\PostManagement"/>
</config>

文件:Model/PostManagement.php

<?php 
namespace Example\HelloWorld\Model;
 
 
class PostManagement {

	/**
	 * {@inheritdoc}
	 */
	public function getPost($param)
	{
		return 'api GET return the $param ' . $param;
	}
}

文件:Api/PostManagementInterface.php

<?php 
namespace Example\HelloWorld\Api;
 
 
interface PostManagementInterface {


	/**
	 * GET for Post api
	 * @param string $param
	 * @return string
	 */
	
	public function getPost($param);
}

如果您想确保该过程顺利且成功,最好考虑 Magento API 集成服务。您将节省大量时间和精力,同时专注于其他重要的业务方面。

通过使用 我们 的 Magento API 集成服务,您可以:

  • 将您的商店与其他第三方平台连接以简化流程
  • 通过一个仪表板执行各种任务并共享数据
  • 消除手动和繁琐的任务
  • 改善客户体验