Magento 2使用示例创建API – 代码段

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

为了更好地支持Magento 2模块开发,Mageplaza团队尝试在Magento 2模块开发系列的 hello world模块中构建API测试器。http://<magento_host>/swagger

表内容

  • 什么是API?
  • 片段

Magento 2中的API是什么?

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

作为基于Magento 2平台的电子商务商店,您应该看两种架构类型的Web API:REST(代表性状态转移)和SOAP(简单对象访问协议)。但是,在官方文档中,他们只提供原始卷曲请求而没有任何示例。为了有效地连接和使用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/mageplaza-helloworld/post">
		<service class="Mageplaza\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="Mageplaza\HelloWorld\Api\PostManagementInterface" type="Mageplaza\HelloWorld\Model\PostManagement"/>
</config>

文件: Model/PostManagement.php

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

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

文件: Api/PostManagementInterface.php

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


	/**
	 * GET for Post api
	 * @param string $param
	 * @return string
	 */
	
	public function getPost($param);
}
赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论