Introduction to REST API

Last modified by VJ.Magento Master on Wed, June 13, 2012 05:51
Source|Old Revisions  

This is an old revision of the document!


Overview

What is REST API? REST API defines a set of functions to which the developers can perform requests and receive responses via HTTP protocol. Because it uses HTTP, REST can be used practically for any programming language and easy to test.

The common characteristics of Magento REST API resources are as follows:

  • You access the resource by sending an HTTP request to the Magento API server. The server replies with a response that contains either the data you requested, or the status indicator, or even both.
  • All resources are located at https://magentohost/api/rest/. (magentohost is your domain)
  • All resources may return different HTTP status codes (e.g. HTTP Status Code 200 for the successful response or HTTP Status Code 400 for the bad request).
  • You request a particular resource by adding a particular path to the base URL that specifies the resource.

Overall Capabilities

Magento REST API allows managing a number of features, namely:

  • Managing customers.
  • Managing customer addresses.
  • Managing products.
  • Retrieving sales orders.
  • Managing inventory.

Authentication

Magento REST API uses 3-legged OAuth 1.0a protocol to authenticate the application to safely access the Magento service.

Output Formats

The REST API supports the response in two formats, which are XML and JSON.

HTTP Verbs

HTTP verbs are used to manage the state of resources. In Magento REST API, there are four verbs used to manage resources: GET, POST, PUT, and DELETE. You can get the contents of the data using HTTP GET, delete the data using HTTP DELETE, and create or update the data using POST/PUT.

Request Structure

All URLs in REST API have the following base URL.

http://magentohost/api/rest/

Example

You would like to retrieve the list of customers from Magento. To do this, you need to use the GET HTTP method. The GET request to retrieve the list of customers will look as follows:

http://magentohost/api/rest/customers

where

REST Resources

REST resources are simply the entities that are exposed to consumers. REST defines the entity of the resource via the URI (uniform resource identifier). Each resource has a unique URL address and any interaction with the resource takes place at its URI.

Products

Product Categories
Product Images
Product Websites

Customers

Customer Addresses

Inventory

Sales Orders

Order Items
Order Addresses
Order Comments

Preparing for REST API

Following steps are required for utilizing REST API resources:

  • Set up permissions for REST resource operations from Magento Admin Panel (System → Web Services → REST - Roles) .
  • Configure the attributes for different users types in Magento Admin Panel (System → Web Services → REST - Attributes) . There are 3 different types of users in accessing the data: Admin, Customer, and Guest. Admin is the backend logged in user, Customer is the fronted logged in user, and Guest is a non-logged in fronted user.

Preparing REST API for the Third-Party Application

  • Register the third-party application (Consumer) in Magento Admin Panel.
  • The third-party application will utilize the provided consumer credentials to call Magento store for getting the access token to access the data.

PHP Examples

Create a simple product as an Admin user with OAuth authentication

  1. /**
  2. * Example of simple product POST using Admin account via Magento REST API. OAuth authorization is used
  3. */
  4. $callbackUrl = "http://yourhost/oauth_admin.php";
  5. $temporaryCredentialsRequestUrl = "http://magentohost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
  6. $adminAuthorizationUrl = 'http://magentohost/admin/oauth_authorize';
  7. $accessTokenRequestUrl = 'http://magentohost/oauth/token';
  8. $apiUrl = 'http://magentohost/api/rest';
  9. $consumerKey = 'yourconsumerkey';
  10. $consumerSecret = 'yourconsumersecret';
  11.  
  12. session_start();
  13. if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
  14.     $_SESSION['state'] = 0;
  15. }
  16. try {
  17.     $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
  18.     $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
  19.     $oauthClient->enableDebug();
  20.  
  21.     if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
  22.         $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
  23.         $_SESSION['secret'] = $requestToken['oauth_token_secret'];
  24.         $_SESSION['state'] = 1;
  25.         header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
  26.         exit;
  27.     } else if ($_SESSION['state'] == 1) {
  28.         $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
  29.         $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
  30.         $_SESSION['state'] = 2;
  31.         $_SESSION['token'] = $accessToken['oauth_token'];
  32.         $_SESSION['secret'] = $accessToken['oauth_token_secret'];
  33.         header('Location: ' . $callbackUrl);
  34.         exit;
  35.     } else {
  36.         $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
  37.         $resourceUrl = "$apiUrl/products";
  38.         $productData = json_encode(array(
  39.             'type_id'           => 'simple',
  40.             'attribute_set_id'  => 4,
  41.             'sku'               => 'simple' . uniqid(),
  42.             'weight'            => 1,
  43.             'status'            => 1,
  44.             'visibility'        => 4,
  45.             'name'              => 'Simple Product',
  46.             'description'       => 'Simple Description',
  47.             'short_description' => 'Simple Short Description',
  48.             'price'             => 99.95,
  49.             'tax_class_id'      => 0,
  50.         ));
  51.         $headers = array('Content-Type' => 'application/json');
  52.         $oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
  53.         print_r($oauthClient->getLastResponseInfo());
  54.     }
  55. } catch (OAuthException $e) {
  56.     print_r($e);
  57. }

Retrieve the list of products as a Customer user with OAuth authentication

  1. <?php
  2. /**
  3. * Example of products list retrieve using Customer account via Magento REST API. OAuth authorization is used
  4. */
  5. $callbackUrl = "http://yourhost/oauth_customer.php";
  6. $temporaryCredentialsRequestUrl = "http://magentohost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
  7. $adminAuthorizationUrl = 'http://magentohost/oauth/authorize';
  8. $accessTokenRequestUrl = 'http://magentohost/oauth/token';
  9. $apiUrl = 'http://magentohost/api/rest';
  10. $consumerKey = 'yourconsumerkey';
  11. $consumerSecret = 'yourconsumersecret';
  12.  
  13. session_start();
  14. if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
  15.     $_SESSION['state'] = 0;
  16. }
  17. try {
  18.     $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
  19.     $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
  20.     $oauthClient->enableDebug();
  21.  
  22.     if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
  23.         $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
  24.         $_SESSION['secret'] = $requestToken['oauth_token_secret'];
  25.         $_SESSION['state'] = 1;
  26.         header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
  27.         exit;
  28.     } else if ($_SESSION['state'] == 1) {
  29.         $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
  30.         $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
  31.         $_SESSION['state'] = 2;
  32.         $_SESSION['token'] = $accessToken['oauth_token'];
  33.         $_SESSION['secret'] = $accessToken['oauth_token_secret'];
  34.         header('Location: ' . $callbackUrl);
  35.         exit;
  36.     } else {
  37.         $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
  38.         $resourceUrl = "$apiUrl/products";
  39.         $oauthClient->fetch($resourceUrl);
  40.         $productsList = json_decode($oauthClient->getLastResponse());
  41.         print_r($productsList);
  42.     }
  43. } catch (OAuthException $e) {
  44.     print_r($e);
  45. }

REST Client Example

Retrieving the list of Products as a Guest

  • Use the REST Client that is a FireFox add-on. In the REST Client, in the Method drop-down list, select the GET option.
  • In the URL field, enter the following URL:
    http://magentohost/api/rest/products?limit=2
  • Click Send. Information about the products will be displayed in the response body. Example in the XML format is as follows:

Example: XML

  1. <?xml version="1.0"?>
  2. <magento_api>
  3.   <data_item>
  4.     <entity_id>16</entity_id>
  5.     <type_id>simple</type_id>
  6.     <sku>n2610</sku>
  7.     <description>The Nokia 2610 is an easy to use device that combines multiple messaging options including email, instant messaging, and more. You can even download MP3 ringtones, graphics, and games straight to the phone, or surf the Internet with Cingular's MEdia Net service. It's the perfect complement to Cingular service for those even remotely interested in mobile Web capabilities in an affordable handset.
  8. Design
  9. Compact and stylish, the 2610 features a candybar design sporting a bright 128 x 128 pixel display capable of displaying over 65,000 colors. Most of the phone's features and on-screen menus are controlled by a center toggle on the control pad. A standard hands-free headphone jack is provided, as are volume control keys, and there's even a "Go-To" button that can be assigned by the user for quick access to favorite applications. Lastly, the included speakerphone allows you to talk handsfree, and because the phone sports an internal antenna, there's nothing to snag or break off.
  10. </description>
  11.     <meta_keyword>Nokia 2610, cell, phone, </meta_keyword>
  12.     <short_description>The words "entry level" no longer mean "low-end," especially when it comes to the Nokia 2610. Offering advanced media and calling features without breaking the bank</short_description>
  13.     <name>Nokia 2610 Phone</name>
  14.     <meta_title>Nokia 2610</meta_title>
  15.     <meta_description>Offering advanced media and calling features without breaking the bank, The Nokia 2610 is an easy to use</meta_description>
  16.     <regular_price_with_tax>149.99</regular_price_with_tax>
  17.     <regular_price_without_tax>149.99</regular_price_without_tax>
  18.     <final_price_with_tax>149.99</final_price_with_tax>
  19.     <final_price_without_tax>149.99</final_price_without_tax>
  20.     <is_saleable>1</is_saleable>
  21.     <image_url>http://magentohost/imageulr/nokia.jpg</image_url>
  22.   </data_item>
  23.   <data_item>
  24.     <entity_id>17</entity_id>
  25.     <type_id>simple</type_id>
  26.     <sku>bb8100</sku>
  27.     <description> Like the BlackBerry 7105t, the BlackBerry 8100 Pearl is
  28. The BlackBerry 8100 Pearl sports a large 240 x 260 screen that supports over 65,000 colors-- plenty of real estate to view your e-mails, Web browser content, messaging sessions, and attachments. The venerable BlackBerry trackwheel has been replaced on this model with an innovative four-way trackball placed below the screen. On the rear of the handheld, you'll find a 1.3-megapixel camera and a self portrait mirror. The handheld's microSD memory card slot is located inside the device, behind the battery. There's also a standard 2.5mm headset jack that can be used with the included headset, as well as a mini-USB port for data connectivity.</description>
  29.     <meta_keyword>Blackberry, 8100, pearl, cell, phone</meta_keyword>
  30.     <short_description>The BlackBerry 8100 Pearl is a departure from the form factor of previous BlackBerry devices. This BlackBerry handset is far more phone-like, and RIM's engineers have managed to fit a QWERTY keyboard onto the handset's slim frame.</short_description>
  31.     <name>BlackBerry 8100 Pearl</name>
  32.     <meta_title>BlackBerry 8100 Pearl</meta_title>
  33.     <meta_description>BlackBerry 8100 Pearl sports a large 240 x 260 screen that supports over 65,000 colors-- plenty of real estate to view your e-mails, Web browser content, messaging sessions, and attachments.</meta_description>
  34.     <regular_price_with_tax>349.99</regular_price_with_tax>
  35.     <regular_price_without_tax>349.99</regular_price_without_tax>
  36.     <final_price_with_tax>349.99</final_price_with_tax>
  37.     <final_price_without_tax>349.99</final_price_without_tax>
  38.     <is_saleable>1</is_saleable>
  39.     <image_url>http://magentohost/imageulr/blackberry.jpg</image_url>
  40.   </data_item>
  41. </magento_api>

Additional Information

You can define the limit of items returned in the response by passing the limit parameter. By default, 10 items are returned and the maximum number is 100 items. You can also define the page number by passing the page parameter. Example:

http://magentohost/api/rest/products?page=2&limit=20

Authorization header will be required for Admin and Customer user types. The following parameters must be provided in the Authorization header for the call:

  • oauth_consumer_key - the Consumer Key value provided after the registration of the application.
  • oauth_nonce - a random value, uniquely generated by the application.
  • oauth_signature_method - name of the signature method used to sign the request. Can have one of the following values: HMAC-SHA1, RSA-SHA1, and PLAINTEXT.
  • oauth_signature - a generated value (signature).
  • oauth_timestamp - a positive integer, expressed in the number of seconds since January 1, 1970 00:00:00 GMT.
  • oauth_token - the oauth_token value (Request Token) received from the previous steps.
  • oauth_version - OAuth version.



 

Magento 2 GitHub Repository

Magento Job Board - Some sort of tag line goes here

Latest Posts| View all Jobs