PHP Web APIS
Web Services
- Collection of protocols that are used to exchange data between disparate applications or systems.
- The essence of web services is the open standards on which they are built, by leveraging public and common protocols like HTTP, along with the XML document model.
- Web services are easy to implement with existing technologies.
Why WebServices Are Used
- Web services allow information to easily pass from webserver to the Requestors.
- Web services allow customers to access the information they desire, without the extraneous information generally presented on web pages.
- Webservices allow the requestor to obtain information from the service, regardless of the information type.
- Webservers can either provide or accept information.
- Web services can provide any level of security, from a completely open service open to all who request it, to a private service.
Introduction to Web APIs
- APIs are the programs to provide information depending on the request
- APIs receives a request based on the information and then it returns a result.
- From an object-oriented (OO) standpoint, dealing with an API is much like dealing with a class
- The two most popular web APIs are
- REST (Representational State Transfer )
- SOAP (Simple Object Access Protocol)
REST (Representational State Transfer)
- A REST request will involve sending a request to a special URL (similar to what you would see after filling out a form using the GET method), then receiving an XML document containing the server's response. The XML response is then parsed, and the desired information is extracted Each REST request generally has several common elements:
- Endpoint URL — The full address for the desired script. A REST service might have only a single script that handles all request types, or different scripts for different request types.
- Developer ID — Most REST services require some sort of developer ID or key to be sent with each request. This identifies the origin of the request and is generally used for tracking purposes. Some services may use this value to limit the number of queries run during a given time frame.
- Desired action — Few servers have a unique endpoint for all possible requests. As such, it is generally required to include the desired action in the request.
- Parameters — Several parameters will need to be included with the request to provide the requested action with some context (for example, the desired action might be a search; the parameters might be a type, and the keywords values of book and style).
CURL (Client URL Library)
- This library is created by Daniel Stenberg
- This allows you to connect and communicate to many different types of servers with many different types of protocols.
- Libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols.
- Libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
CURL Functions
- curl_init — Initialize a cURL session
Syn: curl_init()
- curl_exec — Perform a cURL session
Syn: curl_exec(curlsessionvariable)
- curl_error — Return a string containing the last error for the current session
Syn: curl_error(curlsessionvariable)
- curl_close — Close a cURL session
Syn: curl_close(curlsessionvariable)
- curl_setopt — Set an option for a cURL transfer
Syn: bool curl_setopt ( resource $ch, int $option, mixed $value )
CURLOPT_HEADER TRUE to include the header in the output.
CURLOPT_RETURNTRANSFER TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
Sample code to send request and parsing the XML format response
$session = curl_init($request)
curl_setopt($session, CURLOPT_HEADER, false)
curl_setopt($session, CURLOPT_RETURNTRANSFER, true)
$response = curl_exec($session) curl_close($session)
$parsed_xml = simplexml_load_string($response)
Interacting with the Amazon API
- Amazon's API offers great flexibility and a possible revenue stream for a site owner.
- This allows site owners to not only present their visitors with relevant products and cross promotions, but also to receive some money for their troubles.
Prerequisites
You must have a valid Amazon Web Services developer account. (You can create one here : http://aws.amazon.com)
Amazon Web Services
- Infrastructure Services
- a)Amazon Elastic Compute Cloud (Amazon EC2)
- b)Amazon SimpleDB
- c)Amazon Simple Storage Service (Amazon S3)
- d)Amazon CloudFront
- e)Amazon Simple Queue Service (Amazon SQS)
- f)AWS Premium Support
- Payments & Billing Services
- Amazon Flexible Payments Service (Amazon FPS)
- Amazon DevPay
- On-Demand Workforce
- Web Search & Information Services
- Alexa Web Search
- Alexa Web Information Service
- Alexa Top Sites
- Alexa Site Thumbnail
- Amazon Fulfillment & Associates
- Amazon Fullfillment Webservice
- Amazon Associates Webservice
Amazon Associates Web Service
- The Amazon Associates Web Service allows you to advertise millions of new and used products more efficiently on your web site, while earning referral fees
- This is a powerful tool to help Amazon Associate website owners and developers to make money
- Associates can now easily build rich and highly effective applications that advertise Amazon products and earn referral fees for driving traffic back to Amazon’s web sites or sales of Amazon products and services.
Service Highlights
- Make money from relevant Amazon products on your web site. Earn up to 8.5% in product referral fees on select products when your visitors click through to Amazon and purchase Amazon products advertised on your site.
- Advertise millions of new and used items in categories such as books, movies, music & games, digital downloads, electronics & computers, home & garden, toys, kids & baby, grocery, apparel, shoes & jewelry, health & beauty, sports & outdoors, and tools, auto & industrial.Access product data from Amazon.com, Amazon.fr, Amazon.ca, Amazon.de, Amazon.jp, and Amazon.co.uk
- Retrieve detailed product information, including prices, images, customer reviews, and more.
Request Parameters to integrate amazon API
- Service
- AWSAccessKeyId
- AssociateTag
- Version
- Operation
- ResponseGroup
- SearchIndex
- Keywords
- Service
Specifies the type of service
Ex: AWSECommerceService.
- AWSAccessKeyId
Specifies the developer AccessKeyId
Ex: 1ERM7K5EFJXVPXCE5C82
- AssociateTag
Specifies the AssociateTag.
Ex: test03fd-20
- Version
Specifies version of the Amazon API
Ex: 2007-10-29
- Operation Parameter
Specifies different operations related to search an item, view item details, Adding an item to the shopping cart, Removing item from the cart etc.
ItemSearch --- Search the product database using a one of a variety of possible criteria.
ItemLookup --- Look up specific product(s) in the Amazon database.
CartCreate --- Create a shopping cart and add an item(s).
CartAdd --- Add products to the shopping cart.
CartModify --- Change quantities or status of entries in the shopping cart.
CartGet --- Get the contents of a shopping cart with updated price and availability information.
Response Group Parameter
Response groups are data sets that can be returned by Amazon E-Commerce Service (ECS). They allow you to tailor your requests to return only the data you need.
List of Valid Response Groups
| Accessories |
BrowseNodeInfo |
BrowseNodes |
Cart |
| CartNewReleases |
CartTopSellers |
CartSimilarities |
CustomerFull |
| CustomerInfo |
CustomerLists |
CustomerReviews |
EditorialReview |
| Help |
Images |
ItemAttributes |
ItemIds |
| Large |
ListFull |
ListInfo |
ListItems |
| ListmaniaLists |
ListMinimum |
Medium |
NewReleases |
| OfferFull |
Offers |
OfferSummary |
Request |
| Reviews |
SalesRank |
SearchBins |
Seller |
| SellerListing |
Similarities |
Small |
Subjects |
| TopSellers |
Tracks |
TransactionDetails |
VariationMinimum |
| Variations |
VariationImages |
VariationSummary |
|
- SearchIndex Parameter
Specifies the particular catalogue we're going to search.
Searchindex parameter is a case sensitive.
List of valid SearchIndexes
All, Apparel, Automotive, Baby, Beauty, Blended, Books, Classical, DVD, DigitalMusic, Electronics, GourmetFood, Grocery, HealthPersonalCare, HomeGarden, Industrial, Jewelry, KindleStore, Kitchen, MP3Downloads, Magazines, Marketplace, Merchants, Miscellaneous, Music, MusicTracks, MusicalInstruments, OfficeProducts, OutdoorLiving, PCHardware, PetSupplies, Photo, Shoes, SilverMerchants, Software, SportingGoods, Tools, Toys, UnboxVideo, VHS, Video, VideoGames, Watches, Wireless, WirelessAccessories.
- Keywords Parameter
Specifies the keyword related to the product
- Sample Request
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId= 1ERM7K5EFJXVPXCE5C82&AssociateTag=test03fd-20&Version=2007-10-29&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=Books&Keywords=All
- Sample Response
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-01-19">
<OperationRequest>
<HTTPHeaders>
<Header Name="UserAgent" Value="Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1"></Header>
</HTTPHeaders>
<RequestId>0JQ4GT363KKWN5RBNS6X</RequestId>
<Arguments>
<Argument Name="Service" Value="AWSECommerceService"/>
<Argument Name="Operation" Value="ItemSearch"/>
<Argument Name="AssociateTag" Value="test03fd-20"/>
- <Argument Name="Version" Value="2007-10-29"/>
<Argument Name="Keywords" Value="All"/>
<Argument Name="AWSAccessKeyId" Value="1ERM7K5EFJXVPXCE5C82"/>
<Argument Name="ResponseGroup" Value="Medium,Offers"/>
<Argument Name="SearchIndex" Value="Books"/>
</Arguments>
<RequestProcessingTime>0.0342471599578857</RequestProcessingTime>
</OperationRequest>
<Items>
<Request>
<IsValid>True</IsValid>
<ItemSearchRequest>
<Keywords>All</Keywords>
<SearchIndex>Books</SearchIndex>
</ItemSearchRequest> </Request>
<TotalResults>1</TotalResults>
<TotalPages>1</TotalPages>
<Item>
<ASIN>0764589547</ASIN>
<DetailPageURL>http://www.amazon.com/exec/obidos/redirect?tag=ws%26link_code=xm2 %26camp=2025%26creative=165953%26path=http://www.amazon.com/gp/redirect.html%253f ASIN=0764589547%2526location=/o/ASIN/0764589547%25253FSubscriptionId=1PHH5VTRY7 D300H7JTR2</DetailPageURL>
- <ItemAttributes>
<Author>Paul Reinheimer</Author>
<Author>Chris Shiflett</Author>
<ProductGroup>Book</ProductGroup>
<Title>Professional Web APIs with PHP: eBay, Google, Paypal, Amazon, FedEx plus Web Feeds </Title> </ItemAttributes>
</Item>
</Items>
</ItemSearchResponse>
- <ItemAttributes>
<Author>Paul Reinheimer</Author>
<Author>Chris Shiflett</Author>
<ProductGroup>Book</ProductGroup>
<Title>Professional Web APIs with PHP: eBay, Google, Paypal, Amazon, FedEx plus Web Feeds</Title> </ItemAttributes>
</Item></Items>
</ItemSearchResponse>
Interacting with the eBay API
- The largest online auction house, with thousands of items for sale in many categories from users around the world
Prerequisites
- A regular eBay.com account (www.ebay.com) that will be associated with your development account
- A development account, (http://developer.ebay.com) which is a free account required to access the API
- At least one sandbox user account (http://www.sandbox.ebay.com) to act as a seller for auctions you create during testing
- At least one sandbox user account to act as a buyer for auctions you create during testing.
Ebay APIs
- Shopping API
The Shopping API is optimized for response size, speed and usability. Search for eBay items, products and reviews, user info, and popular items and searches.
- Merchandising API
The Merchandising API provides developers with an easy way to surface available items and products on eBay that provide good value or are otherwise popular with eBay buyers.
- Trading API
eBay Trading API is used to build applications such as selling and post-sales management applications, manage User information, and initiate the item purchase flow on eBay.
- Client Alerts API
Client Alerts provides developers with a way to retrieve updated data on eBay. Keep your users and applications informed with up to date information about business events happening on eBay.
- Notification API
eBay Notification APIs are a set of APIs that are used to manage notification preferences for applications and users. Applications receive User’s notifications on a configured end point.
- Research API
Retrieve historical eBay data.
Sample Request Click Here
Sample Ebay Response
<eBay>
<EBayTime>2005-07-19 18:07:48</EBayTime>
<Search>
<Items>
<Item>
<Id>4503294022</Id>
<Title><![CDATA[Boat Captain Anchor Nautical Canvas Sailboat Pillow NEW]]>
</Title>
<SubtitleText><![CDATA[]]></SubtitleText>
<CurrencyId>1</CurrencyId>
<Link><![CDATA[http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=
4503294022&category=20563]]></Link>
<CurrentPrice>9.99</CurrentPrice>
<LocalizedCurrentPrice>$9.99</LocalizedCurrentPrice>
<BINPrice>US $0.00</BINPrice>
<BidCount>0</BidCount>
<StartTime>2005-07-14 19:43:26</StartTime>
<EndTime>2005-07-21 19:43:26</EndTime>
<BillPointRegistered>0</BillPointRegistered>
<ItemProperties>
<BoldTitle>0</BoldTitle>
<Featured>0</Featured>
<Gallery>1</Gallery>
<GalleryFeatured>0</GalleryFeatured>
<GalleryURL><![CDATA[http://thumbs.ebay.com//pict/4503294022.jpg]]>
</GalleryURL>
<Picture>1</Picture>
<Highlight>0</Highlight>
<Border>0</Border>
<New>0</New>
<BuyItNow>0</BuyItNow>
<IsFixedPrice>0</IsFixedPrice>
<Type>1</Type>
<Gift>0</Gift>
<CharityListing>0</CharityListing>
<MotorsGermanySearchable>0</MotorsGermanySearchable>
</ItemProperties>
</Item>
</Items>
<Count>2</Count>
<HasMoreItems>0</HasMoreItems>
<PageNumber>1</PageNumber>
<GrandTotal>2</GrandTotal>
</Search>
</eBay>
Some of the elements contained in each Item include the following:
- Id — A unique identifier for the item within the eBay system
- CurrencyID — An integer that represents the native currency for the auction. The integers and the currency they represent include the following:
- 1 — US Dollar ($)
- 2 — Canadian Dollar (C $)
- 3 — UK Pound Sterling (GBP)
- 5 — Australian Dollar (AU $)
- 7 — Euro (EUR)
- 13 — Swiss Franc (CHF)
- 41 — Taiwanese Dollar (NT $)
- LocalizedCurrentPrice — Returns the highest bid on the item, taking into account the currency of the item as well as the current location of the requestor
- BINPrice — This is the Buy It Now price. A bidder willing to pay the full Buy It Now price may end the auction immediately
- BillPointRegistered — Bill Point is a payment system eBay used to offer. It is no longer used, so the value will always be zero.
- IsFixedPrice — A binary value. A 1 indicates that the item is for sale at a set price and a 0 indicates a regular auction.
- Type — An integer that indicates the type of auction that is being run. eBay offers several auction types beyond the normal. The integer and type of auctions are as follows:
- 0 — Unknown auction type
- 1 — Chinese auction
- This is the standard auction type that you likely already associate with eBay. A single item is offered for sale, and a time frame is set. Bids are placed competitively during that time frame; at the end, the individual that has placed the highest bid is awarded the item at the highest bid price.
- 2 — Dutch auction
- In a Dutch auction, two or more items are placed up for sale, in which bidders can place a bid not only for an amount per item, but also the number of items desired (for example, you could place a bid for $100, and state that you desire 3 items [at $100 each]). At the end of the auction, items are awarded to the highest bidder, then the second highest, and so on, at the individual bidder's price.
- 5 — Live auction
- Similar to a Chinese auction, except the auction takes place both on eBay and in a live setting where non-eBay members may also bid on the item.
- 6 — Ad Type auction
An advertisement for a real estate listing designed to generate leads rather than bids. This is a nonpurchase listing.
- 7 — eBay Stores Inventory (fixed-price items).
- Similar to fixed-price items, except items are listed only within the seller's store, not within a general eBay category.
- 8 — Personal Offer auction
- A special type of listing where the seller offers a specific item at a set price to another eBay user. This is a Second Chance offer, used by the seller to offer an item to a nonwinning bidder when the winning bidder didn't complete the transaction.
- 9 — Fixed-Price item (combined with Buy It Now)
- One or more items are offered for sale at a fixed price — there is no progressive bidding. Buyers may purchase an item or several items at a set price and complete the transaction immediately. The listing ends either when the duration is exhausted or when all of the available items are sold.
- CharityListing — Depreciated. A binary value, with a 1 indicating that the seller has chosen to donate a percentage of the proceeds of the sale to a selected nonprofit organization, and a 0 of course indicating that the full purchase price will be kept by the seller.
- MotorsGermanySearchable — A depreciated value, used to indicate that the item was dual listed with mobile.de.
Refferences: