Posts

Ultimate Magento 1 Developer Guide : How to get product details using rest API in Magento 1.x ?

Future is mobile apps. Especially, eCommerce Mobile Apps. Sooner or later you’ll run into a case where you need REST API for your online store and you found that Magento does not support all Magento REST API. What should you do now? How can you write REST API for your online store as per client need?

The Magento REST API allows you to use various data entities such as customer, catalog and order information to third-party applications. I’d like to share it with you a quick, simple, well written and easy solution which will explain how can you retrieve the product details with the help of REST API.

You are working on a mobile application and want to display product after customer selected a category. You are able to get the list of the product by category in REST API request but that list doesn’t have many details about the product and you want to show more product details to the users. What should you do to get more product information so that you can show the image and other things in a mobile app?

Magento Rest API for Product Details by SKU

Step 1: Get the SKU which you need to get the product details.

      $sku  =  $this->getRequest()->getParam('SKU');

Step 2: Load the product using the product SKU. We can also load product by its attributes, like SKU, Id. Assuming product SKU to be ‘1000’.

    
       // Mage main object
	$catalogMageObj = Mage::getModel('catalog/product');
	$products = $catalogMageObj->loadByAttribute('sku', $sku);

Step 3: load the product custom attributes details.

	$custom_attributes = array();
	$attributes = $products->getAttributes();
	foreach ($attributes as $attribute) {
		if ($attribute->getAttributeCode() =="category_ids"){
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $products->getCategoryIds()
			);
		}
		else{
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $attribute->getFrontend()->getValue($products)
			);
		}
	}

Step 4: Create and return the full array of the loaded product.

	
protected function getProductDetailsBySku()
{
        $sku  =  $this->getRequest()->getParam('sku');	

        // Mage main object
	$catalogMageObj = Mage::getModel('catalog/product');
	$products = $catalogMageObj->loadByAttribute('sku', $sku);

	$custom_attributes = array();
	$attributes = $products->getAttributes();
	foreach ($attributes as $attribute) {
		if ($attribute->getAttributeCode() =="category_ids"){
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $products->getCategoryIds()
			);
		}
		else{
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $attribute->getFrontend()->getValue($products)
			);
		}
	}
				
	$data = array(
		'id' => $products->getEntityId(),
		'sku' => $products->getSku(),
		'name' => $products->getName(),
		'attribute_set_id' => (int)$products->getAttributeSetId(),
		'price' => $products->getPrice(),
		'status' => $products->getStatus(),
		'visibility' => $products->getVisibility(),
		'type_id' => $products->getTypeId(),
		'created_at' => $products->getCreatedAt(),
		'updated_at' => $products->getUpdatedAt(),
		'product_links' => $productstypes, 
		'custom_attributes'  => $custom_attributes
	);
		
	//return $products;
	return $data;
}

How to get Configured Product Extension Attributes

Getting all options of a specific attribute in Magento is fairly easy but sometimes A more challenging task is to get the options and values that are applicable to a particular configurable product. This can solve using the following code:

// get product extension attributes details
	public function getProductExtensionAttributes($productObj){
		
		if (!is_object($productObj)){
			return false;
		} 
		
		$extensionAttributesFinalArray = array();
		$extensionAttributesArray = array();
		if ($productObj->isConfigurable()){
			$optionsData = $productObj->getTypeInstance(true)->getConfigurableAttributesAsArray($productObj);
			foreach ($optionsData as $option) {
				// get option values
				$values =  $option['values'];
				$tempDataItems = array();
				foreach ($values as $value) {
					$tempData = array(
							"value_index" => $value['value_index'],
							"title" => $value['label']
					);
					$product_super_attribute_id =  $value['product_super_attribute_id'];
					array_push($tempDataItems, $tempData);
				}
				
				// create temp array for extension_attributes
				$extensionAttributesTempArray = array(
						"id" => $option['id'],
						"label" => $option['label'],
						"position" => $option['position'],
						"attribute_id" => $product_super_attribute_id,
						"values" => $tempDataItems,
						"product_id" => (int)$productObj->getEntityId(),
				);
				array_push($extensionAttributesFinalArray, $extensionAttributesTempArray);
			}
			$extensionAttributesArray['configurable_product_options'] = $extensionAttributesFinalArray;
			$extensionAttributesArray['configurable_product_links'] = [];
		}
		
		// returning response
		return $extensionAttributesArray;
	}

The resulting array will consist of an associative array, indexed by the attribute label, with nested arrays containing attribute value => attribute label items.

Conclusion

