Combine social media APIs and XML-based data formats

Program to social media provider APIs using XML dialects

Explore the concepts, design, and implementation details pertaining to interacting with social media sites using various APIs and XML-based data formats such as Really Simple Syndication (RSS), Atom, Facebook Markup Language (FBML), OpenSocial Markup Language (OSML), SOAP, and plain old XML (POX).

Share:

J. Jeffrey Hanson, CTO, Max International

Photo of Jeff HansonJeff Hanson has more than 20 years of experience as a software engineer and architect, including working as CTO for Max International, senior architect for Financial Fusion, chief architect for the Zareus SOA platform, and chief architect for eReinsure.com. Jeff has designed and implemented systems for retail banking, global markets, mortgage lending, newspaper publishing, reinsurance, and others. He is a member of the expert group for the Java Management Extensions Remote API specification and a member of the International Association of Software Architects (IASA). Jeff has authored many articles and books for the software industry including Pro JMX, Mashups: Strategies for the Modern Enterprise, and Messaging Technology IASA IT Architect Skills Library.


developerWorks Contributing author
        level

01 December 2009

Also available in Chinese Japanese Portuguese

This article is for developers who seek to understand the social media environment and how to apply XML-based data formats across various APIs. This is of interest because XML-based data is ubiquitous across social media APIs. XML-based data formats help to standardize and simplify the HTTP programming model across heterogeneous sites and services.

Introduction to social media

The term social media refers to sites and services that allow users to share media, content, data, and so on. Some of the more recognizable social media sites and services are LinkedIn, Facebook, Twitter, MySpace, and the vast array of sites and services offered by Google. News media is quickly being transformed to a social media delivery model as well.

Frequently used acronyms

  • API: application program interfaces
  • HTML: Hypertext Markup Language
  • HTTP: Hypertext Transfer Protocol
  • URI: Uniform Resource Identifier
  • URL: Uniform Resource Locator
  • XML: Extensible Markup Language

Social media delivery vehicles include online forums, weblogs, wikis, picture sharing, video sharing, bookmarking, and social activity streams.

XML plays a big role in the exchange of data within the social media community. Social media providers use XML-based dialects extensively in APIs that they provide to enable access to their services.


Introduction to XML-based data formats

XML is a text-based markup language that is used to structure data in many different dialects. XML dialects are defined by schemas that can be embedded within an associated XML document. Most common programming languages provide support for creating, updating, and parsing XML documents.

XML-based dialects are used in a wide variety of Web services. Some of the more common dialects used in Web services include POX, RSS, Atom, and SOAP. Other dialects are emerging with great acceptance. Table 1 lists and describes some of the more common XML-based dialects used in Web services.

Table 1. Common XML-based dialects used in Web services
DialectDescription
SOAP

SOAP originally stood for Simple Object Access Protocol, but it is no longer an acronym. SOAP is an XML-based protocol specification for exchanging structured data within the context of Web services. It was originally intended for Remote Procedure Call (RPC) and document-oriented message exchange. SOAP has evolved in complexity with the introduction of multiple additional specifications defining its format, exchange patterns, transport-level bindings, and so on. This complexity has restricted it from widespread adoption by service providers and social media providers.

RSSRSS stands for Really Simple Syndication or Rich Site Summary. It is an XML-based dialect for structuring data delivered by Web feeds such as blogs, news, and other online data sources. An RSS document allows publishers to syndicate content in a standard and swift manner. RSS consumers use applications on a computer desktop, in a browser, or from a mobile device to retrieve updates from RSS sites automatically at specific intervals. The RSS consumer subscribes to an RSS feed by entering the feed's address into a given RSS reader application.
AtomThe Atom Syndication Format is an XML-based dialect used for Web feeds in much the same manner as RSS. An Atom feed is a bit more comprehensive than RSS in that each Atom element may contain images, external links to content, metadata, and so on.
FBMLFBML stands for Facebook Markup Language. It is a subset of HTML presented by Facebook to allow application developers to build HTML sites that run on Facebook's servers.
OST and OSMLOpenSocial Template (OST) and OpenSocial Markup Language (OSML) are XML- based dialects defined by Google and other members of the OpenSocial network to enable developers to build social media applications and sites using industry-advocated standards and run in OpenSocial-compliant containers. OST and OSML encourage data-driven development of applications and services while promoting a clear separation of concerns between markup and programming logic.

Applying XML data formats to social media APIs

A social media API is a framework of request/response interactions provided by a social media provider that enables third-party sites to build a sites, pages, services, and so on that interact with the social media provider's functionality. eBay, Amazon, Google, Facebook, Twitter, and OpenSocial are a few examples of the providers exposing APIs for building social media applications and services. The following sections illustrate some simple examples of these XML-based APIs.


