Tuesday, October 30, 2012

Calling Apex web service - something additional to developer force apex quick start guide

In Apex code quick start guide from developer force, there's examples about the Book customized object. However, it's not clearly described about how to invoke a web service built with Apex.
Here I'll continue using the Book object as an example and explain how to call such web service with soapUI.
1. Create a web service for the Book example:
global class BookWebService{
    webService static Id createBook(String name, Decimal price){
        Book__c book=new Book__c(Name=name,Price__c=price);
        insert book;
        return book.Id;
    }
}
2. Generate wsdl from the BookWebService class, and save it locally.
3. Generate partner wsdl from Develop --> API page, and save it locally.
4. In SoapUI, create a project by adding the above 2 wsdls.
5. Invoke login operation based on the partner wsdl with the credential to SFDC.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com">
   <soapenv:Header>
   </soapenv:Header>
   <soapenv:Body>
      <urn:login>
         <urn:username>zzzzzzzzzzz</urn:username>
         <urn:password>xxxxxxxxxxx</urn:password>
      </urn:login>
   </soapenv:Body>
</soapenv:Envelope>

6. Copy the sessionid from the response and make the input for the createBook web service:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:book="http://soap.sforce.com/schemas/class/BookWebService">
   <soapenv:Header>
      <book:AllowFieldTruncationHeader>
         <book:allowFieldTruncation>true</book:allowFieldTruncation>
      </book:AllowFieldTruncationHeader>
      <book:SessionHeader>
         <book:sessionId>00DE0000000adhV!ARQAQLsTZiERi36QEprxQx0F_xI826qAM9W4AQNwCdMnKO18GIrjijaRIvjFsnxYF148Rr_4EFknbzjwerkFhW7enghQPRCN</book:sessionId>
      </book:SessionHeader>
   </soapenv:Header>
   <soapenv:Body>
      <book:createBook>
         <book:name>Book Test</book:name>
         <book:price>100.10</book:price>
      </book:createBook>
   </soapenv:Body>
</soapenv:Envelope>

7. Invoke the web service, and get the following response:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:book="http://soap.sforce.com/schemas/class/BookWebService">
   <soapenv:Header>
      <book:AllowFieldTruncationHeader>
         <book:allowFieldTruncation>true</book:allowFieldTruncation>
      </book:AllowFieldTruncationHeader>
      <book:SessionHeader>
         <book:sessionId>00DE0000000adhV!ARQAQLsTZiERi36QEprxQx0F_xI826qAM9W4AQNwCdMnKO18GIrjijaRIvjFsnxYF148Rr_4EFknbzjwerkFhW7enghQPRCN</book:sessionId>
      </book:SessionHeader>
   </soapenv:Header>
   <soapenv:Body>
      <book:createBook>
         <book:name>Book Test</book:name>
         <book:price>100.10</book:price>
      </book:createBook>
   </soapenv:Body>
</soapenv:Envelope>

8. Query SFDC with the returned Id:


No comments: