Magento API / web service work

Magento has strong web service features. I can say Magento’s web service is one step ahead than others e-commerce. Magneto has soap, v2_soap(soap 2) and xmlrpc adapter facilities. Using magento web services you can synchronize customer, categories, products, orders etc data with existing stores. Here I am going to describe magento’s web service deals step by step.

Setup API: At first create api user and api key from Magento’s admin. Follow below steps.
1. Create api user from admin->system->web services-> Users->Add New User->User Info. See picture.

Api user create with api key

Api user create with api key

2. Create role to set permission on api method under admin->system->web services-> Roles->Add New Role.
3. Define “Role Resources” for created role. See picture.

Set api permission on role

Set api permission on role

4. Set “User Role” from admin->system->web services-> Users->choose user->User Role.

Call API:
API user and key is created. Now we can call api methods in two ways.
1. Soap call
2. V2_Soap call

Here I am going to discuss both ways.

Soap call:
Magento wiki and help center have described this method. So who are beginner in web service work they can call magento api using this soap method. You get all api documentations in Magento site. Here is an example.


//create soap object
$proxy = new SoapClient('http://127.0.0.1/magento/api/soap/?wsdl');

// create authorized session id using api user name and api key
// $sessionId = $proxy->login('apiUser', 'apiKey');
$sessionId = $proxy->login('m4u_admin', '12345678');

 // Get customer info for customer id = 1
$customerinfo = $proxy->call($sessionId, 'customer.info', 1);

print_r($customerinfo);


V2_Soap call:

V2_soap call is for advance user. Who are expert in web service work they can easily use this method to call any magento api method from remote place. Whose magento knowledge is zero they also can use this soap method to work with magento web service. But about this method you will not get any api documentation in Magento wiki. But I think it will easy for you.

Here I am going to describe a-z about v2_soap method as any beginner also can use this soap calling method.


//create soap object
$proxy = new SoapClient('http://127.0.0.1/magento/api/v2_soap/?wsdl');

// create authorized session id using api user name and api key
// $sessionId = $proxy->login('apiUser', 'apiKey');
$sessionId = $proxy->login('m4u_admin', '12345678');

 // Get customer info for customer id = 1
$customerinfo = $proxy->customerCustomerInfo($sessionId,1);

print_r($customerinfo);

Which method you need to call?

At first decide which method you need to call of api. Suppose you want to retrieve customer info from Magento store. So you should call customer related api method to get customer info. But you donot know which method exactly you need. To view all available methods in your magento api please run http://127.0.0.1/magento/api/v2_soap/?wsdl. Now pick appropriate api method from wsdl operation list. Suppose I pick “customerCustomerInfo” method to get customer info.

<operation name="customerCustomerInfo">
   <documentation>Retrieve customer data</documentation> 
   <input message="typens:customerCustomerInfoRequest"/>
   <output message="typens:customerCustomerInfoResponse"/>
</operation>

What is request parameter?

From wsdl you get a clear concept about api request/input parameter. For “customerCustomerInfo” operation input message is “customerCustomerInfoRequest”. So you will get all input/request parameter info (name and type) to call customerCustomerInfo method in message “customerCustomerInfoRequest”. customerCustomerInfo has three request parameter such sessionid(string), customerid(int) and atribuates(Array).

<message name="customerCustomerInfoRequest"> 
    <part name="sessionId" type="xsd:string"/>
    <part name="customerId" type="xsd:int"/>
    <part name="attributes" type="typens:ArrayOfString"/>
</message>   

So we can request customerCustomerInfo method as below.

// Get customer info for customer id = 1 and attribute is optional
$attribute = array(‘firstname’, ‘lastname’, ‘email’, ‘store_id’);
$customerinfo = $proxy->call($sessionId, ‘customer.info’, 1, $attribute);

see picture for details-

API v2_soap wsdl request and response message.

API v2_soap wsdl request and response message.

What is return/response data?

From wsdl you also get idea about api response/return/output. For “customerCustomerInfo” operation output message is “customerCustomerInfoResponse”. So you will get output/result info (name and type) of customerCustomerInfo method in message “customerCustomerInfoResponse”. customerCustomerInfo will return customerCustomerEntity object as data. Please see what the format of customerCustomerEntity object in wsdl.

<message name="customerCustomerInfoResponse">
    <part name="customerInfo" type="typens:customerCustomerEntity"/>
</message>

That’s it!!

About these ads

66 responses to “Magento API / web service work

  1. Good article.

  2. Goog Job. This article is very interesting for my project.
    I’ve a doubt. Do you know if I can “addtocart” a product using the webservice methods?? I was looking for that issue in the API Doc , but I didn’t find anything.

    Thanks in advance.

  3. Hi moinul,

    I have followed the above steps but i have not get the perfect output by using API,so plz explain me how to use API. I am not getting the “customerCustominformation” method in the XML sheet in the browser page.

    • Hello Raj,

      To retrieve user information you have to write code like below.

      //create soap object
      $proxy = new SoapClient(‘http://127.0.0.1/magento/api/v2_soap/?wsdl’);

      // create authorized api sessionid using api user name and api key
      // $sessionId = $proxy->login(‘apiUser’, ‘apiKey’);
      $sessionId = $proxy->login(‘m4u_admin’, ’12345678′); // replace this using your own apikey and user id

      // Get customer info for customer id = 1
      $customerinfo = $proxy->customerCustomerInfo($sessionId,1);

      print_r($customerinfo);

  4. THANKS A LOT ISLAM. I WANT THE STORE NAME THROUGH API. WE ARE GETTING STORE ID IN THE PLACE OF STORE ID WE SHOULD PUT STORE NAME. IS IT POSSIBLE TO GET THE STORE NAME THROUGH CUSTOMER INFO?

    • Raj, You have to modify customer Info api method to get STORE NAME. You have store id in customer info. Use store id to get STORE Name and embed in api method.

  5. Is it possible to login and logout a user via the API? I’m trying to do this as part of an integration with another cms. How can this be achieved? Thanks for the great article!

    • Alex, It is not possible to destroy cookie/session through API. It is not a Magento limitation. It is matter of web service technology. Actually web service does not support session/cookie deletion. So you have to do this in alternate way. Suppose, you can manage a usertoken in magento db to track a user login and logout. Then You can create new api method to verify that token. I have used this usertoken technique in click2mail.com site to do same work.

  6. Hi Moinul Islam,

    Can you please guide me how to create the orders by using custom API. I have already create dthe two functions for creating the orders. It was working fine with saving customer data perfectly. But i am unable to save the product cost. It was saving as zero in the database. so plz share with me how to do perfectly the creating order API?

    • Hello Raj, did you get any solution? I have seen your code and it seems all are ok. But you are getting problem with order price. I think your product is virtual product. For virtual product you have to change code like below. Because a virtual product have no shipping address.

      $convertQuoteObj=Mage::getSingleton('sales/convert_quote');
      $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getBillingAddress());
      $orderPaymentObj=$convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
      $orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
      //$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
      $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
      

      If you have further any query then let me know.
      Thanks and sorry for late

  7. Is it possible to update a customer password for an existing customer using Magento API soap V2? I have had no success… tried using password, password_hash, both, salted hash, no luck. Others have posted similar failure with no successful solution posted anywhere I have seen. You are much more responsive than Magento forum so I thought my question would get help faster here :)
    thank you

    • Alex, goto Mage_Customer_Model_Customer_Api model and modify update method as below

      $customer->setPassword($customerData['password']); 
      $customer->save();
      return true;
      
  8. Thank you!
    Can I override this API method the same way I have overridden the regular customer model session methods (like login)? I’m writing a module to fully integrate SMF and Magento and don’t want to change the core files. Also when I upgrade the file I modify might be updated and my changes will be lost. It seems like Magento checks the md5 sum of it’s files when it upgrades and replaces any that aren’t correct. The Magento Wiki on customizing the API is a disaster as you probably know. If I can just get this password update function to work I’ll be done :)
    Varian should hire you to write Magento documentation because you do a better job than anyone there :D

  9. Here’s what I am trying to do:

    in app/etc/modules/Magentobridge.xml I have:

    <?xml version="1.0"?>
    <!--
    /*
    * Magento bridge files
    * for integrating SMF and Magento
    */
    -->
    <config>
        <modules>
            <Magentobridge_Apioverride>
    		    <active>true</active>
    		    <codePool>local</codePool>
            </Magentobridge_Apioverride>
        </modules>
    </config>
    

    in app/code/local/Magentobridge/Apioverride/etc/config.xml I have:

    <?xml version="1.0"?>
    <config>
      <modules>
        <Magentobridge_Apioverride>
          <version>0.1.0</version>
        </Magentobridge_Apioverride>
      </modules>
      <global>
        <models>
          <customer>
            <rewrite>
              <api_v2>Magentobridge_Apioverride_Model_Customer_Api_V2</api_v2>
            </rewrite>
          </customer>
        </models>
      </global>
    </config>
    

    and in app/code/local/Magentobridge/Apioverride/Api/v2.php I have:

    <?php
    
    class Magentobridge_Apioverride_Model_Customer_Api_V2 extends Mage_Customer_Model_Customer_Api_V2
    {
        public function update($customerId, $customerData)
        {
            $customer = Mage::getModel('customer/customer')->load($customerId);
    
            if (!$customer->getId()) {
                $this->_fault('not_exists');
            }
    
            foreach ($this->getAllowedAttributes($customer) as $attributeCode=>$attribute) {
                if (isset($customerData->$attributeCode)) {
                    $customer->setData($attributeCode, $customerData->$attributeCode);
                }
            }
    //big thanks to you for finding this!
            if(isset($customerData['password'])){
             $customer->setPassword($customerData['password']);} 
            $customer->save();
            return true;
        }
    
    }
    

    Is that the correct way to do this?
    Thanks!!!

  10. Hello Alex,
    change your model rewrite code in config xml as like below

    <models>
      <customer>
            <rewrite>
                  <customer_api_v2>Magentobridge_Apioverride_Model_Customer_Api_V2</customer_api_v2>
            </rewrite>
       </customer>
    </models>
    

    Thanks

  11. I’m getting closer. There is a response now :)
    Unfortunately with your code I get

     1="error:" 2="Uncaught" 3="SoapFault" 4="exception:" 5="Fatal"] Resource path is not callable

    when using ANY soap functions

    • Alex, i have checked and run that code in my pc. Please check your api calling url. Or if you can give access of your server then i can check the problem.

  12. Hi Moinul, I emailed you api and ftp logins for my site. The soapfault error I posted above is using my code. When I upload the code you emailed me I get another error, ‘SoapFault exception: [SOAP-ENV:Server] Cannot use object of type stdClass as array’.
    It looks like I’m getting closer :)
    Thanks!

  13. hi i’m trying to use the magento’s sales order api but my code is not connecting to the soap client can you give the solution.

    The error occured during my testing.

    Warning: SoapClient::SoapClient(http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl) [soapclient.soapclient]: failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Service Error in D:\xampp\htdocs\metny1\dreammining\cake_1_2\app\webroot\soaptest.php on line 37

    Warning: SoapClient::SoapClient() [soapclient.soapclient]: I/O warning : failed to load external entity “http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl” in D:\xampp\htdocs\metny1\dreammining\cake_1_2\app\webroot\soaptest.php on line 37

    Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn’t load from ‘http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl’ : failed to load external entity “http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl” in D:\xampp\htdocs\metny1\dreammining\cake_1_2\app\webroot\soaptest.php:37 Stack trace: #0 D:\xampp\htdocs\metny1\dreammining\cake_1_2\app\webroot\soaptest.php(37): SoapClient->SoapClient(‘http://192.168….’) #1 {main} thrown in D:\xampp\htdocs\metny1\dreammining\cake_1_2\app\webroot\soaptest.php on line 37

  14. thanx for the grat info

  15. Assalamo alikum,
    I know i m writing this in wrong category but still i m writing because i need your help.I made one website multiple stores and currencies and languages but it is not working as i did all the settings.I don’t know where it is going wrong, i tried all the solutions but ca’t get it done.If you can help me please drop me a mail.
    My website is http://magento.copiaclassica.com
    and if you want admin details i will PM you if you can give me your mail id.

    Thanks & Regards
    Naved M Pasha

  16. Indianic Orange

    Hello guys,

    I am new to using web services. I wants to use soap api to transfer data of contact us form to some other system like OTRS ticket system .

    I have code below to use.. but in magento where we have to place this code and how can we call it i can’t understand:

    error_reporting(E_ALL);

    # Please define the connection information here:
    $url = “http://example.com/otrs/rpc.pl”;
    $username = “some_user”;
    $password = “some_pass”;
    $title = “My Test Ticket via SOAP and PHP”;
    $from = “me@example.com”;

    # Set up a new SOAP connection:
    $client = new SoapClient(null, array(‘location’ =>
    $url,
    ‘uri’ => “Core”,
    ‘trace’ => 1,
    ‘login’ => $username,
    ‘password’ => $password,
    ‘style’ => SOAP_RPC,
    ‘use’ => SOAP_ENCODED));

    # Create a new ticket. The function returns the Ticket ID.
    $TicketID = $client->__soapCall(“Dispatch”, array($username, $password,
    “TicketObject”, “TicketCreate”,
    “Title”, $title,
    “Queue”, “Postmaster”,
    “Lock”, “Unlock”,
    “PriorityID”, 2,
    “State”, “new”,
    “CustomerUser”, $from,
    “OwnerID”, 1,
    “UserID”, 1,
    ));

    # A ticket is not usefull without at least one article. The function
    # returns an Article ID.
    $ArticleID = $client->__soapCall(“Dispatch”,
    array($username, $password,
    “TicketObject”, “ArticleCreate”,
    “TicketID”, $TicketID,
    “ArticleType”, “webrequest”,
    “SenderType”, “customer”,
    “HistoryType”, “WebRequestCustomer”,
    “HistoryComment”, “created from PHP”,
    “From”, $from,
    “Subject”, $title,
    “ContentType”, “text/plain; charset=ISO-8859-1″,
    “Body”, “This is the body”,
    “UserID”, 1,
    ));

    # Use the Ticket ID to retrieve the Ticket Number.
    $TicketNr = $client->__soapCall(“Dispatch”,
    array($username, $password,
    “TicketObject”, “TicketNumberLookup”,
    “TicketID”, $TicketID,
    ));

    But dont know how can i deal with this code..

    Please help me if you have some idea..

    Thanks,

    Bijal :)

    • Hi Bijal,

      Have you find a standard way to call the Web-services using magento?
      I will appropriate any help regarding this. Waiting for response !!

      Thanks,
      Darshana

      • Moinul Al-Mamun

        Hi Darshana, I have described it in post so far. Please can you check again? Actually what do you need? If it is not satisfy your requirements please can you write details?
        I will try to make it clear.

        Thanks

  17. Hi,i followed the insturction but was getting error on gettting product information so i removed the permission on catalog and just given on customers section and it worked.I hope it will help others.

  18. Thank you for this nice intro, though I have one question about the wsdl file.
    I have created my own API with my own models and methods, but what kind of function will wsdl file have? Why would I create it in my module?
    For example I created new module and have the config.xml and api.xml in my etc folder, is it necessary to put wsdl.xml file too?

  19. Could you give us a post about ‘How to make a magento bridge?’. Please

    • Moinul Al-Mamun

      Hi Key, to make a bridge with magento you can use magento api. If magento api don’t fulfill your requirements then to extend magento api. I am not sure actually what you need. For more details you have to explain your requirements.

      Thanks

      • Hi moinul
        i am new to web services and i am writing service using soap client but
        i am getting one error like this SOAP-ERROR: Parsing WSDL: Couldn’t load from ‘http://192.168.0.77/fincomp/index.php/api/?wsdl=1′ : Couldn’t find end of Start Tag body line 146
        i looked in to magento forum and tried other ways also but i didnt got solution i had been getting erro for past 1 week please can u help on this
        waiting for your reply
        Thanks
        A.Heamnth Sai

  20. Hi,
    I have done all the settings suggested in this article but I don’t know where i have to keep the web service code, in which file copy the above code and how it will work. Please suggest.

  21. Pingback: Customer Export API, Product Export API,Order Export API ,Product Inventory Export, Product Inventory Update API in PHP and XML Tested in Magento 1.5.1.0 | Open Source Rocks

  22. Hi, and thanks
    After adding Role, I want to add user. But the API key and API key confirmation has *(astriks) and I don’t know where to get it.
    best regards
    Emil

  23. how to get the store id of a by magento web service , to retrieve the product.list data specific to store only. please help me im searching and trying for this from whole day but not got the result. :(

  24. acutlay my requirement is , i have retrieve the products list specific to one store by magento web service , for that store id or store view code is needed but iam not able to find it, and after finding that the store id has to pass as to the magento api function available product.list but i dont know how to pass the store id to the argument of that funtion, please help me :(

    like ..
    $storeproduct_array=$client->call($session, 'product.list', 'storeid or storeview id >/b>');

    please tell me how to pass the storeid or storeview code in that function call…

    with best regards,
    yaba

    • Moinul Al-Mamun

      Hello Yaba, for storeId or code contact with your magento administrator or if you have magento admin access then go to System->Manage store. There you will get the store info.
      Thanks !

      • Hi Moinul Al-Mamun, thanks for your reply,

        i have the store id code, but please tell me how to retrieve the products to particular store by store id, how to pass this as argument to the product.list web service function

        i have done like below but dont have luck…

        $storeproduct_array=$client->call($session, 'product.list', 'storeid or storeview id >');

        but didnot get products related to particular store, instead getting all the products of all the store of website.

        please check the code and let me know..

        thanks and regards
        yaba

  25. Aslkm, dear all any body please help me ..iam waiting for the reply for the above post ..

    plaase admin bhai Moinul Al-Mamun, help me regarding this..

  26. Hi Moinul,
    i am new to magento, ur article is good and i want to retrieve user information but i dont know where can i place that code which u hav provided, i mean can u plz tell me the path whr wil i write that code..

    Thanks in advance.

  27. Thank you!! you make Web service & API integration easy @Magento.
    I also love http://www.php-example.com where i am learning Oracle.

    Kelly Blue
    Web Developer, Sydney, Australia

  28. Hello All,
    Is there any one have done Integration With POS?
    Please guide me? How can I achieve the Integration With POS.

    Thanks
    Saleem

  29. Hello,
    I am building a custom front end to Magento, where users selects the products they want to purchase outside of Magento. But then use Magento for the rest.

    I already use the product apis to pull the product_id/sku/name/price out. So I have a list of product_id’s ready for purchase.

    I will use the apis for creating and building a shopping cart.

    My question is…
    Once I build a shopping cart using the apis and have the shoppingcart_id, how do I redirect the user directly into that shopping cart page in Magento?

    Thanks for any help or suggestions.

  30. Is there any web-services written in magento for category and products??
    Regards,
    Rajesh

  31. Hi men, im trying to make a WSDL, to do this i start to found the methods that bring me the info from DB, then i make an array to return all the request info


    $product_data['Id']=$product->getId();
    $product_data['Ref']=$product->getSku();
    $product_data['Weight']=$product->getData(‘weight’);

    return $product_data;

    if i print the request info “print_r( $product_data);”, the info is the necesary but now, i dont know where i have to put the code to create the wsdl …

    Thank`s.

  32. Hello – its a very informative article..

    How i can get all customer list? I also need get all sales data daily basis and stored into the SQL server, i am doing through SSIS – Script component.

    your help is appreciated… regards – Mitesh.

  33. Hi,
    Thanx for the really good article. I have one question.

    I am trying to put filters when I fetch the data like this.

    $result = $proxy->salesOrderList($sessionId, array(‘increment_id’ => array(‘eq’=>’100000004′)));

    but its not working I tried to find the query running for magento but that query is not including the condition increment_id = 100000004 please let me know if is there any other way to do this

    :Pankaj

  34. Assalmo Aleekom ,
    Thank you so much for all these informations :) it really helps.
    i’m new in web services and magento. i need to know steps to update a custom customer attribute using API.
    more details : i made a custom attribute (lap id) in customer registration form ,and i need to update this field using web services , can you guide me pleeeeeease steps to be done.

  35. Hi, I would appreciate if you have a look to this:

    I need to set limit using magento api V2 making soap calls.

    here is an example of my code:
    ———————————————–
    $client = new SoapClient($this->api_soap_url);
    $session_id = $client->__soapCall(‘login’,array(‘user’, ‘password’));

    $data = array($session_id);

    $result = $client->__soapCall(‘customerCustomerList’, $data);
    ———————————————–

    This returns all customers, but don’t know how to set limit here.

    Thanks in advance

  36. I have a simple query,

    I want to pass extra value through web services for particular user for each order item. where to add this code.
    I just want help to locate the file from where the order information or collected and pass through api.

  37. Hi Moinul,

    Thanks for such nice post…
    I’m facing a problem in connecting to V2 API…

    $proxy = new SoapClient(‘http://SERVERIP/test_magento/api/v2_soap/?wsdl=1’);
    $sessionId = $proxy->login(‘admin’, ’12345678′);

    It is not returning me the session ID. even not giving any error also…
    I’m running it in Win server 2008, magento 1.6.1

    what could be the problem… please reply me if you have a solution

    Thanks in advance…

  38. Hi Moinul,
    i use product.list method for retrieving product information, but it only retrieves some attributes. how i get all possible attributes through product.list method

  39. Hi Moinul,
    i use product.list method for retrieving product information, but it only retrieves some attributes. how i get all possible attributes through product.list method. so please suggest what i do????????

  40. Hi Moinul,
    I m new to magento.
    can we call custom api method from phtml file in form action event.
    I want to fetch order status for specified order id.

  41. Hi,
    The SOAP API for Magento 1.4.1 and 1.7 are different.. Some API like store.list, catalog_category.level works fine for 1.7.0 but not working for 1.4.1…. why it is like that??

    How can we find the store_id for all category in case of multistore multiwebsite?
    or
    How can we restrict the list of product using filters? I mean if I want to retrive the first 500 products how to set the filter…???

    Any good tutorial or blog .. pls.. thanks in advance..

  42. Hi !
    How to export data from magento api web service to XML ?

  43. graphicriver retail

    Oh my goodness! Amazing article dude! Thanks, However
    I am having problems with your RSS. I don’t know the reason why I can’t join it.
    Is there anybody getting identical RSS issues? Anyone who knows the
    solution can you kindly respond? Thanks!!

  44. Limo in Dallas

    Right here is the right site for anyone who would like to understand this topic.
    You realize so much its almost tough to argue with you (not
    that I personally would want to…HaHa). You definitely put a brand new spin on a topic that has
    been discussed for decades. Great stuff, just wonderful!

  45. hi
    i am android developer, and i want to connect my app to magento through soap web service. please help me how it heppen.

  46. class ProductClient
    {
    const API_USER = “name”;
    const API_KEY = “password”;
    const SOAP_URL = “http://domain.com/api/v2_soap/?wsdl”;

    protected $client;
    protected $session;

    public function __construct() {
    $this->client = new SoapClient(‘http://domain.com/api/v2_soap/?wsdl’);
    $this->session = $this->client->login($this->API_USER, $this->API_KEY);
    }

    I try to use “self” for thу client and other tips but it got the 1 error –
    “Class ‘SoapClient’ not found”

  47. Hello,

    I want to create customer login web servie through Soap API.
    Please help.

  48. hi,
    how to integrate Magento with other product like sap.

  49. Pingback: Fix Magento Error 500 After Upgrade Windows XP, Vista, 7, 8 [Solved]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s