eBay

eBay provides APIs that allow developers to submit items for listing on eBay, retrieve a current list of eBay categories, view information about items listed on eBay, retrieve high-bidder information for items, retrieve lists of items being sold by a given user, retrieve lists of items on which a given user has bid, display eBay listings on other sites, and leave feedback about sellers.

Retrieving basic user information as an XML document

Listing 1 is an example of an HTTP request that retrieves the default/basic set of information for an eBay user as an XML document.

Listing 1. eBay GetUserProfile
http://open.api.ebay.com/shopping?callname=GetUserProfile
   &responseencoding=XML
   &appid=johndoesAppID
   &siteid=0
   &version=525
   &UserID=johndoesUserID

Listing 2 shows the same request in XML format that can be transmitted using an HTTP POST.

Listing 2. eBay GetUserProfile as XML
<?xml version="1.0" encoding="utf-8"?>
<GetUserProfileRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <UserID>johndoesUserID</UserID>
</GetUserProfileRequest>

Retrieving extended user information as an XML document

To retrieve additional information about a given user, the eBay API provides the IncludeSelector parameter.

Listing 3 is an example of the URL format for an HTTP GET request that retrieves detailed information for a given user.

Listing 3. eBay GetUserProfile with details
http://open.api.ebay.com/shopping?callname=GetUserProfile
   &responseencoding=XML
   &appid=johndoesAppID
   &siteid=0
   &version=525
   &UserID=johndoesUserID
   &IncludeSelector=Details

Listing 4 is the same detailed user-information request in XML format that can be transmitted using an HTTP POST.

Listing 4. eBay GetUserProfile with details as XML
<?xml version="1.0" encoding="utf-8"?>
<GetUserProfileRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <UserID>hypothetical-user</UserID>
  <IncludeSelector>Details</IncludeSelector>
</GetUserProfileRequest>

Listing 5 illustrates an example of a typical response retrieved with the HTTP requests illustrated in Listing 3 and Listing 4. This response includes detailed information about the user.

Listing 5. eBay GetUserProfile response
<?xml version="1.0" encoding="utf-8"?>
<GetUserProfileResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2007-11-09T21:05:05.781Z</Timestamp> 
  <Ack>Success</Ack> 
  <Build>e525_core_APILW_5028523_R1</Build> 
  <Version>525</Version> 
  <User>
    <FeedbackScore>1054</FeedbackScore> 
    <FeedbackPrivate>false</FeedbackPrivate> 
    <FeedbackRatingStar>Red</FeedbackRatingStar> 
    <NewUser>false</NewUser> 
    <RegistrationDate>2005-11-01T20:50:00.000Z</RegistrationDate> 
    <RegistrationSite>US</RegistrationSite> 
    <Status>Confirmed</Status> 
    <SellerBusinessType>Undefined</SellerBusinessType> 
    <UserID>johndoesUserID</UserID> 
    <StoreURL>http://stores.ebay.com/johndoesStore</StoreURL> 
    <StoreName>John Doe's Store</StoreName> 
    <SellerItemsURL>
      http://search.ebay.com/_W0LMsarsrjohndoesUserIDQQhtZ-1
    </SellerItemsURL> 
    <AboutMeURL>http://members.ebay.com/aboutme/johndoesUserID</AboutMeURL> 
    <MyWorldURL>http://myworld.ebay.com/johndoesUserID</MyWorldURL> 
    <MyWorldSmallImage>
      http://i2.ebayimg.ebay.com/01/u/000/00/23/animage.JPG?set_id=34
    </MyWorldSmallImage> 
    <MyWorldLargeImage>
      http://i2.ebayimg.ebay.com/01/u/000/77/23/anotherimage.JPG?set_id=34
    </MyWorldLargeImage> 
    <ReviewsAndGuideURL>
      http://search.reviews.us.ebay.com/members/johndoesUserID
    </ReviewsAndGuideURL> 
    <FeedbackDetailsURL>
      http://feedback.ebay.com?ViewFeedback&userid=johndoesUserID&...
    </FeedbackDetailsURL> 
  </User>
</GetUserProfileResponse>

Retrieving basic user information as a SOAP envelope

Listing 6 illustrates an example of an eBay API HTTP request that retrieves the basic of information for a user given as a SOAP request.

Listing 6. eBay GetUserProfile requesting SOAP response
http://open.api.ebay.com/shopping?callname=GetUserProfile
   &responseencoding=SOAP
   &appid=johndoesAppID
   &siteid=0
   &version=525
   &UserID=johndoesUserID
   &IncludeSelector=Details

Listing 7 shows the same eBay API request for detailed user information as a SOAP envelope.

Listing 7. eBay GetUserProfile request as a SOAP envelope
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope
  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <GetUserProfileRequest xmlns="urn:ebay:apis:eBLBaseComponents">
      <UserID>johndoesUserID</UserID>
      <IncludeSelector>Details</IncludeSelector>
    </GetUserProfileRequest>
  </soapenv:Body>
</soapenv:Envelope>

Listing 8 shows the detailed user-information response returned as a SOAP envelope.

Listing 8. eBay GetUserProfile SOAP response
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope
  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <GetUserProfileResponse xmlns="urn:ebay:apis:eBLBaseComponents">
      <Timestamp>2009-11-09T20:01:05.781Z</Timestamp> 
      <Ack>Success</Ack> 
      <Build>e525_core_APILW_5028523_R1</Build> 
      <Version>525</Version> 
      <User>
        <FeedbackScore>1047</FeedbackScore> 
        <FeedbackPrivate>false</FeedbackPrivate> 
        <FeedbackRatingStar>Red</FeedbackRatingStar> 
        <NewUser>false</NewUser> 
        <RegistrationDate>2009-10-12T10:10:00.000Z</RegistrationDate> 
        <RegistrationSite>US</RegistrationSite> 
        <Status>Confirmed</Status> 
        <SellerBusinessType>Undefined</SellerBusinessType> 
        <UserID>johndoesUserID</UserID> 
        <StoreURL>http://stores.ebay.com/johndoesStore</StoreURL> 
        <StoreName>John Does Store</StoreName> 
        <SellerItemsURL>
          http://search.ebay.com/_W0LMsarsrjohndoesUserIDQQhtZ-1
        </SellerItemsURL> 
        <AboutMeURL>http://members.ebay.com/aboutme/johndoesUserID</AboutMeURL>
        <MyWorldURL>http://myworld.ebay.com/johndoesUserID</MyWorldURL> 
        <MyWorldSmallImage>
          http://i2.ebayimg.ebay.com/01/u/000/00/23/animage.JPG?set_id=23
        </MyWorldSmallImage> 
        <MyWorldLargeImage>
          http://i2.ebayimg.ebay.com/01/u/000/77/23/anotherimage.JPG?set_id=23
        </MyWorldLargeImage> 
        <ReviewsAndGuideURL>
          http://search.reviews.us.ebay.com/members/johndoesUserID
        </ReviewsAndGuideURL> 
        <FeedbackDetailsURL>
          http://feedback.ebay.com/ws?ViewFeedback&userid=johndoesUserID&...
        </FeedbackDetailsURL> 
      </User>
    </GetUserProfileResponse>
  </soapenv:Body>
</soapenv:Envelope>

Amazon

Amazon provides a number of Web service APIs—conveniently referred to as Amazon Web Services—to expose functionality for accessing Amazon's infrastructure of services. These services include, but are not limited to, those listed and described in Table 2.

Table 2. Some of the Amazon Web services
ServiceDescription
Elastic Compute Cloud (EC2)A Web service that provides resizable compute capacity in the cloud
Simple Storage Service (S3)A simple Web services interface that you can use to store and retrieve large amounts of data, at any time, from anywhere on the Web
CloudFrontA Web service for content delivery
SimpleDBA Web service for running queries on structured data in the cloud
Simple Queue Service (SQS)A cloud-hosted queue for moving messages between distributed applications
E-Commerce Service (ECS)Provides facilities to create Web sites or applications that integrate ECS with other Amazon services for retrieving product data, content from customers, seller information, product listings, shopping carts, and so on

Retrieving public user information as an XML document

The following example uses Amazon ECS services to retrieve public information about a given customer. This API requires that each request is authenticated using a request signature. A request signature is created by base-64-encoding the request type, domain, the URI, and a sorted string of every parameter in the request using an Amazon Web Service secret key.

Listing 9 is an example of a typical signed request for an Amazon ECS API request.

Listing 9. Amazon CustomerContentSearch request
http://webservices.amazon.com/onca/xml?
Service=AWSECommerceService
&AWSAccessKeyId=johndoesAccessKeyID
&AssociateTag=johndoesAssociateID
&Operation=CustomerContentSearch
&Name=Jane%20Doe

You can create the signed request in Listing 9 using the following steps:

  1. Append the timestamp to the URL:
    http://ecs.amazonaws.com/onca/xml?
    Service=AWSECommerceService
    &AWSAccessKeyId=johndoesAccessKeyID
    &AssociateTag=johnDoesAssociateID
    &Operation=CustomerContentSearch
    &Name=Jane%20Doe
  2. URL encode the request.

    To URL-encode a request means to convert the request string to valid URL format by converting non-URL-compliant characters to URL-compliant characters. Most programming languages have standard libraries and/or functions to do this. For a complete explanation of URL encoding, see Resources.

  3. Extract the query parameters and remove the ampersand characters (&):
    Service=AWSECommerceService
    AWSAccessKeyId=johndoesAccessKeyID
    AssociateTag=johnDoesAssociateID
    Operation=CustomerContentSearch
    Name=Jane%20Doe
  4. Sort the query parameters by ASCII byte value:
    AssociateTag=johnDoesAssociateID
    AWSAccessKeyId=johndoesAccessKeyID
    Name=Jane%20Doe
    Operation=CustomerContentSearch
    Service=AWSECommerceService
  5. Reconnect the sorted list of query parameters with ampersands (&). The result is a canonical string:
    AssociateTag=johnDoesAssociateID
    &AWSAccessKeyId=johndoesAccessKeyID
    &Name=Jane%20Doe
    &Operation=CustomerContentSearch
    &Service=AWSECommerceService
  6. Prepend the request type header with line breaks to the canonical string:
    GET
    ecs.amazonaws.com
    /onca/xml

The string that is to be signed will look similar to Listing 10.

Listing 10. Amazon CustomerContentSearch signature string
GET
ecs.amazonaws.com
/onca/xml
AssociateTag=johnDoesAssociateID
&AWSAccessKeyId=johndoesAccessKeyID
&Name=Jane%20Doe
&Operation=CustomerContentSearch
&Service=AWSECommerceService

HMAC and SHA-256

Hash-based Message Authentication Code (HMAC) is a cryptographic mechanism used for message authentication using a hash function in combination with a secret key.

Secure Hash Algorithm 256 (SHA-256) is a 32-bit cryptographic hash function that is used in message authentication to validate the authenticity of a block of data.

For more information, see Resources.

Now, create a Request for Comments (RFC) 2104-compliant HMAC code from the string in Listing 10 using SHA-256 and your Amazon Secret Access Key. The signed string will look similar to Listing 11.

Listing 11. Amazon CustomerContentSearch signed string
Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg=

Now, URL encode the signature, as in Listing 12.

Listing 12. Amazon CustomerContentSearch signed and encoded string
Nace%2BU3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg%3D

The URL-encoded signature is then appended to the URL for the API request, as in Listing 13.

Listing 13. Amazon CustomerContentSearch request with signature
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService
   &AWSAccessKeyId=johndoesAccessKeyID
   &AssociateTag=johnDoesAssociateID
   &Name=Jane%20Doe
   &Operation=CustomerContentSearch

The amount of information retrieved by CustomerContentSearch is determined by the response groups specified in the request and the data made available by the customer. Listing 14 is a typical response that includes a complete set of XML customer data.

Listing 14. Amazon CustomerContentSearch XML response
<CustomerContentSearchResponse
  xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
  <OperationRequest>
    <HTTPHeaders>
      <Header Name="UserAgent" Value="Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) 
AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.27 Safari/532.0"></Header>
    </HTTPHeaders>
    <RequestId>0RXAHS524460FBBFDMGJ</RequestId>
    <Arguments>
      <Argument Name="Service" Value="AWSECommerceService"></Argument>
      <Argument Name="Name" Value="Jane Doe"></Argument>
      <Argument Name="Operation" Value="CustomerContentSearch"></Argument>
      <Argument Name="AssociateTag" Value="johnDoesAssociateID"></Argument>
      <Argument Name="Signature" 
Value="SOWM2hnR8zF5b9tyXQEsO0oG0crM7rbSwy1QL7UDfT0="></Argument>
      <Argument Name="AWSAccessKeyId" Value="johndoesAccessKeyID"></Argument>
    </Arguments>
    <RequestProcessingTime>0.104732990264893</RequestProcessingTime>
  </OperationRequest>
  <Customers>
    <Request>
      <IsValid>True</IsValid>
      <CustomerContentSearchRequest>
        <Name>Jane Doe</Name>
      </CustomerContentSearchRequest>
    </Request>
    <TotalResults>1</TotalResults>
    <TotalPages>1</TotalPages>
    <Customer>
      <CustomerId>janedoesCustomerID</CustomerId>
    </Customer>
  </Customers>
</CustomerContentSearchResponse>

Retrieving public user information as a SOAP envelope

