Hi,

Welcome back to Magento Tutorial. We would like to introduce you a new lesson about API in Magento this week. Let’s discover it now!

The Magento API provides you with the ability to manage your eCommerce stores by providing calls for working with resources such as customers, categories, products, and sales orders. It also allows you to manage shopping carts and inventory.

  • API architecture in Magento
  • How to use available API function in Magento
  • How to declare and create a new API

1. API architecture in Magento

An HTTP request is made to a URL and Magento’s standard routing system sends that request to a controller action in the Mage_Api module. This controller action instantiates a Magento API server object, initializes that object with the API type (soap, XML-RPC, etc.), and then calls the server object’s run method.

The API server is responsible for handling the API request, and directly setting the output on the response object. There’s no layout XML here, no loadLayout/renderLayout methods need to be called.

This API object is a Magento model with the class alias api/server, making it a Mage_Api_Model_Serverobject. There’s also an intended architecture the server object uses to achieve its goals. That architecture can be described as follows

On initialization the API server object will, based on the passed in paramaters, examine the Magento configuration to determine which API adapter object and API handler object should be instantiated. A handler object is subservient to an adapter object. Upon having its run method called, the API server object calls therun method on the adapter object, making the adapter object ultimately responsible for fulfilling the API request.

The relationship between adapters and handlers can be tricky to understand, and reveals a few of the of the assumptions made by the team that worked on the Magento API. Defined without context, that relationships can be described with the following

The adapter object is responsible for including and instantiating the API libraries and objects, while the handler is responsible for translating an API function call to the correct Magento API resource class and method

To understand this definition, you’ll need a little background on the history of SOAP and XML-RPC style APIs

2. How to use API in Magento

The Magento SOAP v1 API provides you with the ability to manage your eCommerce stores by providing calls for working with resources such as customers, categories, products, and sales orders. It also allows you to manage shopping carts and inventory.

A SOAP v2 API version has been available since Magento 1.3, and a WS-I compliant version has been available since Magento 1.6.

Supported Types

The Magento API supports SOAP and XML-RPC, where SOAP is the default protocol.

2.1. SOAP

To connect to Magento SOAP web services, load the WSDL into your SOAP client from either of these URLs:

http://magentohost/api/?wsdl</span>
<span style="color: #000000;"> http://magentohost/api/soap/?wsdl

where magentohost is the domain for your Magento host.

As of v1.3, you may also use the following URL to access the Magento API v2, which has been added to improve compatibility with Java and .NET:

http://magentohost/api/v2_soap?wsdl=1

The following PHP example shows how to make SOAP calls to the Magento API v1:

$client = new SoapClient('http://magentohost/soap/api/?wsdl');</span>

<span style="color: #000000;">// If somestuff requires api authentification,</span>
<span style="color: #000000;"> // then get a session token</span>
<span style="color: #000000;"> $session = $client-&gt;login('apiUser', 'apiKey');</span>

<span style="color: #000000;">$result = $client-&gt;call($session, 'somestuff.method');</span>
<span style="color: #000000;"> $result = $client-&gt;call($session, 'somestuff.method', 'arg1');</span>
<span style="color: #000000;"> $result = $client-&gt;call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));</span>
<span style="color: #000000;"> $result = $client-&gt;multiCall($session, array(</span>
<span style="color: #000000;"> array('somestuff.method'),</span>
<span style="color: #000000;"> array('somestuff.method', 'arg1'),</span>
<span style="color: #000000;"> array('somestuff.method', array('arg1', 'arg2'))</span>
<span style="color: #000000;"> ));</span>
<span style="color: #000000;"> // If you don't need the session anymore</span>
<span style="color: #000000;"> $client-&gt;endSession($session);

2.2. XML-RPC

To use XML-RPC, load the following URL into your XML-RPC client:

http://magentohost/api/xmlrpc/

where magentohost is the domain for your Magento host.

The following PHP example shows how to make XML-RPC calls:

$client = new Zend_XmlRpc_Client('http://magentohost/api/xmlrpc/');</span>

<span style="color: #000000;">// If somestuff requires api authentification,</span>
<span style="color: #000000;"> // we should get session token</span>
<span style="color: #000000;"> $session = $client-&gt;call('login', array('apiUser', 'apiKey'));</span>