This is the era of eCommerce with the Mobile app as peoples are spending time on their mobile. The user has various choices to purchase an item from the web that’s why your eCommerce website should remain competitive in your business. The mobile app is a new way, which turns your Magento website into a fully functional eCommerce store with everything user needs.

On this tutorial, we have discussed how to get all the product details Magento which you can use to develop your Magento Mobile App.

References

Further reading

Ultimate Magento 1 Developer Guide : Token Base Rest API for authentication and authorization

Security has always been a major concern we talk about high-level applications or mobile apps, especially when we talk about exposing our business through services. I have already explained a lot of REST API in my earlier articles. I explained, how do we create a Magento 1 REST API, how do we get the available categories from the store, How can you search the products in your mobile app etc. This article will explain how to make token based REST API to handle authentication among the devices. There is no standard way of doing token based authentication on the Magento 1 that’s why we design our own security technique and structure which suits best to our application.

One of the key principles of REST is that it’s stateless. This means that the server never keeps user state. In the context of security, this aspect has impacts when implementing security. This means that authentication hints must be sent and verified at each time.  An authenticated user will be allowed to access resources for a particular period of time and can re-instantiate the request with an increased session time delta to access other resource or the same resource.

Magento REST API Security

Magento 1 Security in itself is very complicated and tricky topic. I’ll try to explain how we can achieve it in REST API security in my own way. When we plan to create a mobile app, we especially want to take care of authentication and authorization. There are various ways to achieve security in Magento 1 but we have decided to use token-based authentication on our mobile app.

Authentication

Authentication is all about the identity of an end user. It’s about validating the identity of a user who is accessing our system, that he is authenticated enough to use our resources or not. Does that end user have valid credentials to log in our system? Credentials can be in the form of a username and password. We’ll use Basic Authentication technique to understand how we can achieve authentication in WebAPI.

Authorization

Authorization should be considered as a second step after authentication to achieve security. Authorization means what all permissions the authenticated user has to access web resources. Is allowed to access/ perform an action on that resource? This could be achieved by setting roles and permissions for an end user who is authenticated or can be achieved through providing a secure token, using which an end user can have access to other services or resources.

Magenot Token Based Authorization

Authorization part comes just after authentication, once authenticated a service can send a token to an end user through which user can access other resources. The token could be any encrypted key, which only server/service understands and when it fetches the token from the request made by the end user, it validates the token and authorizes user into the system. Token generated could be stored in a database or an external file as well i.e. we need to persist the token for future references. The token can have its own lifetime and may expire accordingly. In that case, the user will again have to be authenticated into the system.

Implementation of the token based authorization in Magento 1

Below is the code which we have used to create & manage tokens in Magento 1.x version.

 Public function generateUserToken($data){
        // get the username & password of the user
        $username = $data['username'];
    	$password = $data['password'];

        // check username password exists on our system or not
         if (!$customer->authenticate($username, $password)) {
              // user is not registered with this Magento 1 website
         }

        // load customer details if exist
	$customerObj = $customer->loadByEmail($username);
	$customerId =  $customerObj->getEntityId();

        // check user token is already generated or not and return token if exist and return the token from database if exist
	$customerapitokensObj = Mage::getModel('customerapi/customerapitokens');
	$customerapitokensObj->load($customerId, 'customer_id');
	if ($customerapitokensObj->getToken()){
		$token = $customerapitokensObj->getToken();
		return $token;
	}

        // generate token and save customer tokens
	try {
                // create MD5 token with username and password and date comibanation to make token unique
		$date  = date("Y-m-d H:i:s")."".$username."".$password;
		$token = md5(uniqid($date, true));
				
		$customerapitokensObj->setCustomerId($customerId);
		$customerapitokensObj->setToken($token);
		$customerapitokensObj->setStatus(1);
		$customerapitokensObj->setDate(date("Y-m-d H:i:s"));
		$newUserData = $customerapitokensObj->save();
				
		return $token; 
	} catch (Exception $e) {
		$this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_UNAUTHORIZED);
	}

}

Database Structure for the Token support

magentoTokenBasedAutentication

 

Conclusion

In this article, I tried to explain about how we can build an API application with basic Authentication and Authorization. One can mold this concept to achieve the level of security needed. If you want to implement Token-based-authentication on your Magento 1 mobile apps then you will find these above steps easier. The above code will create and manage the token-based authentication on your Magento 1 store and you can display on your mobile app. If any better approach or solution your thoughts are most welcome. Please share with us so that it might help others as well.

References

Further reading

 

Ultimate Magento 1 Developer Guide : How to get Country and Region Collection using rest API in Magento 1.x ?

Sooner or later you’ll run into a case where you need REST API for your online store and you found that Magento 1 does not support all Magento 1 REST API. What should you do now? How can you write REST API for your online store as per client need?

The Magento 1 REST API allows you to use various data entities such as customer, catalog and order information to third party applications. I’d like to share it with you a quick, simple, well written and easy solution which will explain how can you retrieve the data with the help of REST API.

When working with Magento 1 REST API, for some specific reasons a developer wants to access a list of countries with regions to display the countries list on the mobile app. We first needed to access a collection of countries in Magento 1, then we will get the region based on the country. Below is some sample code that we can use to access country names and codes in Magento.

Magento 1 collection of all countries

Magento 1 has a model which provides all the countries list and below is the code for getting the collection of all countries.

       public function getCountryCollection(){
            //get the all countries
            $countryCollection = Mage::getModel('directory/country_api')->items();
       }

Magento 1 collection of regions related to specific country

Magento 1 has a predefined model which takes countryId and return all the available region, below is the code for getting the available region based on the countryId.

      public function getRegionByCountryId(){
              // get region based on countries
              $regions = Mage::getModel('directory/region_api')->items($countryId);
      }

Get All countries Collection with their Region

Magento 1 has a predefined way to get countries and available region of the specified countries but does not provide the all countries list with the available region. I have used both above ways to create a single REST API and get all the countries along with the regions. Below is the complete code.

        
public function getCountriesWithRegions(){
         //get all countries
        $countryCollection = Mage::getModel('directory/country_api')->items();
	$countries = array();
	foreach($countryCollection as $country)
	{	
		// get region based on countries
		$regions = Mage::getModel('directory/region_api')->items($country['country_id']);
		$availableRegion = array();
		foreach ($regions as $region){
			$temData = array(
				'id' => $region['region_id'],
				'code' => $region['code'],
				'name' => $region['name']
			);
			array_push($availableRegion, $temData);
		}
			
		// creating array which contains country with available region
		$data = array(
			'id' => $country['country_id'],
			'two_letter_abbreviation' => $country['iso2_code'],
			'three_letter_abbreviation' => $country['iso3_code'],
			'full_name_english' => $country['name'],
			'available_regions' => $availableRegion
		);
			array_push($countries, $data);
	}
		
	// returning response
	return $countries;
}

Conclusion

This is the era of eCommerce with the Mobile app as peoples are spending time on their mobile. The user has various choices to purchase an item from the web that’s why your eCommerce website should remain competitive in your business. The mobile app is a new way, which turns your Magento 1 website into a fully functional eCommerce store with everything user needs.

On this tutorial, we have discussed how to get all the country list along with the region in Magento 1 which you can use to develop your Magento 1 Mobile App.

References

Further reading

Ultimate guide to edit and delete address in magento mobile app

Magento is based on open source platform for e-commerce which provides smooth shopping cart system with control over the look and functionality of the store. It is growing in the e-commerce market day by day. More traders are using this platform for their e-store. It provides a various feature for an e-commerce store, you can check its features in our previous blog. With the increase in the e-commerce stores, mobile-commerce has also become popular these days. Mobile visits account for one-third of e-commerce sites traffic. To have an e-commerce mobile app for electronic commerce store is like putting a  retail outlet in the customer’s pocket. Magento provides SEO, items management, and other tools. It enforce traders to have the mobile app for superb shopping experience for customers.  In this blog, I am going to discuss some important features i.e edit delete address Magento in the mobile app using REST API.

Edit Delete address Magento:

Here we will discuss the edit delete address Magento in a mobile app using REST API. Here we take an example of two address.

{
 "customer": 
   {
     "email": "[email protected]",
     "firstname": "test",
     "lastname": "test",
     "websiteId": 0,
        "addresses": [
           {
              "id": 1,
              "firstname": "test",
              "lastname": "test",
              "company": "test technology",
              "street": ["Test Street 9", "Tiny House 9"],
              "city": "City Nine",
              "region_id": 12,
              "region": "California",
              "postcode": "91790",
              "country_id": "US",
              "telephone": "1234567890"
           }, 
           {
             "id": 2,
             "firstname": "test",
             "lastname": "test",
             "company": "test technology",
             "street": ["Test Street 10", "Tiny House 10"],
             "city": "City Ten",
             "region_id": 12,
             "region": "California",
             "postcode": "91790",
             "country_id": "US",
             "telephone": "1234567890"
            }]
   }
}

Edit address in Magento:

Below is the API to create a customer. Then put the parameters for the address:

 PUT http://Base URL/rest/V1/customers/me