Amazon SOAP requests specify request endpoints by locale and whether or not the request is to be made over a secure connection. The SOAP endpoints listed in Table 3 are available to use for Amazon Product Advertising API SOAP requests.

Table 3. Amazon Web Services SOAP endpoints
LocaleEndpoint
CAhttp://ecs.amazonaws.ca/onca/soap
https://aws.amazonaws.ca/onca/soap
DEhttp://ecs.amazonaws.de/onca/soap
https://aws.amazonaws.de/onca/soap
FRhttp://ecs.amazonaws.fr/onca/soap
https://aws.amazonaws.fr/onca/soap
JPhttp://ecs.amazonaws.jp/onca/soap
https://aws.amazonaws.jp/onca/soap
UKhttp://ecs.amazonaws.co.uk/onca/soap
https://aws.amazonaws.co.uk/onca/soap
UShttp://ecs.amazonaws.com/onca/soap
https://aws.amazonaws.com/onca/soap

Listing 15 illustrates an example of a SOAP envelope that is passed to a call to the Amazon ItemSearch operation.

Listing 15. Amazon CustomerContentSearch response as SOAP
<?xml version="1.0" encoding="UTF-8" ?>
<soapenv:Envelope
     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <ItemSearch xmlns="http://ecs.amazonaws.com/AWSECSCommerce/onca/soap">
      <AWSAccessKeyId>johndoesAccessKeyID</AWSAccessKeyId>
      <Request>
        <SearchIndex>Books</SearchIndex>
        <Keywords>Lord%20of%20the%20Rings</Keywords>
      </Request>
    </ItemSearch>
  </soapenv:Body>
</soapenv:Envelope>

Google

Google exposes a comprehensive array of online services that are enabled with Web service APIs. Most of these APIs are enabled with an XML-based request/response format. Google Apps is one example of a Google service that enables XML-based interactions within the confines of the Google infrastructure.

Authenticating an API request

Many Google services require authorized access before information can be exchanged. One mechanism that is used is an API referred to as the ClientLogin API. Access provided under the authorization of the ClientLogin API involves a token issued by Google that can be used in all subsequent requests.

Listing 16 illustrates a request to Google for a ClientLogin token.

Listing 16. Google ClientLogin request
https://www.google.com/accounts/ClientLogin?
accountType=HOSTED_OR_GOOGLE
&Email=johndoe@example.com
&Passwd=foobar
&service=apps
&source=mytestapp

A successful response from the request in Listing 16 results in a response similar to Listing 17.

Listing 17. Google ClientLogin response
SID=ABCDE...
LSID= ABCDE...
Auth= ABCDE...

For the purposes of this article, you can ignore two of the codes illustrated in the response in Listing 17: SID and LSID. The Auth value, however, is the authorization token that you can use in subsequent Google API requests.

Secured API requests require the Authorization header to be set with the token returned from a successful ClientLogin response, as in Listing 18.

Listing 18. Google authorization header for secured Google API request
Authorization: GoogleLogin auth=ABCDE...

Retrieving user profile information as an Atom feed

cURL

cURL is a command-line tool for performing online requests with URL syntax, with support for FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS, and others. cURL also supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form-based upload, proxies, cookies, user+password authentication and so on.

Google Apps provides user profile information in a profile feed. You can use a profile feed to view and modify profiles of users associated with a Google Apps account. Profile feeds are retrieved using the Profiles Data API.

Listing 19 illustrates an example of a standard HTTP GET request to retrieve the profile for a Google Apps user, johndoe@example.com. The request is transmitted as a cURL command line and passes a previously retrieved authentication token.

Listing 19. Google retrieve user profile feed request
curl -k --header "Authorization: GoogleLogin auth=ABCDE..." \
https://apps-apis.google.com/a/feeds/example.com/user/2.0/johndoe

The preceding cURL command includes the Auth token returned from a previous successful ClientLogin request. Upon successful execution of this command, an Atom entry similar to the example in Listing 20 should be returned.

Listing 20. Google retrieve user profile Atom feed response
<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
       xmlns:apps='http://schemas.google.com/apps/2006'
       xmlns:gd='http://schemas.google.com/g/2005'>
  <id>https://apps-apis.google.com/a/feeds/example.com/user/2.0/johndoe</id>
  <updated>1970-01-01T00:00:00.000Z</updated>
  <category
    scheme='http://schemas.google.com/g/2005#kind'
    term='http://schemas.google.com/apps/2006#user'/>
  <title type='text'>John Doe</title>
  <link
    rel='self'
    type='application/atom+xml'
    href='https://apps-apis.google.com/a/feeds/example.com/user/2.0/johndoe'/>
  <link
    rel='edit'
    type='application/atom+xml'
    href='https://apps-apis.google.com/a/feeds/example.com/user/2.0/johndoe'/>
  <apps:login
    userName='johndoe'
    suspended='false'
    ipWhitelisted='false'
    admin='true'
    changePasswordAtNextLogin='false'
    agreedToTerms='true'/>
  <apps:quota limit='7168'/>
  <apps:name familyName='Doe' givenName='John'/>
  <gd:feedLink
    rel='http://schemas.google.com/apps/2006#user.nicknames'
    href='https://apps-
