In: Categories » Internet » APIs and Web Feeds » How to implement the REST technology
|
There are two sides to this tale, the first is how to generate legitimate REST requests, and the second is how to handle the responses correctly. Generating RequestsWhen it comes to generating the request, you have three main options. First, you can generate the request manually, using PHP's header functions. This gives you complete flexibility in generating the request, but does involve the most coding. Second, you can use one of PHP's built-in request functions such as file_get_contents() or file()/fopen(), fread(), and fclose(). With this method, a lot of the detailed information is handled automatically by PHP, and you receive the same response. Finally,you can use a custom class designed to be used with the API in question. Generally these classes require nothing more than the parameter list, and will return the results in the form of a custom object or make them accessible through a class. Manual GenerationGenerating requests manually is only tricky the first time, after that, code-reuse and modularity kick in. Conceptually the function that will generate the request is pretty basic. First, all the request parameters are prepared to ensure proper transmission. Next, the URL for the endpoint is generated, then parsed and broken up into its component parts. Finally, the request itself is sent using sockets: functioncallAPI($endpoint, $devkey, $action, $type, $keyword) Three of the passed parameters are URL encoded. This is necessary to ensure they are passed properly over the URL. In the previous example, a search for "style" was performed; if the search had instead been "style book," the space would have required encoding, resulting in style%20book. I have neglected encoding the devkey variables, trusting that the issuing authority took how it would be used into consideration when creating them. $url = $endpoint ."?devkey=$devkey&action=$action&type=$type&keyword=$keyword"; Here the URL itself is generated, including the now URL-encoded parameters. The URL needs to be deconstructed down to its component parts for use in the raw socket connection. $fp=fsockopen($host, 80); Here the information generated by previous code is finally sent. The first fputs() line sends the path to the requested document, and the second line specifies the desired host. $response=""; Finally, the response is retrieved and the content of the response is returned. You learn how to handle responses in the sections dealing with that side of things shortly. Quick GenerationUtilizing PHP's built-in file functions, the same process can be completed with much less code (though you do have less flexibility). Conceptually this function works the same as the previous one, except all the file socket calls are replaced with one call to file_get_contents(): functioncallAPIQuick($endpoint, $devkey, $action, $type, $keyword) There really isn't much to explain with this example. The URL encoding was discussed previously, and the single file_get_contents() call handles all the magic. The ampersand in front of the function call is used to suppress any warnings that may arise from a non-existent file or URL, because these should be handled by the calling function (file_get_contents() will return false in these instances). In pre-PHP5 environments you will need to use fopen() instead of file_get_contents(). Some flexibility is lost with this request type, because you can no longer set custom headers or optional headers, which may be required or very desirable depending on the API with which you are interacting. Automated ToolsAs the popularity of web services increases, so will the prevalence of prebuilt classes to handle the dirty work of actually interacting with the server. If the service you want to interact with has a class available, it is definitely worth looking into. Accessing the class will of course be dependent on the class itself. It should come with sufficient documentation, and access will likely not differ too much from the earlier examples — just with a little more error checking (you hope). Something to keep in mind is that many prebuilt modules are developed and maintained by third parties, and as such you might have to wait a while after new features are released on the API for them to become available with your class. Handling the ResponseHow you deal with the response depends on which method of sending the request you choose. If you generated the request either manually or with the aid of one of PHP's built-in functions (like file_get_contents()) you will also need to manually handle the response. If you used a third-party module, it will have its own interface for retrieving results. Manually Parsing the ResponseThe response provided by the server should be an XML document; luckily, XML was designed to be easy to parse. Unfortunately, no matter how it was designed, manually parsing anything usually isn't a lot of fun. PHP5 comes with SimpleXML, which makes handling XML documents a breeze. PHP4 users don't have SimpleXML; however, a few third-party modules like MiniXML are available that perform similar functions. Once you have received the response, sticking it into a SimpleXML object should be a breeze. Using the previous library example and request function, you end up with something like this: $response= callAPIQuick('http://library.example.com/api.php', '123', 'search', Here, the response is not false (and hence something, presumably the XML you were hoping for, was returned). Note that this assumption is generally pretty valid. When a server providing an API encounters an error, it should provide the error in a nice XML format. The simplexml_load_string() function takes the response and turns it into an XML object that can be directly accessed, iterated through, and so on. Finally, the print_r() function results in a user-friendly output showing the contents of the object, shown here: SimpleXMLElement Object ) [1] => SimpleXMLElement Object Looking at that output, a couple things should be immediately obvious:
Bearing all that information in mind, a couple of quick lines of code are all that is required to explore the content more fully. echo "You searched for: {$xml->Request->Parameters->Argument[3]->Value}<br>";echo "Here are your {$xml->Response->ResultCount} results<br>"; foreach($xml->Response->Item AS &$item) { echo "{$item->Title} by {$item->Author}<br>"; } Here the search query and result count is presented, and then the results themselves are iterated through. The syntax gets a little weird when dealing with arrays (as demonstrated when the search query is printed), so it is often sensible to iterate through them for clarity. REST is an effective method of querying remote APIs when it is permissible for the request portion of your transaction to take place in the clear. Creating REST queries is as easy as URL-encoding the required parameters and specifying an endpoint for the call. Dealing with REST responses can be a little trickier; however, by leveraging tools like SimpleXML, it too can be completed quickly.
|
legal disclaimer
1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service
Useful tools and features
related articles
The two primary architectures for APIs are REST and SOAP. When creating your API, you really have three options: REST, SOAP, or both. REST APIs are known for being easy and quick to develop for, but the entire request is sent in the clear regardless of the type of encryption used. SOAP APIs are more complex, requiring more effort to generate the response and handle the request, but allow for greater flexibility by adding namespace support. Providing APIs of both types may sound like an attractive option, but keep in mind that it will double ...
2. Advantages and Disadvantages of SSL ~ API related
Configuring your web server to present the API over an SSL connection adds protection for both the request and response bodies, while requiring little to no additional coding for the API. Remember that the use of a server certificate only authenticates the server for the client, it does nothing to identify the client itself. It is best used layered with one of the previous two examples. Advantages: Encryption — Both request and response bodies are protected from intermediate prying eyes. ...
3. How SOAP Works
A SOAP request will involve creating and populating a request envelope, which contains all the required information (as specified by the WSDL document), transmitting that envelope to the API server, and handling the response. A SOAP request generally contains all of the following elements: SOAP Envelope — With namespace inclusions. SOAP Body — Possibly defining additional namespaces. Desired Action — How the desired action is represented will depen...
4. Why Do You Need to Produce Feeds
Feeds have several advantages, primarily related to consumption, over traditional HTML formats. Many desktop applications are devoted to reading feeds at regular intervals, and many of the new batch of web browsers include features for reading feeds. These free the user from manually checking various sources (websites) for new information. Instead, the automated tool checks the subscribed feeds every few minutes and presents them to the user (usually organized in a user-configurable manner). The standard and predictable format makes this a m...
Generally speaking, 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 and acted upon. 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 type...
6. Important Considerations When Using Feeds
XML feeds provide a great resource of information, but their use is not without its own special considerations. Security and legal concerns go hand in hand whether you are producing or consuming feeds. Consider if you will the implications of going away for the weekend, only to discover that your aggregator has been attacked, your site is now displaying wildly inaccurate information provided by the attacker, and your legal department is fielding not-so-nice phone calls regarding the current content of your homepage. Also consider how often...
7. Advantages and Disadvantages of Client Side Certificates
The API server can generate a certificate and provide it to the client via a secure channel before any requests are made. This certificate is then used in the authentication process; this confirms the identity of both the client and server before requests are made. Although this method provides the greatest level of security (barring a dedicated VPN connection, which won't be covered here), it also has the most strenuous requirements on both sides: not all modules (say, NuSOAP) can handle client-side certificates. Advantages:...
8. What are Feeds ~ RSS and ATOM Feed Specifications
You can think of feeds as small modules of information that can be plugged into existing websites, consumed by clients on their desktop, or consumed by aggregators to be presented by users with other feeds. Aggregators also offer searching functionality to users, allowing new users to locate your site and feed (a great reason to provide a feed in the first place). Websites such as Yahoo! produce web feeds. Software that downloads and uses feeds is said to consume or aggregate feeds. Sites such ...
9. Introduction to Web APIs ~ REST vs SOAP
When interacting with web services, generally the choice of which method to use will be made for you. The majority of services operate in either REST or SOAP, not both (Amazon is a notable exception to this rule). When given the choice, however, there are several points to consider: Overhead — REST requests are relatively slim. SOAP requests, on the other hand, contain a lot of additional information, which can really add up. Transparency — With REST requests (even when completed ov...