<span style="color: #000000;">$client-&gt;call('call', array($session, 'somestuff.method', array('arg1', 'arg2', 'arg3')));</span>
<span style="color: #000000;"> $client-&gt;call('call', array($session, 'somestuff.method', 'arg1'));</span>
<span style="color: #000000;"> $client-&gt;call('call', array($session, 'somestuff.method'));</span>
<span style="color: #000000;"> $client-&gt;call('multiCall', array($session,</span>
<span style="color: #000000;"> array(</span>
<span style="color: #000000;"> array('somestuff.method', 'arg1'),</span>
<span style="color: #000000;"> array('somestuff.method', array('arg1', 'arg2')),</span>
<span style="color: #000000;"> array('somestuff.method')</span>
<span style="color: #000000;"> )</span>
<span style="color: #000000;"> ));</span>

<span style="color: #000000;">// If you don't need the session anymore</span>
<span style="color: #000000;"> $client-&gt;call('endSession', array($session));

The XML-RPC only supports the version 1 of the Magento API.

API Methods

The following table contains the API methods that can be called from your SOAP or XML-RPC client on the Magento v1 API.

Method Description Return Value
startSession() Start the API session and return session ID. string
endSession(sessionId) End the API session. boolean
login(apiUser, apiKey) Start the API session, return the session ID, and authorize the API user. string
call(sessionId, resourcePath,array arguments) Call the API resource that is allowed in the current session. See Note below. mixed
multiCall(sessionId, array calls,array options) Call the API resource’s methods that are allowed for current session. See Notes below. array
resources(sessionId) Return a list of available API resources and methods allowed for the current session. array
globalFaults(sessionId) Return a list of fault messages and their codes that do not depend on any resource. array
resourceFaults(sessionId, resourceName) Return a list of the specified resource fault messages, if this resource is allowed in the current session. array

Note: For call and multiCall, if no session is specified, you can call only resources that are not protected by ACL.

Note: For multiCall, if the “break” option is specified, multiCall breaks on first error.

The Magento SOAP API v2 does not support the call() and multiCall() methods, and instead provides a separate method for each API resource.

Global API Faults

The following table contains fault codes that apply to all SOAP/XML-RPC API calls.

Fault Code Fault Message
0 Unknown Error
1 Internal Error. Please see log for details.
2 Access denied.
3 Invalid api path.
4 Resource path is not callable.

SOAP API Version v2

Since Magento 1.3, version v2 of the SOAP API has also been available. The main difference between v1 and v2 is that instead of using methods call and multiCall, it has separate methods for each action.

For example, consider the following PHP code using SOAP v1.

$params = array(array(</span>

<span style="color: #000000;">'status'=&gt;array('eq'=&gt;'pending'),</span>
<span style="color: #000000;"> 'customer_is_guest'=&gt;array('eq'=&gt;'1'))</span>
<span style="color: #000000;"> ));</span>
<span style="color: #000000;"> $result = $client-&gt;call($sessionId, 'sales_order.list', $params);

With SOAP v2, the following code would be equivalent.

$params = array('filter' =&gt; array(</span>

<span style="color: #000000;">array('key' =&gt; 'status', 'value' =&gt; 'pending'),</span>
<span style="color: #000000;"> array('key' =&gt; 'customer_is_guest', 'value' =&gt; '1')</span>
<span style="color: #000000;"> ));</span>
<span style="color: #000000;"> $result = $client-&gt;salesOrderList($sessionId, $params);

Note that the WSDL for SOAP v1 and SOAP v2 are different. Note that in SOAP v1, customizing the API did not involve changing the WSDL. In SOAP v2, changes to the WSDL are required.

You can configure the SOAP v2 API to be WS-I compliant in the system configuration menu. To do this, set Services > Magento Core API > WS-I Compliance to Yes.

Note that the WSDL for the SOAP v2 API is different when in WS-I compliant mode.

Using the WS-I compliant SOAP v2 API WSDL, it is easy to automatically generate client classes for Java, .NET, and other languages using standard libraries.


3. How to declare and create a new API

The Core API allows you to manage a set of common resources used in Magento. However, you may choose to have your own set of resources to manage, or you may wish to extend the Core API to handle additional resources.