apis.google.com/a/feeds/example.com/nickname/2.0?username=johndoe'/>
  <gd:feedLink
    rel='http://schemas.google.com/apps/2006#user.emailLists'
    href='https://apps-
apis.google.com/a/feeds/example.com/emailList/2.0?recipient=johndoe%example.com'/>
</entry>

Retrieving user profile information as an RSS feed

You can parameterize many of the Google APIs to return RSS as the result format. This typically involves setting one parameter on the input request.

To retrieve the same profile for johndoe@example.com as an RSS item using cURL, execute the command line in Listing 21.

Listing 21. Google retrieve user profile RSS feed request
curl -k --header "Authorization: GoogleLogin auth=ABCDE..." \
https://apps-apis.google.com/a/feeds/example.com/user/2.0/johndoe?alt=rss

Upon success of the preceding cURL command, an RSS entry similar to Listing 22 should be returned as the response.

Listing 22. Google retrieve user profile RSS feed response
<?xml version='1.0' encoding='UTF-8'?>
<item xmlns:atom='http://www.w3.org/2005/Atom'
      xmlns:apps='http://schemas.google.com/apps/2006'
      xmlns:gd='http://schemas.google.com/g/2005'>
  <guid isPermaLink='false'>
    https://apps-apis.google.com/a/feeds/example.com/user/2.0/johndoe
  </guid>
  <atom:updated>1970-01-01T00:00:00.000Z</atom:updated>
  <category domain='http://schemas.google.com/g/2005#kind'>
    http://schemas.google.com/apps/2006#user
  </category>
  <title>John Doe</title>
  <apps:login
    userName='johndoe'
    suspended='false'
    ipWhitelisted='false'
    admin='true'
    changePasswordAtNextLogin='false'
    agreedToTerms='true'/>
  <apps:quota limit='7168'/>
  <apps:name familyName='Doe' givenName='John'/>
  <gd:feedLink
    rel='http://schemas.google.com/apps/2006#user.nicknames'
    href='https://apps-
apis.google.com/a/feeds/example.com/nickname/2.0?username=johndoe'/>
  <gd:feedLink
    rel='http://schemas.google.com/apps/2006#user.emailLists'
    href='https://apps-
apis.google.com/a/feeds/example.com/emailList/2.0?recipient=johndoe%40example.com'/>
</item>

Facebook

Facebook released the Facebook Platform to enable developers to create applications that allow users to share information and stay connected. Applications that run on Facebook can be constructed using the FBML markup language described earlier in Table 1.

Login button page using FBML

Facebook provides FBML as a mechanism for building pages that interact with Facebook services and data. The FBML-enabled page in Listing 23 constructs a login button that authenticates a user to the Facebook platform. You can embed this button in any HTML page.

Listing 23. FBML-enabled page
<html>
<head>
<title>test</title>
</head>
<body>
<script
src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US"
type="text/javascript">
</script>
<script type="text/javascript">
  FB.init("ff60291faf5de5c350fab4d4cc84b9cb");
</script>
 
 <fb:login-button length="short" size="medium"></fb:login-button>
 <br/>
 <fb:profile-pic uid="loggedinuser" size="square" facebook-logo="true">
 </fb:profile-pic>
 <br/> 
 <fb:name uid="loggedinuser" useyou="false" linked="true"></fb:profile-pic>
 <br/> 
 <div id="profile_pics"></div>
<script type="text/javascript">
var widget_div = document.getElementById("profile_pics");
FB.ensureInit(function () {
  FB.Facebook.get_sessionState().waitUntilReady(function() {
  FB.Facebook.apiClient.friends_get(null, function(result) {
    var markup = "";
    var num_friends = result ? Math.min(5, result.length) : 0;
    if (num_friends > 0) {
      for (var i=0; i<num_friends; i++) {
        markup += 
          '<fb:profile-pic
             size="square"
             uid="'+result[i]+'"
             facebook-logo="true"></fb:profile-pic>';
      }
    }
    widget_div.innerHTML = markup;
    FB.XFBML.Host.parseDomElement(widget_div);
  });
  });
});
</script>
</body>
</html>

The rendered response for parsing of the FBML form in Listing 23 is illustrated in Figure 1.

Figure 1. FBML-rendered response
Screen capture of FBML-rendered response that shows the Facebook login button page

Login button page using XFBML

Facebook has presented XFBML as a subset of FBML that allows FBML-based pages to be incorporated in an HTML page using Facebook Connect or for using FBML within an iframe.

Listing 24 constructs a login button that authenticates a user to the Facebook Connect platform. You can embed this button in any HTML page.

Listing 24. XFBML-enabled page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>test</title>
</head>
<body>
 <script 
src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US" 
type="text/javascript"></script>
 <fb:login-button></fb:login-button>
 <script type="text/javascript">  FB.init("ff60291faf5de5c350fab4d4cc84b9cb", 
"xd_receiver.htm"); </script>
</body>
</html>

The rendered response for parsing of the XFBML form in Listing 24 is illustrated in Figure 2.

Figure 2. XFBML-rendered response
Screen capture of XFBML-rendered response that shows the Facebook login button

Twitter

REST

Representational State Transfer (REST) is a software architecture and conversation model for distributed systems. The term Representational State Transfer was introduced and defined by Roy Fielding (one of the authors of the Hypertext Transfer Protocol versions 1.0 and 1.1) in his doctoral dissertation. See Resources for more information.

Twitter's presence is becoming pervasive across the Web. This is, in large part, due to the ease with which Twitter offers its services to developers through its APIs. Twitter's APIs are REST-based and can return results as XML, JavaScript Serialized Object Notation (JSON), RSS, and Atom feed formats.

Retrieving the Twitter public timeline as an RSS feed

Twitter allows you to retrieve API responses in many formats, including RSS. Listing 25 illustrates an example of a Twitter API request that retrieves the public timeline from Twitter as an RSS feed using a using cURL command line.

Listing 25. Twitter public timeline request
curl http://twitter.com/statuses/public_timeline.rss

Upon success of the preceding cURL command, an RSS feed similar to the example in Listing 26 should be returned as the response.

Listing 26. Twitter public timeline response
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>Twitter public timeline</title>
    <link>http://twitter.com/public_timeline</link>
    <atom:link type="application/rss+xml" 
href="http://twitter.com/statuses/public_timeline.rss" rel="self"/>
    <description>Twitter updates from everyone!</description>
    <language>en-us</language>
    <ttl>40</ttl>
  <item>
    <title>Here is a tweet title</title>
    <description>Here is a tweet description</description>
    <pubDate>Tue, 10 Nov 2009 18:28:16 +0000</pubDate>
    <guid>http://twitter.com/astrogerly/statuses/1234567890</guid>
    <link>http://twitter.com/astrogerly/statuses/1234567890</link>
  </item>
  <item>
    <title>Here is another tweet title</title>
    <description>Here is another tweet description</description>
    <pubDate>Tue, 9 Nov 2009 14:32:11 +0000</pubDate>
    <guid>http://twitter.com/astrogerly/statuses/6789012345</guid>
    <link>http://twitter.com/astrogerly/statuses/6789012345</link>
  </item>
  ...
  </channel>
</rss>

Retrieving a friend's timeline as XML

Twitter APIs can return results as plain old XML, if needed. You accomplish this by adding xml to the end of the request URL.

Some APIs require authentication before they can be accessed. The authentication is a simple username/password pair passed along with the request.

To retrieve the timeline for a given user's Twitter friends as XML using cURL, execute the command line in Listing 27.

Listing 27. Twitter friend's timeline request
curl -u johndoe:johndoespassword http://twitter.com/statuses/friends_timeline.xml

Note the username:password pair in the command line for the API in Listing 27.

On success of the preceding cURL command, an XML document similar to the example in Listing 28 should be returned as the response.

Listing 28. Twitter friend's timeline response
<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array">
  <status>
    <created_at>Tue Nov 10 16:50:40 +0000 2009</created_at>
    <id>1234567890</id>
    <text>Tweet shown here</text>
    <source>web</source>
    <user>
      <id>7654321</id>
      <name>atwitterusername</name>
      <screen_name>atwitterscreenname</screen_name>
      <location>Worldwide...</location>
      <description>User description</description>
      ...
    </user>
  </status>
  <status>
    <created_at>Tue Nov 9 14:33:22 +0000 2009</created_at>
    <id>1234567890</id>
    <text>Another tweet shown here</text>
    <source>web</source>
    <user>
      <id>1234567</id>
      <name>anothertwitterusername</name>
      <screen_name>anothertwitterscreenname</screen_name>
      <location>Worldwide...</location>
      <description>Another user description</description>
      ...
    </user>
  </status>
  ...