Now we can edit the address by using the address id. If we send the address id with change data then only that address will be changed that we want to edit. If we don’t send the address id then the new address will be generated.


{ "customer":
    {
       "email":"[email protected]",
       "firstname":"test",
       "lastname":"test",
       "websiteId": 0,
       "addresses": [
            {
                "id": 1,
                "firstname": "testedit",
                "lastname": "testedit",
                "company": "test technology edit",
                "street": [
                "Test Street 9",
                "Tiny House 9"
                ],
                "city": "City Nine edit",
                "region_id": 12,
                "region": "California",
                "postcode": "91790000",
                "country_id": "US",
                "telephone": "123456789000"
            },
            {
                "firstname": "test",
                "lastname": "test",
                "company": "test technology",
                "street": [
                "Test Street 10",
                "Tiny House 10"
                ],
                "city": "City Ten",
                "region_id": 12,
                "region": "California",
                "postcode": "91790",
                "country_id": "US",
                "telephone": "1234567890"
            }
        ]
    }

In the example we send the address id with the parameters then id with 1 will be edited.

Delete address in Magento:

Below is the API to create a customer. Then put the parameters for the address:

PUT http://Base URL/rest/V1/customers/me

Now we can delete the address by not sending the address in the parameter. For example, we want to delete the address with id 1. Then we will not send the id 1 in the addresses. Then that address will not be generated and that address will not come in the address list.

 { "customer":
    {
       "email":"[email protected]",
       "firstname":"test",
       "lastname":"test",
       "websiteId": 0,
       "addresses": [
            {
                "id":2
                "firstname": "test",
                "lastname": "test",
                "company": "test technology",
                "street": [
                "Test Street 10",
                "Tiny House 10"
                ],
                "city": "City Ten",
                "region_id": 12,
                "region": "California",
                "postcode": "91790",
                "country_id": "US",
                "telephone": "1234567890"
            }
        ]
    }

By this address id with 1 will be deleted.

These are the ways to edit and delete the address in the Magento app using the Mgento API.

Conclusion

As the implementation of Magento framework is increasing day by day for the e-commerce stores, demand for mobile commerce is also increasing with the same speed and popularity. So developing an e-commerce mobile app is becoming common and for any e-commerce store edit and delete address are very common and powerful property. Keeping these all things in mind I wrote this article to help the new developer for Magento. I hope this will help you… :-). Below is our sample app based on Magento REST API, you can refer it as an example which has shown the use of edit deletes address Magento using REST APIs.

magento-logo
MagentoShop
Looking for a native Magento mobile app builder (iOS/Android) for your Magento based online marketplace? Try the 30-day free trial of our Magento mobile app, go mobile commerce in a few hours and increase your sales exponentially. No Setup Fee, Pay as you go pack at just $69/month.

References

  • Magento: Magento Documentation for Developers
  • Magento API: Magento API Documentation for Developers. Get the Edit Delete address Magento API.

Further reading:

How to build custom Magento Rest API effortlessly in less than 2 hours : Part 1

Sooner or later you’ll run into a case where you need REST API for your online store and you found that Magento does not support all Magento REST API. What should you do now? How can you write REST API for your online store as per client need?

The Magento REST API allows you to use various data entities such as customer, catalog and order information to third party applications. I’d like to share it with you a quick, simple, well written and easy solution with will explains how you can write an extension for Magento REST API.

Magento REST API Features

  • Simplistic design approach
  • Testing and troubleshooting is easier
  • Better performance than ever
  • Ability to manage customers, addresses, orders, inventories and products using HTTP verbs such as GET, POST, PUT and DELETE.
  • Data requests and responses can be in XML or JSON format.

Custom Extension for REST API

Create new custom module on your Magento server with the following structure to create a custom module with REST support.

rest-api-structure

 

Here’s the list of files required for the desired setup, Here Ip is the package and Productapi are the module name. You can edit as per your need:

  • app/code/local/Ip/Productapi/etc/config.xml: It’s a module configuration file.
  • app/code/local/Ip/Productapi/etc/api2.xml: It’s a file which declares the APIs provided by our module.
  • app/code/local/Ip/Productapi/Helper/Data.php: It’s a file used by the Magento translation system.
  • app/code/local/Ip/Productapi/Model/Api.php: It’s a model file which implements the logic of our API methods.
  • app/code/local/Ip/Productapi/Model/Api2/Product/Productlist/Rest/Guest/V1.php: It’s a file to support Magento’s v1 REST API.

Magento REST API Step 1: Enabling Extention

The first thing to now do is create your module definition file in app/etc/modules (not in the above folder diagram). For my extension, this is call Productapi.xml

<?xml version="1.0"?>
<config>
  <modules>
    <Ip_Productapi>
      <active>true</active>
      <codePool>local</codePool>
      <version>0.1.0</version>
    </Ip_Productapi>
  </modules>
</config>

Magento REST API Step 2: Extensions Configuration

Now, we need to start setting up our extensions configuration.  We need two files for this in our extension’s etc folder; config.xml and api2.xml.

Config.xml:

Create the config.xml file and put in the Ip -> Productapi -> etc directory and paste the below code. Here we are configuring Helper and Model file for the REST API and no need to change in Magento core file.

<?xml version="1.0"?>
<config>
  <modules>
    <Ip_Productapi>
      <version>0.1.0</version>
    </Ip_Productapi>
  </modules>
  <global>
    <helpers>
      <productapi>
        <class>Ip_Productapi_Helper</class>
      </productapi>
    </helpers>
    <models>
       <ip_productapi>
             <class>Ip_Productapi_Model</class>
        </ip_productapi>
        <api2>
	      <rewrite>
	            <request>Ip_Productapi_Model_Api2_Request</request>
	       </rewrite>
	</api2>
    </models>
  </global>
</config> 

api.xml: 

Create api2.xml and put in the Ip -> Productapi -> etc > api2.xml and paste the below code:

<config>
    <api2>
        <resource_groups>
            <ip_productapi translate="title" module="ip_productapi">
                <title>Ip Products</title>
                <sort_order>10</sort_order>
            </ip_productapi>
        </resource_groups>
        <resources>        
        	<ip_productapi_list translate="title" module="ip_productapi">
                <group>ip_productapi</group>
                <model>ip_productapi/api2_product_productlist</model>
                <title>Product List</title>
                <sort_order>11</sort_order>
                <privileges>
                    <guest>
		         <retrieve>1</retrieve>
                    </guest>
                    <customer>
		          <retrieve>1</retrieve>
                    </customer>
                </privileges>
                <attributes translate="attribute1 attribute2 attribute3" module="ip_productapi">
                    <attribute1>attribute1</attribute1>
                    <attribute2>attribute2</attribute2>
                    <attribute3>attribute3</attribute3>                    
                </attributes>
                <routes>
                    <route_entity>
                        <route>/ip/V1/products</route>
                        <action_type>entity</action_type>
                    </route_entity>
		</routes>
                <versions>1</versions>
            </ip_productapi_list>
        </resources>
    </api2>
</config>

On the Model(under Resource), we are telling Magento the name of the models used in the API calls. privileges section say what our users(guest, customer) can do here.

On the attributes section, we are set up the attributes which we need on the REST API response. For the moment we are returning three attributes(attribute1, attribute2, attribute3).

The last section of api2.xml is the route. On the route section, we are telling the front controller name of the REST API. Magento API runs on the route and whenever gets API call it uses the route and pass request to the definition. That’s all from extension configuration and now all we need to do is write the API class to handle the REST request.

Magento REST API Step 3: Helper file

Next, we’ll need to create the Helper file to make sure the translation system of Magento works . It’s almost an empty file, but should be there as per the conventions!

<?php
/**
 * Copyright © 2015 Ipragmatech . All rights reserved.
 */
namespace Ipragmatech\Ipreview\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
	public function __construct(\Magento\Framework\App\Helper\Context $context
	) {
		parent::__construct($context);
	}
}

Creating Magento REST API Model file

we need to create a model file to support the Magento V1 API. Let’s create a model file with the following contents. On this file, we will write our logic and return the response.

<?php
/**
 * Override for Magento's Catalog REST API
 */
class Ip_Productapi_Model_Api2_Product_Productlist_Rest_Guest_V1 extends Mage_Catalog_Model_Api2_Product_Rest 
{
	/**
	 * Return item GET
	 */
	protected function _retrieve()
	{
		// Write your code Here
	}	
}

Note

So that’s it as far as the file setup is concern for the custom API implementation. If you’re curious, enable the module from the back­-end and don’t forget to clear the cache. In the next Article, we’ll go ahead and know how to configure the application with the Admin role.

Conclusion

It’s important to remember that HTTP was conceived to communicate between systems, which share nothing but an understanding of the protocol. In general, the fewer assumptions beyond HTTP you make, the better: this allows the widest range of programs and devices to access your API.
If you are planning to add Magento REST API functionality on your website or mobile app then this article gives you the complete guide for creating Magento REST API structure in less time, effort and cost. You can also join the conversation if you have any other solution or idea which we can use to make it more attractive and easy. That’s all folks and feel free to contact us in case if you have any query.

References

For further reading