What is API?
Application Programming Interface(API) is a specification intended to be used as an interface by software components to communicate with each other. It is a also set of routines, protocols, and tools for building software applications.sources: http://en.wikipedia.org/wiki/Application_programming_interface
http://www.webopedia.com/TERM/A/API.html
-------------------------------------------------------------------------------------------------------------------------
API for Facebook
(source http://developers.facebook.com/docs/reference/php/facebook-api/)Get the User's profile via the Graph API and print their name
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$user_profile = $facebook->api('/me','GET');
echo "Name: " . $user_profile['name'];
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
Get the User's name using FQL and print it
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$fql = 'SELECT name from user where uid = ' . $user_id;
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,
));
// FQL queries return the results in an array, so we have
// to get the user's name from the first element in the array.
echo '<pre>Name: ' . $ret_obj[0]['name'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
Post a link to a User's wall using the Graph API
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
// Give the user a logout link
echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
Upload a photo to a User's profile
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'fileUpload' => true,
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$photo = './mypic.png'; // Path to the photo on the local filesystem
$message = 'Photo upload via the PHP SDK!';
?>
<html>
<head></head>
<body>
<?
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$ret_obj = $facebook->api('/me/photos', 'POST', array(
'source' => '@' . $photo,
'message' => $message,
)
);
echo '<pre>Photo ID: ' . $ret_obj['id'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'photo_upload'
));
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
} else {
// No user, print a link for the user to login
// To upload a photo to a user's wall, we need photo_upload permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'photo_upload') );
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
Parameters
Graph API Methods
To call a Graph API method, pass in the endpoint path you wish to retrieve as the first parameter, and other optional parameters as necessary:$ret = $facebook->api($path, $method, $params);
Name | Description |
---|---|
path |
The Graph API path for the request, e.g. "/me" for the logged in user's profile. |
method |
(optional) Specify the HTTP method for this request: 'GET' , 'POST' , or 'DELETE' . |
params |
(optional) Parameters specific to the particular Graph API method you are calling. Passed in as an associative array of 'name' => 'value' pairs. |
FQL Queries
To run an FQL query, pass the parameters in as an array, with the'method'
property set to 'fql.query'
:$ret = $facebook->api( array(
'method' => 'fql.query',
'query' => 'SELECT . . . ',
));
(DEPRECATED) REST APIs
REST APIs are called exactly the same as FQL queries, except that the'method'
property is replaced with the REST API name, and other parameters are
replaced as necessary for the specific API call. For example:$ret = $facebook->api( array(
'method' => 'link.getStats',
'urls' => 'facebook.com,developers.facebook.com',
));
----------------------------------------------------------------------------------
API for Twitter
source (https://dev.twitter.com/docs/streaming-apis)
The Streaming APIs
Updated on Tue, 2012-05-15 15:01
Overview
The set of streaming APIs offered by Twitter give developers low latency access to Twitter's global stream of Tweet data. A proper implementation of a streaming client will be pushed messages indicating Tweets and other events have occurred, without any of the overhead associated with polling a REST endpoint.Twitter offers several streaming endpoints, each customized to certain use cases.
Public streams | Streams of the public data flowing through Twitter. Suitable for following specific users or topics, and data mining. |
---|---|
User streams | Single-user streams, containing roughly all of the data corresponding with a single user's view of Twitter. |
Site streams | The multi-user version of user streams. Site streams are intended for servers which must connect to Twitter on behalf of many users. |
Differences between Streaming and REST
Connecting to the streaming API requires keeping a persistent HTTP connection open. In many cases this involves thinking about your application differently than if you were interacting with the REST API. For an example, consider a web application which accepts user requests, makes one or more requests to Twitter's API, then formats and prints the result to the user, as a response to the user's initial request:
-----------------------------------------------------------------------------------------------------------
API for Google+
source: https://developers.google.com/+/api/Google+ API
The Google+ API is the programming interface to Google+. You can use the API to integrate your app or website with Google+. This enables users to connect with each other for maximum engagement using Google+ features from within your application.API
View the Google+ API reference, with resources People, Activities and Comments.
Note: The Google+ API currently provides read-only access
to public data. All API calls require either an
OAuth 2.0 token or an
API key.
Quota
Applications are limited to a courtesy usage quota. This should provide enough access for you to preview the API and to start thinking about how you want to build your application. To see the courtesy limit and to request a higher limit for your application, please see the Google APIs Console. To learn more, see the Google APIs Console Help.Authorization
Many API calls require that the user of your application grant permission to access their data. Google uses the OAuth 2.0 protocol to allow authorized applications to access user data. To learn more, see OAuth.API Calls
Most of the Google+ API follows a RESTful API design, meaning that you use standard HTTP methods to retrieve and manipulate resources. For example, to get the profile of a user, you might send an HTTP request like:GET https://www.googleapis.com/plus/v1/people/userId
Common Parameters
Different API methods require parameters to be passed either as part of the URL path or as query parameters. Additionally, there are a few parameters that are common to all API endpoints. These are all passed as optional query parameters.Parameter Name | Value | Description |
---|---|---|
callback |
string |
Specifies a JavaScript function that will be passed the response data for using the API with JSONP. |
fields |
string |
Selector specifying which fields to include in a partial response. |
key |
string |
API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. |
access_token |
string |
OAuth 2.0 token for the current user. Learn more about OAuth. |
prettyPrint |
boolean |
If set to "true", data output will include line breaks and indentation to make it more readable. If set to "false", unnecessary whitespace is removed, reducing the size of the response. Defaults to "true". |
userIp |
string |
Identifies the IP address of the end user for whom the API call is being made. This allows per-user quotas to be enforced when calling the API from a server-side application. Learn more about Capping Usage. |
Data Formats
Resources in the Google+ API are represented using JSON data formats. For example, retrieving a user's profile may result in a response like:{ "kind": "plus#person", "id": "118051310819094153327", "displayName": "Chirag Shah", "url": "https://plus.google.com/118051310819094153327", "image": { "url": "https://lh5.googleusercontent.com/-XnZDEoiF09Y/AAAAAAAAAAI/AAAAAAAAYCI/7fow4a2UTMU/photo.jpg" } }
Common Properties
While each type of resource will have its own unique representation, there are a number of common properties that are found in almost all resource representations.Property Name | Value | Description |
---|---|---|
displayName |
string |
This is the name of the resource, suitable for displaying to a user. |
id |
string |
This property uniquely identifies a resource. Every resource of a
given kind will have a unique id . Even though an
id may sometimes look like a number, it should always
be treated as a string.
|
kind |
string |
This identifies what kind of resource a JSON object represents. This is particularly useful when programmatically determining how to parse an unknown object. |
url |
string |
This is the primary URL, or permalink, for the resource. |
Pagination
In requests that can respond with potentially large collections, such as activities list, each response contains a limited number of items set by maxResults (default: 20). Each response also contains a nextPageToken property. To obtain the next page of items, you pass this value of nextPageToken to the pageToken property of the next request. Repeat this process to page through the full collection. For the last page, nextPageToken will be absent.
Note: Page tokens become stale over time — if new items have
been added to a list since you started paginating, they might not appear in the results.
If you've held a pageToken for a long period of time and want to continue paging,
it may be better to restart pagination by repeating the original request (omitting pageToken).
For an example of pagination, calling an activities list method returns a response with nextPageToken:
{ "kind": "plus#activityFeed", "title": "Plus Public Activities Feed", "nextPageToken": "CKaEL", "items": [ { "kind": "plus#activity", "id": "123456789", ... }, ... ] ... }To get the next page of activities, pass the value of this token in with your next Activities list request:
https://www.googleapis.com/plus/v1/people/me/activities/public?pageToken=CKaELAs before, the response to this request includes nextPageToken, which you can pass in to get the next page of results. You can continue this cycle to get new pages.
Partial Responses
By default, the server sends back the full representation of a resource after processing requests. For better performance, you can ask the server to send only the fields you really need and get a partial response instead.To request a partial response, use the
fields
request
parameter to specify the fields you want returned. You can use this
parameter with any request that returns a response body.Example
The following example shows the use of thefields
parameter with the Google+ API.Simple request: This HTTP
GET
request omits the fields
parameter and returns the full activity resource, with its dozens of fields.https://www.googleapis.com/plus/v1/activities/z12gtjhq3qn2xxl2o224exwiqruvtda0i?key=YOUR-API-KEYRequest for a partial response: This HTTP
GET
request for the above resource that uses the fields
parameter significantly reduces the amount of data returned.https://www.googleapis.com/plus/v1/activities/z12gtjhq3qn2xxl2o224exwiqruvtda0i?fields=url,object(content,attachments/url)&key=YOUR-API-KEY
In response to the above request, the server sends back a JSON response that contains only the
url
field and the pared-down object
that includes only content
and attachments.url
.{ "url": "https://plus.google.com/102817283354809142195/posts/F97fqZwJESL", "object": { "content": "A picture... of a space ship... launched from earth 40 years ago.", "attachments": [ { "url": "http://apod.nasa.gov/apod/ap110908.html" } ] } }Note that the response is a JSON object that includes only the selected fields and their enclosing parent objects.
Syntax of the
fields
parameter is covered next, followed by more detail about what gets returned in the response.Fields parameter syntax summary
The format of thefields
request parameter value is
loosely based on XPath syntax. The supported syntax is summarized below,
and additional examples are provided in the following section.- Use a comma-separated list to select multiple fields.
- Use
a/b
to select a fieldb
that is nested within fielda
; usea/b/c
to select a fieldc
nested withinb
.
- Specify field sub-selectors to request only specific sub-fields by placing expressions in parentheses "
( )
" after any selected field. For example:fields=items(id,object/content)
returns only the itemid
and object'scontent
, for eachitems
array element.
- Use wildcards in field selections, if needed.
For example:
fields=items/object/*
selects all items in an object.
More examples of using the fields parameter
The examples below include descriptions of how thefields
parameter value affects the response.
Note: As with all query parameter values, the
fields
parameter value must be URL encoded. For better readability, the examples in this document omit the encoding.- Field selections: Identify the fields you want returned.
- The
fields
request parameter value is a comma-separated list of fields, and each field is specified relative to the root of the response. Thus, if you are performing a list operation, the response is a collection, and it generally includes an array of resources. If you are performing an operation that returns a single resource, fields are specified relative to that resource. If the field you select is (or is part of) an array, the server returns the selected portion of all elements in the array.
Here are some collection-level examples from activities.list:
Examples Effect items
Returns all elements in the items
array, including all fields in each element, but no other fields.updated,items
Returns both the updated
field and all elements in theitems
array.items/title
Returns only the title
field for all elements in theitems
array.
Whenever a nested field is returned, the response includes the enclosing parent objects. The parent fields do not include any other child fields unless they are also selected explicitly.
Here are some resource-level examples from activities:
Examples Effect title
Returns the title
field of the requested resource.actor/displayName
Returns the displayName
sub-field of theactor
object in the requested resource.object/attachments/url
Returns only the url
field for all members of theattachments
array, which is itself nested under theobject
object. - Field sub-selections: Request only parts of the selected elements.
- By default, if your request specifies particular objects, the
server returns the objects in their entirety. You can specify a response
that includes only certain sub-fields within the selected objects. You
do this using "
( )
" sub-selection syntax, as in the example below.Example Effect items(id,url)
Returns only the values of the id
andurl
fields for each element in theitems
array.
Handling partial responses
After a server processes a valid request that includes thefields
query parameter, it sends back an HTTP 200 OK
status code, along with the requested data. If the fields
query parameter has an error or is otherwise invalid, the server returns an HTTP 400 Bad Request
status code, along with an error message telling the user what was wrong with their fields selection (for example, "Invalid field selection a/b"
).
Note: Whenever possible, use
maxResults
judiciously to reduce the results of each query to a manageable size.
Otherwise, the performance gains possible with partial response might
not be realized.
Note: I do not own any of this. This is for a requirement for our subject ITNA03.
Sources of where I copied the contents of this blog is shown.