</statuses>

Retrieving the Twitter public timeline as an Atom feed

Twitter APIs can return results in Atom format as well. Again, you accomplish this by adding "atom" to the end of the request URL, as shown in the cURL command line in Listing 29.

Listing 29. Twitter public timeline as Atom feed request
curl http://twitter.com/statuses/public_timeline.atom

On success of the preceding cURL command, an Atom feed similar to Listing 30 should be returned as the response.

Listing 30. Twitter public timeline as Atom feed response
<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <title>Twitter public timeline</title>
  <id>tag:twitter.com,2007:Status</id>
  <link type="text/html"
        href="http://twitter.com/public_timeline"
        rel="alternate"/>
  <link type="application/atom+xml"
        href="http://twitter.com/statuses/public_timeline.atom"
        rel="self"/>
  <updated>2009-11-10T18:48:25+00:00</updated>
  <subtitle>Twitter updates from everyone!</subtitle>
    <entry>
      <title>username: @Here is a tweet</title>
      <content type="html">username: @Here is a tweet</content>
      <id>
        tag:twitter.com,2007:http://twitter.com/username/statuses/1234567890
      </id>
      <published>2009-11-10T18:48:25+00:00</published>
      <updated>2009-11-10T18:48:25+00:00</updated>
      <link type="text/html"
            href="http://twitter.com/username/statuses/1234567890"
            rel="alternate"/>
      <link type="image/jpeg"
            href="http://a3.twimg.com/profile_images/1234567890/userimage.JPG"
            rel="image"/>
      <author>
        <name>User Name</name>
      </author>
    </entry>
    <entry>
      <title>anotherusername: @Here is another tweet</title>
      <content type="html">anotherusername: @Here is another tweet</content>
      <id>
        tag:twitter.com,2007:http://twitter.com/anotherusername/statuses/6789012345
      </id>
      <published>2009-11-09T16:42:15+00:00</published>
      <updated>2009-11-09T16:42:15+00:00</updated>
      <link type="text/html"
            href="http://twitter.com/anotherusername/statuses/6789012345"
            rel="alternate"/>
      <link type="image/jpeg"
            href="http://a3.twimg.com/profile_images/6789012345/userimage.JPG"
            rel="image"/>
      <author>
        <name>Anotheruser Name</name>
      </author>
    </entry>
</feed>

OpenSocial

OpenSocial is a consortium of organizations (Google, MySpace, and others) seeking to define common APIs and markup languages for building social media applications and services. The primary markup languages defined by the OpenSocial group are OpenSocial Markup Language (OSML) and OpenSocial Template (OST).

Declarative markup with OST

OST is a declarative markup language designed for gadget developers to enable them to create reusable templates that can be used to build data-driven applications and sites. An OST implementation parses and executes OST code before it ever reaches a client's browser. This process allows data to be retrieved, stored, injected, and so on prior to rendering within a browser.

Using OSML within OST

OSML defines a set of tags that every OpenSocial-compliant container can parse and render. OSML tags within an OST page are used to retrieve data such as a user's profile information, friend lists, and so on.

Retrieving a user's friends with OST/OSML

The example of an OST/OSML gadget in Listing 31 illustrates use of the OSML PeopleRequest tag to retrieve a user's friends. The userId attributes userId and groupId specify which list of friends to retrieve. The list of friends is then rendered by the OST container as the page executes.

Listing 31. OpenSocial OST/OSML gadget
<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs title="Server-side Template">
    <Require feature="opensocial-data" />
    <Require feature="opensocial-templates">
    </Require>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[      
      <script xmlns:os="http://ns.opensocial.org/2008/markup" type="text/os-data">
        <os:PeopleRequest key="friends" userId="@viewer" groupId="@friends"/>
      </script>
 
      <script type="text/os-template">
        <ul>
          <li repeat="${friends}">
            <span id="id${Context.Index}">${Cur.name.givenName}</span>
          </li>
        </ul>
     </script>
    ]]>
  </Content>
</Module>

Summary

Social media is quickly becoming a wave of technology, techniques, and APIs that allow users to share content, media, and more. You certainly don't want to ignore it. Social media is prevalent on sites such as LinkedIn, Facebook, Twitter, and many different sites and services offered by Google.

In this article, you reviewed the concepts, design, and implementation details pertaining to interacting with social media sites using various APIs and XML-based data formats such as RSS, Atom, FBML, OSML, SOAP, and simple XML.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Open source
ArticleID=449418
ArticleTitle=Combine social media APIs and XML-based data formats
publish-date=12012009