This tutorial leads you through the process of creating a custom API for a customer module that handles basic customer information.

Note: This tutorial applies to v1 of the API.

To learn more about the Core API, to read Magento Core API calls.

For general information about the Magento API, go to the Introduction.

3.1. Creating an XML file that will defend the API resource

Create a file named api.xml in the /etc folder in the customer module. Start with the empty structure, as follows:

<config>

<api>
<resources>
</resources>
<acl>
<all>
</all>
</acl>
</api>
</config>

3.2. Adding a Resource

Add an element named customer in the <resources> element. Add a <methods> element, with elements for list lesson31 resource.

Note that: list will return all customers

<config>

<api>
<resources>
<lesson31 translate="title" module="lesson31">
<title>Lesson31 Resource</title>
<methods>
<list translate="title" module="lesson31">
<title>Retrive Lesson 31</title>
</list>
</methods>
</lesson31>
</resources>
...
</api>
</config>

3.3. Adding Faults

The resource can return some faults, so add a <faults> element in the customer element, and list the various faults.

<config>

<api>
<resources>
<lesson31 translate="title" module="lesson31">
<title>Lesson31 Resource</title>
<methods>
<list translate="title" module="lesson31">
<title>Retrive Lesson 31</title>
</list>
</methods>
<faults module="lesson31">
<data_invalid> <!-- if we get invalid input data for customers -->
<code>100</code >
<!-- we cannot know all the errors that can appear, their details can be found in error message for call -->
<message>Invalid lesson 31 data. Details in error message.</message>
</data_invalid>
</faults>
</lesson31>
</resources>
...
</api>
</config>

3.4. Describing the Access Control List (ACL) for the Resource

In order to prevent unauthorized access to our lesson 31 API, you must first list the resources that are restricted within the <acl> element.

<config>

<api>
...
<acl>
<resources>
<lesson31 translate="title" module="lesson31">
<title>Lesson 31</title>
<list translate="title" module="lesson31">
<title>List all lesson 31</title>
</list>
</lesson31>
</resources>
</acl>
</api>
</config>

3.5. Creating PHP Code

Next, write some PHP code to access the resources. Start by creating a class called Mage_Lesson31_Model_Api that extends Mage_Api_Model_Resource_Abstract. Save it into a file called Api.php.

<?php

/**
* Magestore
*
* Online Magento Course
*
*/

/**
* Lesson31 Model
*
* @category Magestore
* @package Magestore_Lesson31
* @author Magestore Developer
*/
class Magestore_Lesson31_Model_Api extends Mage_Api_Model_Resource_Abstract
{
public function items($filters)
{
}
}

Note that you cannot create method “list” because it’s a PHP keyword, so instead the method is named items. In order to make this work, add a <method> element into the <list> element in api.xml, as shown below.

<config>

<api>
<resources>
<lesson31 translate="title" module="lesson31">
<title>Lesson31 Resource</title>
<methods>
<list translate="title" module="lesson31">
<title>Retrive Lesson 31</title>
<method>items</method> <!-- we have another method name inside our resource -->
<acl>lesson31/list</acl>
</list>
</methods>
<faults module="lesson31">
<data_invalid> <!-- if we get invalid input data for customers -->
<code>100</code >
<!-- we cannot know all the errors that can appear, their details can be found in error message for call -->
<message>Invalid lesson 31 data. Details in error message.</message>
</data_invalid>
</faults>
</lesson31>
</resources>
...
</api>
</config>

Now add some simple functionality to the Mage_Lesson31_Model_Api methods you created.

Retrieve list of lesson 31 using filtering:

class Magestore_Lesson31_Model_Api extends Mage_Api_Model_Resource_Abstract {

public function items($filters) {
$collection = Mage::getModel('lesson31/lesson31')->getCollection()
->addAttributeToSelect('*');

if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
// If we are adding filter on non-existent attribute
}
}

$result = array();
foreach ($collection as $lesson31) {
$result[] = $lesson31->toArray();
}

return $result;
}

}

After this lesson, we should know:

  • How API works in Magento
  • How to use available API functions
  • How to create a new API

Don’t forget to follow us in Magento Tutorial. You can read more in Magento Open Course.

Author

Why Magestore? We believe in building a meaningful & long-term relationship with you.

Write A Comment