Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Sunday 8 December 2019

Swagger - REST API documentation tool

Swagger - REST API documentation tool


Question: What is swagger?
It is REST API documentation tool which is used to list the APIs and view the request and response.
In this, we need to add some annotations in your functions and then it will automatically generate a beautiful and user-friendly documentation for your APIs.



Question: Where it is used?
Whenever we develop an android, IOS (Apple) application, we need to create an APIs for them.

To check the API details (URL, Request, response), we use Swagger.


Question: Who is using swagger?
Backend Developer: developer used it while creating Or updating an API.
Team Leader: As it give List of APIs with request and response. Team leader used it review the APIs.
Android/IOS Developer: While integrating the APIs, Its quite help the developer because they can check the response of APIs with different request.


Question: What are benefits of swagger?
  1. Its give list of APIs with short description.
  2. Its give the Request and Response of API.
  3. We can test the response of API with different request.
  4. We need to integrate in application first time, after the we need to add some annotations in functions/APIs.
  5. Can be integrate in Core PHP or Framework.
  6. We need not to list and details of apis manually.



Question: What is Swagger Editor?
The Swagger Editor is the tool for quickly getting started with the Swagger Specification.
Create new APIs OR update existing ones in a powerful Editor which visually renders your Swagger definition and provides real time error-feedback.
http://editor.swagger.io/#/


Question: Give a Demo URL?
http://petstore.swagger.io/


Question: From where i can download?
http://swagger.io/docs/#swagger-ui-documentation-29


Question: How to Add API in swagger?
Add Following code before the class declaration
/**
 * @SWG\Resource(
 *     apiVersion="1.0",
 *     swaggerVersion="1.2",
 *     description="Search users"
 * )
 */



Question: How to add new Operation for an API?
Add Following code before the method declaration
    /**
     * @SWG\Api(
     *     path="/search",
     *     @SWG\Operation(
     *         method="POST",
     *         summary="Get users near your location",
     *         type="Users list",
     *         @SWG\Parameters(
     *             @SWG\Parameter(
     *                 name="interests",
     *                 paramType="form",
     *                 description="comma seperated looking for",
     *                 required=false,
     *                 type="string",
     *                 minimum="1.0"
     *             ),
     *             @SWG\Parameter(
     *                 name="page",
     *                 paramType="form",
     *                 description="page number",
     *                 required=true,
     *                 type="string",
     *                 minimum="1.0"
     *             ),
     *         ),
     *         @SWG\ResponseMessage(code=400, message="Invalid Data")
     *     )
     * )
     */



Saturday 16 November 2019

How to Send Tweets automatically with PHP?

How to Send Tweets automatically with PHP?


Basic Requirements
  1. An Twitter account.
  2. An Twitter app. If don't have please create @ https://apps.twitter.com
  3. Twitter Auth REST API, If don't have please download from https://github.com/abraham/twitteroauth
  4. An Server, You can also test in local wampserver or xampserver


How to Send Tweets automatically with PHP, Follow following Steps:
  1. Include twitter files.
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/twitteroauth.php');
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/config.php');
  2. Collect all constants values from your twitter app (i.e apps.twitter.com)

  3. Add constants in TwitterOAuth constructor.
    define('CONSUMER_KEY', 'YOUR_KEY');
    define('CONSUMER_SECRET', 'YOUR_SECRET_KEY');
    define('ACCESS_TOKEN', 'YOUR_TOKEN');
    define('ACCESS_TOKEN_SECRET', 'YOUR_TOKEN_SECRET');
    
  4. $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  5. Now post the message.
    $message='This is test tweet.';
    $twitter->post('statuses/update', array('status' => $message));
  6. Refresh the twitter.com, you will see your message at top of page.

Thursday 14 June 2018

Get the access token with OAuth 2.0 for Google API


Follow Below 4 steps to get the access token with OAuth 2.0 for Google API


1. Obtain OAuth 2.0 credentials ("Client ID" and "Secret Key") from the Google Developers Console.
  • Go to https://console.developers.google.com/
  • Select your project (create new project, If not have created before).
  • Click on "APIs & auth"
  • Click to "APIs", Now you have all the list of Google APIs  .
  • Select OR Search the APIs from search box, the one which you want to use.
  • Select API and Click on "Enable API". (I enable "Google Webmaster Tools API")
  • Now, click on "Credentials", Click on "Create new Client ID" under OAuth tab.
  • Popup will come. click on "Configure consent screen".
  • New form will appear. Fill the details and click on "Save".
  • Confirmation page appear, Click on "Create Client ID"
  • Now you will see the screen simpilar to below:

 Obtain OAuth 2.0 credentials
 Obtain OAuth 2.0 credentials
  • m. Get the "client Id" and "Client secret". (DON'T SHARE IT).


2. Create a new page in PHP like http://www.domain.com/auth-url.php
Add this URL in "Authorized redirect URIs" in your project (in Edit setting) above created.


3. Get the GET Access token from google using "Client ID" and "Secret Key"
Add the below code in "auth-url.php"
  define(YOUR_CLIENT_ID,'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
  define(YOUR_CLIENT_SECRET,'xxxxxxxxxxxxxxx');
if (isset($_GET['code'])) {    
    $code = $_GET['code'];
    //Set the Auth URL
    $url = 'https://accounts.google.com/o/oauth2/token';
    
    //Set the Auth Parameter
    $redirectUri='http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"];
    $params = array(
        "client_id" => YOUR_CLIENT_ID,
        "client_secret" => YOUR_CLIENT_SECRET,
        "redirect_uri" => $redirectUri,
        "grant_type" => "authorization_code",
        "code" => $code,
    );

    /** Init the curl */
    $ch = curl_init();
    curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
    curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
    curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
    $output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    if ($info['http_code'] === 200) {
        header('Content-Type: ' . $info['content_type']);
        return $output;
    } else {
        die('An error occured');
    }
    /** Init the curl */
    
} else {

    $url = "https://accounts.google.com/o/oauth2/auth";

    //Set the Auth Parameter
    $params = array(
        "response_type" => "code",
        "client_id" => YOUR_CLIENT_ID,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],        
        "scope" => "https://www.googleapis.com/auth/webmasters.readonly" //I have added scope for webmaster tool
        
    );

    $requestTo = $url . '?' . http_build_query($params);

    //Redirect the page
    header("Location: " . $requestTo);
} 



4. You will get result simpliar to below.
{ "access_token" : "ya29.kgGOtdWEj32NOSxLWkZXAaXAagmkP-4WgHEd8gpUfuelHD_lslquKzHMVV2OnnNc5h1BKWkY8aeCrA", "token_type" : "Bearer", "expires_in" : 3600 }

Here you got access_token, token_type and expires_in (in Seconds).


If this code does not work and need any assistance, Please feel free to comment.

Tuesday 5 September 2017

Validate Icalendar File or URL




Question: What is Desktop iCalendar?
Desktop iCalendar is a handy desktop calendar for Windows. It stays on your desktop and shows the days of the current month have the events. It can be sync with Google Calendar OR Yahoo Calendar. You can share the calendars with your family and friends with use of the Google OR Yahoo. File format of iCalendar is .ics.


Question: What is use of iCalendar?
iCalendar is a computer file format which allows Internet users to send meeting requests and tasks to other Internet users, via facebook, email. Recipients of the iCalendar data file can respond to the sender easily or counter propose another meeting date/time


Question: Why need of Validate the Icalendar?
When we validate, It make sure us that we are sharing correct and valid file. Also it make sure recipients will get the  task/events once they get.


Question: How to validate Icalendar File OR code snippt.
http://severinghaus.org/projects/icv/


Question: What are Development Tools for Validate Icalender.
Language Library
C/C++ libical
Java iCal4J
Python vObject
Ruby iCalendar
Ruby RiCal

Monday 9 January 2017

How to integrate Google Places Search API in website?

How to integrate Google Places Search API in website?

Get the Google API Key
  1. Login to https://console.developers.google.com
  2. Get the API Keys.
  3. Enable "Google Places API Web Service" from Google Google Map API



HTML Code

<script src="https://maps.googleapis.com/maps/api/js?v=3&amp;libraries=places&amp;key=HERE_YOUR_KEYS"></script>
<div class="search-Form">
<input id="search" name="q" type="text" value="" /> <input id="submit" type="submit" value="go" />
</div>



JavaScript Code

    var lat
    var lon
    function initialize() {
        var input = document.getElementById('search');
        var autocomplete = new google.maps.places.Autocomplete(input);

        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            lat = place.geometry.location.lat()
            lon = place.geometry.location.lng()
        });

    }

    google.maps.event.addDomListener(window, 'load', initialize);

View Demo

Monday 13 June 2016

Google Custom Search API

Google Custom Search API

Custom Search API lets you pro grammatically used to custom search engines for your site(s), you can search text OR images.


Format of URL
https://www.googleapis.com/customsearch/v1?q={SEARCH_TEXT}&cx={SEARCH_ENGINE_ID}&key={YOUR_API_KEY}



Question: What is SEARCH_TEXT?
It is search text which user want to search like "php", "interview questions", "web technology experts" etc.


Question: How to get SEARCH_ENGINE_ID?
  • Login to your gmail account
  • https://cse.google.com/cse
  • Create a new "Search Engine" or Us Existing one
  • Go to "Search Engine" from listing "Search Engine Listing"
  • Enable the "Image search"
  • Search "Sites to search" and select "Search on Entire Web"
  • Get the Search Engine ID, My search engine id is "0150557dddd364721200:zrndkpkfwyga"



Question: How to get YOUR_API_KEY?
If you don't have API_KEY, please get the API Key from http://code.google.com/apis/console#access .
You must need google account.


Question: How to extract data from custom search with text PHP?

$url='https://www.googleapis.com/customsearch/v1?q=php&amp;cx={SEARCH_ENGINE_ID}&amp;key={APP_KEY}';
try{
    echo $jsonData=file_get_contents($url);die;
    $searchData = json_decode($jsonData);
}  catch (Exception $e){
    echo $e-&gt;getMessage();
}
if(!empty($searchData-&gt;items)){
    foreach($searchData-&gt;items as $item){        
        echo $text = $item-&gt;title;        
        echo "\n";
    }    
}



Output

PHP: Hypertext Preprocessor
PHP - Wikipedia, the free encyclopedia
PHP 5 Tutorial
PHP | Codecademy
PHP Tutorial
PHP For Windows: Binaries and sources Releases
PHP: The Right Way
Physicians Health Plan of Northern Indiana, Inc. (PHPNI)
Newest 'php' Questions - Stack Overflow
PHP Programming - Wikibooks, open books for an open world



Question: What is URL of Google Explorer API ?
https://developers.google.com/apis-explorer/?hl=en_US#p/customsearch/v1/search.cse.list


Question: Give me example of Full data return by API in JSON Format?

{ "kind": "customsearch#search", "url": { "type": "application/json", "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&amp;num={count?}&amp;start={startIndex?}&amp;lr={language?}&amp;safe={safe?}&amp;cx={cx?}&amp;cref={cref?}&amp;sort={sort?}&amp;filter={filter?}&amp;gl={gl?}&amp;cr={cr?}&amp;googlehost={googleHost?}&amp;c2coff={disableCnTwTranslation?}&amp;hq={hq?}&amp;hl={hl?}&amp;siteSearch={siteSearch?}&amp;siteSearchFilter={siteSearchFilter?}&amp;exactTerms={exactTerms?}&amp;excludeTerms={excludeTerms?}&amp;linkSite={linkSite?}&amp;orTerms={orTerms?}&amp;relatedSite={relatedSite?}&amp;dateRestrict={dateRestrict?}&amp;lowRange={lowRange?}&amp;highRange={highRange?}&amp;searchType={searchType}&amp;fileType={fileType?}&amp;rights={rights?}&amp;imgSize={imgSize?}&amp;imgType={imgType?}&amp;imgColorType={imgColorType?}&amp;imgDominantColor={imgDominantColor?}&amp;alt=json" }, "queries": { "request": [ { "title": "Google Custom Search - php", "totalResults": "508000000", "searchTerms": "php", "count": 10, "startIndex": 1, "inputEncoding": "utf8", "outputEncoding": "utf8", "safe": "off", "cx": "015055756665264721200:zrnkpkfwyga" } ], "nextPage": [ { "title": "Google Custom Search - php", "totalResults": "508000000", "searchTerms": "php", "count": 10, "startIndex": 11, "inputEncoding": "utf8", "outputEncoding": "utf8", "safe": "off", "cx": "015055756665264721200:zrnkpkfwyga" } ] }, "context": { "title": "My Test Website" }, "searchInformation": { "searchTime": 0.526994, "formattedSearchTime": "0.53", "totalResults": "508000000", "formattedTotalResults": "508,000,000" }, "items": [ { "kind": "customsearch#result", "title": "PHP: Hypertext Preprocessor", "htmlTitle": "\u003cb\u003ePHP: Hypertext Preprocessor\u003c/b\u003e", "link": "http://php.net/", "displayLink": "php.net", "snippet": "3 days ago ... Server-side HTML embedded scripting language. It provides web developers \nwith a full suite of tools for building dynamic websites: native APIs ...", "htmlSnippet": "3 days ago \u003cb\u003e...\u003c/b\u003e Server-side HTML embedded scripting language. It provides web developers \u003cbr\u003e\nwith a full suite of tools for building dynamic websites: native APIs ...", "cacheId": "s9KZuwBTtSkJ", "formattedUrl": "php.net/", "htmlFormattedUrl": "\u003cb\u003ephp\u003c/b\u003e.net/", "pagemap": { "cse_thumbnail": [ { "width": "81", "height": "77", "src": "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQ0eKPRpNFSCbNpy4gCBZEwPVyUH9nZyQ_XbcbXanWV8ZarBAKse5lA-A" } ], "metatags": [ { "viewport": "width=device-width, initial-scale=1.0" } ], "cse_image": [ { "src": "http://php.net//images/news/php10thbd.jpg" } ] } }, { "kind": "customsearch#result", "title": "PHP - Wikipedia, the free encyclopedia", "htmlTitle": "\u003cb\u003ePHP\u003c/b\u003e - Wikipedia, the free encyclopedia", "link": "https://en.wikipedia.org/wiki/PHP", "displayLink": "en.wikipedia.org", "snippet": "PHP is a server-side scripting language designed for web development but also \nused as a general-purpose programming language. Originally created by ...", "htmlSnippet": "\u003cb\u003ePHP\u003c/b\u003e is a server-side scripting language designed for web development but also \u003cbr\u003e\nused as a general-purpose programming language. Originally created by ...", "cacheId": "qU2AN8Gt0LkJ", "formattedUrl": "https://en.wikipedia.org/wiki/PHP", "htmlFormattedUrl": "https://en.wikipedia.org/wiki/\u003cb\u003ePHP\u003c/b\u003e", "pagemap": { "cse_thumbnail": [ { "width": "160", "height": "80", "src": "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcREVCk76Rs7cXwmEsYOZPAzcDG4lixebNeXhy4ziXFrfgTtKQ4bCD13PQ" } ], "metatags": [ { "referrer": "origin-when-cross-origin" } ], "cse_image": [ { "src": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/PHP_Logo,_text_only.svg/200px-PHP_Logo,_text_only.svg.png" } ] } }, { "kind": "customsearch#result", "title": "PHP 5 Tutorial", "htmlTitle": "\u003cb\u003ePHP\u003c/b\u003e 5 Tutorial", "link": "http://www.w3schools.com/php/", "displayLink": "www.w3schools.com", "snippet": "PHP is a server scripting language, and a powerful tool for making dynamic and \n... At W3Schools you will find complete references of all PHP functions:.", "htmlSnippet": "\u003cb\u003ePHP\u003c/b\u003e is a server scripting language, and a powerful tool for making dynamic and \u003cbr\u003e\n... At W3Schools you will find complete references of all \u003cb\u003ePHP\u003c/b\u003e functions:.", "cacheId": "8VKxSW_v5GEJ", "formattedUrl": "www.w3schools.com/php/", "htmlFormattedUrl": "www.w3schools.com/\u003cb\u003ephp\u003c/b\u003e/", "pagemap": { "metatags": [ { "viewport": "width=device-width, initial-scale=1" } ] } }, { "kind": "customsearch#result", "title": "PHP | Codecademy", "htmlTitle": "\u003cb\u003ePHP\u003c/b\u003e | Codecademy", "link": "https://www.codecademy.com/learn/php", "displayLink": "www.codecademy.com", "snippet": "Learn to program in PHP, a widespread language that powers sites like \nFacebook.", "htmlSnippet": "Learn to program in \u003cb\u003ePHP\u003c/b\u003e, a widespread language that powers sites like \u003cbr\u003e\nFacebook.", "cacheId": "KACW1XKkN38J", "formattedUrl": "https://www.codecademy.com/learn/php", "htmlFormattedUrl": "https://www.codecademy.com/learn/\u003cb\u003ephp\u003c/b\u003e", "pagemap": { "metatags": [ { "viewport": "width=device-width, initial-scale=1.0", "csrf-param": "authenticity_token", "csrf-token": "yCGsG/vOZD+nnEe9mhqr3+gC4Ibrdi/K8dTzrbbbxpk=", "fb:app_id": "212500508799908", "og:url": "https://www.codecademy.com/learn/php", "og:site_name": "Codecademy", "og:type": "article", "og:title": "PHP", "og:description": "Learn to program in PHP, a widespread language that powers sites like Facebook." } ] } }, { "kind": "customsearch#result", "title": "PHP Tutorial", "htmlTitle": "\u003cb\u003ePHP\u003c/b\u003e Tutorial", "link": "http://www.tutorialspoint.com/php/", "displayLink": "www.tutorialspoint.com", "snippet": "PHP Tutorial for Beginners - A simple and short PHP tutorial and complete \nreference manual for all built-in PHP functions. This tutorial is designed for \nbeginners ...", "htmlSnippet": "\u003cb\u003ePHP\u003c/b\u003e Tutorial for Beginners - A simple and short \u003cb\u003ePHP\u003c/b\u003e tutorial and complete \u003cbr\u003e\nreference manual for all built-in \u003cb\u003ePHP\u003c/b\u003e functions. This tutorial is designed for \u003cbr\u003e\nbeginners ...", "cacheId": "pZNex8X8UWIJ", "formattedUrl": "www.tutorialspoint.com/php/", "htmlFormattedUrl": "www.tutorialspoint.com/\u003cb\u003ephp\u003c/b\u003e/", "pagemap": { "cse_thumbnail": [ { "width": "204", "height": "155", "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ8PER4KIXsaae0nNy3Na4XIoSGeqH83TGs4r5Eo1lSKGDVDH2_RCJi1M8" } ], "metatags": [ { "viewport": "width=device-width,initial-scale=1.0,user-scalable=yes", "og:locale": "en_US", "og:type": "website", "fb:app_id": "471319149685276", "og:site_name": "www.tutorialspoint.com", "apple-mobile-web-app-capable": "yes", "apple-mobile-web-app-status-bar-style": "black", "author": "tutorialspoint.com" } ], "cse_image": [ { "src": "http://www.tutorialspoint.com/php/images/php-mini-logo.jpg" } ] } }, { "kind": "customsearch#result", "title": "PHP For Windows: Binaries and sources Releases", "htmlTitle": "\u003cb\u003ePHP\u003c/b\u003e For Windows: Binaries and sources Releases", "link": "http://windows.php.net/download/", "displayLink": "windows.php.net", "snippet": "This site is dedicated to supporting PHP on Microsoft Windows. It also supports \nports of ... PHP 7.1. 7.1 has no release. PHP 7.0 (7.0.7). Download source code ...", "htmlSnippet": "This site is dedicated to supporting \u003cb\u003ePHP\u003c/b\u003e on Microsoft Windows. It also supports \u003cbr\u003e\nports of ... \u003cb\u003ePHP\u003c/b\u003e 7.1. 7.1 has no release. \u003cb\u003ePHP\u003c/b\u003e 7.0 (7.0.7). Download source code ...", "cacheId": "LZ-At1_VxXEJ", "formattedUrl": "windows.php.net/download/", "htmlFormattedUrl": "windows.\u003cb\u003ephp\u003c/b\u003e.net/download/" }, { "kind": "customsearch#result", "title": "PHP: The Right Way", "htmlTitle": "\u003cb\u003ePHP\u003c/b\u003e: The Right Way", "link": "http://www.phptherightway.com/", "displayLink": "www.phptherightway.com", "snippet": "4 days ago ... An easy-to-read, quick reference for PHP best practices, accepted coding \nstandards, and links to authoritative PHP tutorials around the Web.", "htmlSnippet": "4 days ago \u003cb\u003e...\u003c/b\u003e An easy-to-read, quick reference for \u003cb\u003ePHP\u003c/b\u003e best practices, accepted coding \u003cbr\u003e\nstandards, and links to authoritative \u003cb\u003ePHP\u003c/b\u003e tutorials around the Web.", "cacheId": "SkEDu_-C2_YJ", "formattedUrl": "www.phptherightway.com/", "htmlFormattedUrl": "www.\u003cb\u003ephp\u003c/b\u003etherightway.com/", "pagemap": { "metatags": [ { "og:image:url": "http://www.phptherightway.com/images/og-image.png", "og:image:width": "1024", "og:image:height": "640", "og:title": "PHP: The Right Way", "og:description": "An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web", "og:url": "http://www.phptherightway.com", "og:site_name": "PHP: The Right Way", "og:type": "website", "viewport": "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" } ] } }, { "kind": "customsearch#result", "title": "Physicians Health Plan of Northern Indiana, Inc. (PHPNI)", "htmlTitle": "\u003cb\u003ePhysicians Health Plan\u003c/b\u003e of Northern Indiana, Inc. (PHPNI)", "link": "http://www.phpni.com/", "displayLink": "www.phpni.com", "snippet": "We care about your healthcare needs. PHP understands the business of \nhealthcare and knows how important good health is to the quality of life. Our staff \nof ...", "htmlSnippet": "We care about your healthcare needs. \u003cb\u003ePHP\u003c/b\u003e understands the business of \u003cbr\u003e\nhealthcare and knows how important good health is to the quality of life. Our staff \u003cbr\u003e\nof ...", "cacheId": "kgzNo6SonKwJ", "formattedUrl": "www.phpni.com/", "htmlFormattedUrl": "www.\u003cb\u003ephp\u003c/b\u003eni.com/", "pagemap": { "cse_thumbnail": [ { "width": "182", "height": "143", "src": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQgzIyBIT9mt4ob6wj9DsJ4qzDMZFR-EGRL2ZPbGhYzntiGwsdiG6UYbJtt" } ], "cse_image": [ { "src": "http://www.phpni.com/Images/Misc/HIXUracSeal2019.png" } ] } }, { "kind": "customsearch#result", "title": "Newest 'php' Questions - Stack Overflow", "htmlTitle": "Newest '\u003cb\u003ephp\u003c/b\u003e' Questions - Stack Overflow", "link": "http://stackoverflow.com/questions/tagged/php", "displayLink": "stackoverflow.com", "snippet": "I'm having a bad brain fart... Ok, so i'm looking for a simple php script that will look \nthrough my database for a username and echo a column. The column I want ...", "htmlSnippet": "I'm having a bad brain fart... Ok, so i'm looking for a simple \u003cb\u003ephp\u003c/b\u003e script that will look \u003cbr\u003e\nthrough my database for a username and echo a column. The column I want ...", "cacheId": "4h3qSIyRzagJ", "formattedUrl": "stackoverflow.com/questions/tagged/php", "htmlFormattedUrl": "stackoverflow.com/questions/tagged/\u003cb\u003ephp\u003c/b\u003e", "pagemap": { "cse_thumbnail": [ { "width": "225", "height": "225", "src": "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqiMqeE25uz0622Vj9Cvxf2QlczrckZNpgcCthUPsXMgvzR_AktvSQoMz" } ], "qapage": [ { "image": "http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&amp;a", "primaryimageofpage": "http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&amp;a", "title": "Newest 'php' Questions", "name": "Newest 'php' Questions", "description": "Q&amp;A for professional and enthusiast programmers" } ], "metatags": [ { "twitter:card": "summary", "twitter:domain": "stackoverflow.com", "og:type": "website", "og:image": "http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&amp;a", "twitter:title": "Newest 'php' Questions", "twitter:description": "Q&amp;A for professional and enthusiast programmers", "og:url": "http://stackoverflow.com/questions/tagged/php" } ], "cse_image": [ { "src": "http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&amp;a" } ] } }, { "kind": "customsearch#result", "title": "PHP Programming - Wikibooks, open books for an open world", "htmlTitle": "\u003cb\u003ePHP\u003c/b\u003e Programming - Wikibooks, open books for an open world", "link": "https://en.wikibooks.org/wiki/PHP_Programming", "displayLink": "en.wikibooks.org", "snippet": "A wikibook about programming in PHP. Also provides external links for more \ninformation.", "htmlSnippet": "A wikibook about programming in \u003cb\u003ePHP\u003c/b\u003e. Also provides external links for more \u003cbr\u003e\ninformation.", "cacheId": "eY2r0GBtEgkJ", "formattedUrl": "https://en.wikibooks.org/wiki/PHP_Programming", "htmlFormattedUrl": "https://en.wikibooks.org/wiki/\u003cb\u003ePHP\u003c/b\u003e_Programming", "pagemap": { "cse_thumbnail": [ { "width": "183", "height": "275", "src": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcS13jbwM9UIs5ekUya3TcycwhkH89RXdXRjtasahlTQzc-uwPOTPbNBZDTa" } ], "metatags": [ { "referrer": "origin-when-cross-origin" } ], "cse_image": [ { "src": "https://upload.wikimedia.org/wikipedia/commons/f/ff/PHPWikibookCover.png" } ] } } ] } 




Thursday 17 March 2016

How to post raw data using CURL in PHP?

How to post raw data using CURL in PHP

Question: How to POST data using CURL in PHP?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,            "http://domain.com/ajax/postdata" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     '{"2016-3-18":[],"2016-03-19":[["15:00","19:00"]],"2016-3-18":[],"2016-3-19":[],"2016-3-20":[],"2016-3-21":[],"2016-3-22":[],"2016-3-23":[],"2016-3-24":[],"2016-3-25":[],"2016-3-26":[],"2016-3-27":[],"2016-3-28":[],"2016-3-29":[],"2016-3-30":[],"2016-3-31":[],"2016-4-1":[],"2016-4-2":[],"2016-4-3":[],"2016-4-4":[],"2016-4-5":[],"2016-4-6":[],"2016-4-7":[],"2016-4-8":[],"2016-4-9":[],"2016-4-10":[],"2016-4-11":[],"2016-4-12":[]}' ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 
echo $result=curl_exec ($ch);



Question: How to read Raw data with PHP?
     $rawData= file_get_contents('php://input');
     /** Use the rawData **/

     /** Use the rawData **/



Friday 8 May 2015

Youtube v3 API Sample API Requests and Response - Search Videos - Get Video Details

Youtube v3 API Sample API Requests and Response - Search Videos - Get Video Details


For youtube v3 API, you must need an API_KEY for video search, get video details, upload video and delete video etc.
In each request, you need to pass the APK_KEY to get the records, If you didn't pass the API_KEY, you will not get the response from youtube api.

In Youtube V2 API_KEY is not required, but its is compulsary for youtube V3 API.
google has stopped the youtube v2 API so you must use V3 API.

If you don't have API_KEY, please get the API Key from http://code.google.com/apis/console#access .
You must need google account for youtube v3 API.
Youtube v3 API Sample API Requests and Response - Search Video List - Get Video Details


Now, I am assuming you have valid API_KEY. if you have added referer while creating API, then you can use API_KEY for that domain only. Yeah you can add multiple domain for 1 key.
Suppose we have following API_KEY.
API_KEY: AIzaSyBqXp0Uo2ktJcMRpL_ZwF5inLTWZfsCYqY

Also you must enable the "YouTube Data API" from google console for the same key.

Get List of youtube Videos (By Default It will gives 4 videos)
https://www.googleapis.com/youtube/v3/search?part=snippet&key=AIzaSyBqXp0Uo2ktJcMRpL_ZwF5inLTWZfsCYqY


Get List of youtube videos (Search 40 videos)
https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=40&key=AIzaSyBqXp0Uo2ktJcMRpL_ZwF5inLTWZfsCYqY


Get List of youtube videos (Search 40 videos + having keyword "sports" )
https://www.googleapis.com/youtube/v3/search?part=snippet&q=sports&maxResults=40&key=AIzaSyBqXp0Uo2ktJcMRpL_ZwF5inLTWZfsCYqY


Get List of youtube videos( Search with 100km of 37.42307,-122.08427(lat/long)
https://www.googleapis.com/youtube/v3/search?locationRadius=100km&part=snippet&location=37.42307%2C-122.08427&type=video&key=AIzaSyBqXp0Uo2ktJcMRpL_ZwF5inLTWZfsCYqY


Get List of youtube videos (search videos which are tags with sports [videoCategoryId=17])
https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&videoCategoryId=17&key=AIzaSyBqXp0Uo2ktJcMRpL_ZwF5inLTWZfsCYqY


Response Format:
{"kind":"youtube#searchListResponse","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/okahf16vRr9O67w1AX2xksAkmDI\"","nextPageToken":"CAUQAA","pageInfo":{"totalResults":1000000,"resultsPerPage":5},"items":[{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/EIQjGNXfg22wA149MrmBxBM3QX4\"","id":{"kind":"youtube#video","videoId":"a2RA0vsZXf8"},"snippet":{"publishedAt":"2010-11-21T05:14:05.000Z","channelId":"UCplkk3J5wrEl0TNrthHjq4Q","title":"\"Just A Dream\" by Nelly - Sam Tsui & Christina Grimmie","description":"Check out our epic song with Coke Bottles! https://www.youtube.com/watch?v=ZzuRvzsNpTU Hope you guys like this duet between Christina Grimmie and Sam ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/hqdefault.jpg"}},"channelTitle":"KurtHugoSchneider","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/3bB0h6KJXx-TPbAqXKd5nADWGX0\"","id":{"kind":"youtube#video","videoId":"Ahha3Cqe_fk"},"snippet":{"publishedAt":"2011-11-11T18:37:24.000Z","channelId":"UC-8Q-hLdECwQmaWNwXitYDw","title":"Katy Perry - The One That Got Away","description":"Sometimes you promise someone forever but it doesn't work out that way. Watch Katy Perry and Diego Luna star in the sixth chapter of the “Teenage Dream” ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/Ahha3Cqe_fk/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/Ahha3Cqe_fk/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/Ahha3Cqe_fk/hqdefault.jpg"}},"channelTitle":"KatyPerryVEVO","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/VZLQn8wfLOJ60oe6Bced9ryD7Kg\"","id":{"kind":"youtube#video","videoId":"NV7xJ73_eeM"},"snippet":{"publishedAt":"2014-11-17T14:00:19.000Z","channelId":"UCMu5gPmKp5av0QCAajKTMhw","title":"Romeo and Juliet vs Bonnie and Clyde. Epic Rap Battles of History Season 4","description":"Download on iTunes ▻ http://bit.ly/1yN7aai ◅ Season 3 Autographed CDs available at ▻ http://shop.erb.fm ◅ Subscribe for more battles! http://bit.ly/1ElwJ40 ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/NV7xJ73_eeM/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/NV7xJ73_eeM/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/NV7xJ73_eeM/hqdefault.jpg"}},"channelTitle":"ERB","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/IN61vHPZ3FNoK9mme_Kf9E0U50c\"","id":{"kind":"youtube#video","videoId":"XjwZAa2EjKA"},"snippet":{"publishedAt":"2013-11-20T08:03:53.000Z","channelId":"UC-8Q-hLdECwQmaWNwXitYDw","title":"Katy Perry - Unconditionally (Official)","description":"Download \"Unconditionally\" from Katy Perry's 'PRISM': http://smarturl.it/PRISM Official video for Katy Perry's \"Unconditionally\" directed by Brent Bonacorso and ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/XjwZAa2EjKA/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/XjwZAa2EjKA/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/XjwZAa2EjKA/hqdefault.jpg"}},"channelTitle":"KatyPerryVEVO","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/gKZhz62FdXndZR7dJdi_PDTpe9U\"","id":{"kind":"youtube#video","videoId":"-kWHMH2kxXs"},"snippet":{"publishedAt":"2014-11-01T04:10:36.000Z","channelId":"UC8-Th83bH_thdKZDJCrn88g","title":"Wheel of Impressions with Kevin Spacey","description":"In this Halloween edition of Wheel of Impressions, Jimmy and Kevin take turns doing random celebrity impersonations, such as Christopher Walken talking ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/-kWHMH2kxXs/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/-kWHMH2kxXs/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/-kWHMH2kxXs/hqdefault.jpg"}},"channelTitle":"latenight","liveBroadcastContent":"none"}}]}



Get Youtube Videos by Channel
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCv7IjJclSgpfGUHnG171ovw&order=date&key=AIzaSyBpu8hgnXbkqFVWrAvwRUEz7T13ii3I7WM
Response Format:
{"kind":"youtube#searchListResponse","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/q7tdIBpMwbnE_LWyfCaBtuEXMes\"","nextPageToken":"CAUQAA","pageInfo":{"totalResults":296,"resultsPerPage":5},"items":[{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/kvgjXpyJJ1CVnWs7i6kI_3-X0go\"","id":{"kind":"youtube#video","videoId":"drsH-pNpxho"},"snippet":{"publishedAt":"2015-04-23T14:21:19.000Z","channelId":"UCv7IjJclSgpfGUHnG171ovw","title":"A4 Pain - Painkiller #7 by Fez","description":"Insane new episode from A4 Pain Player: A4 Pain https://www.youtube.com/channel/UCVSS_0NReZbN3phT1OSKseQ Editor: Fez TOS ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/drsH-pNpxho/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/drsH-pNpxho/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/drsH-pNpxho/hqdefault.jpg"}},"channelTitle":"TheApokalypse4","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/t-udHC0CmSmK9Ej_q8KQgfHpyAo\"","id":{"kind":"youtube#video","videoId":"4kq8pW3ML0M"},"snippet":{"publishedAt":"2015-04-09T20:09:46.000Z","channelId":"UCv7IjJclSgpfGUHnG171ovw","title":"Apokalypse4 Killcams of the week - Episode 12","description":"Yes this is a weekly, episode we're trying to bring out more content for you guys, this is a example. Hope you enjoy! [CLICK SHOW MORE] This weeks winners!","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/4kq8pW3ML0M/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/4kq8pW3ML0M/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/4kq8pW3ML0M/hqdefault.jpg"}},"channelTitle":"TheApokalypse4","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/2_P60vNc53lyEX63yeKf_wlXYSk\"","id":{"kind":"youtube#video","videoId":"faizfXUbCAc"},"snippet":{"publishedAt":"2015-04-05T15:35:47.000Z","channelId":"UCv7IjJclSgpfGUHnG171ovw","title":"Apokalypse4 Challenges you - Episode 13","description":"Winner's chosen on the 1st of May, submit your ONLINE responses through twitter to @tehapokalypse4 and follow us for further information, good luck guys!","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/faizfXUbCAc/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/faizfXUbCAc/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/faizfXUbCAc/hqdefault.jpg"}},"channelTitle":"TheApokalypse4","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/JVw8gcWNDBq6A0k3NzNYydX7n4A\"","id":{"kind":"youtube#video","videoId":"vHTMfV7sJVg"},"snippet":{"publishedAt":"2015-03-25T16:10:24.000Z","channelId":"UCv7IjJclSgpfGUHnG171ovw","title":"A4 Sponge: Cleaning up - Episode 1","description":"Insane feeder and editor collaborate and produce a insane episode, enjoy guys! Subscribe :) http://bit.ly/SubToA4 10000 Teamtage ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/vHTMfV7sJVg/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/vHTMfV7sJVg/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/vHTMfV7sJVg/hqdefault.jpg"}},"channelTitle":"TheApokalypse4","liveBroadcastContent":"none"}},{"kind":"youtube#searchResult","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/imFn4cchjV1Gbp9F2zt9P-FgIvU\"","id":{"kind":"youtube#video","videoId":"AAMk41lxuyA"},"snippet":{"publishedAt":"2015-03-09T19:47:21.000Z","channelId":"UCv7IjJclSgpfGUHnG171ovw","title":"TheFantastic4 - ft. Gibby, Frizzy, Metal, Pregs by Cayzuh","description":"the ex a4 players return one last time. gibby https://www.youtube.com/user/ByGibbio frizzy https://www.youtube.com/user/OnyxFreeZy metal ...","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/AAMk41lxuyA/default.jpg"},"medium":{"url":"https://i.ytimg.com/vi/AAMk41lxuyA/mqdefault.jpg"},"high":{"url":"https://i.ytimg.com/vi/AAMk41lxuyA/hqdefault.jpg"}},"channelTitle":"TheApokalypse4","liveBroadcastContent":"none"}}]}




Get youtube video Detail
To get the youtube video detail, you must have an valid youtube video.
https://www.googleapis.com/youtube/v3/videos?id=a2RA0vsZXf8&part=snippet,statistics&key=AIzaSyBqXp0Uo2ktJcMRpL_ZwF5inLTWZfsCYqY
Response Format:
{"kind":"youtube#videoListResponse","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/5O69VO4RLDboG2ONvOiRwnoX77I\"","pageInfo":{"totalResults":1,"resultsPerPage":1},"items":[{"kind":"youtube#video","etag":"\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/7xlJyY3lj1NCugehSg-sBnEM0YQ\"","id":"a2RA0vsZXf8","snippet":{"publishedAt":"2010-11-21T04:52:18.000Z","channelId":"UCplkk3J5wrEl0TNrthHjq4Q","title":"\"Just A Dream\" by Nelly - Sam Tsui & Christina Grimmie","description":"Check out our epic song with Coke Bottles! https://www.youtube.com/watch?v=ZzuRvzsNpTU\n\nHope you guys like this duet between Christina Grimmie and Sam Tsui on \"Just A Dream\" originally by Nelly!\n\nAnd if you don't know Christina, definitely check out her stuff and subscribe to her, because she rocks!!\nhttp://www.youtube.com/zeldaxlove64\n\nShare this on Facebook!  http://on.fb.me/JustADreamSamChristina\n\nWe just opened an online store with shirts, cd's and other cool stuff here:\nhttp://www.kurthugoschneider.com/store\n\n\n--------------\n\nLinks\n\nKURT SCHNEIDER\nFacebook- http://www.facebook.com/KurtHugoSchneider\nTwitter- http://www.twitter.com/KurtHSchneider\n\nSAM TSUI\nFacebook- http://www.facebook.com/SamTsuiMusic\nTwitter- http://www.twitter.com/SamuelTsui\n\n---------------\n\n'Just A Dream' (originally Performed By Nelly)\nWritten By: Cornell Haynes, Frank Romano, Jim Jonsin, James Scheffer, Richard Butler\nPublished By: Universal Music Publishing / EMI Music Publishing / Reach Global Inc.","thumbnails":{"default":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/default.jpg","width":120,"height":90},"medium":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/mqdefault.jpg","width":320,"height":180},"high":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/hqdefault.jpg","width":480,"height":360},"standard":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/sddefault.jpg","width":640,"height":480},"maxres":{"url":"https://i.ytimg.com/vi/a2RA0vsZXf8/maxresdefault.jpg","width":1280,"height":720}},"channelTitle":"Kurt Hugo Schneider","categoryId":"10","liveBroadcastContent":"none","localized":{"title":"\"Just A Dream\" by Nelly - Sam Tsui & Christina Grimmie","description":"Check out our epic song with Coke Bottles! https://www.youtube.com/watch?v=ZzuRvzsNpTU\n\nHope you guys like this duet between Christina Grimmie and Sam Tsui on \"Just A Dream\" originally by Nelly!\n\nAnd if you don't know Christina, definitely check out her stuff and subscribe to her, because she rocks!!\nhttp://www.youtube.com/zeldaxlove64\n\nShare this on Facebook!  http://on.fb.me/JustADreamSamChristina\n\nWe just opened an online store with shirts, cd's and other cool stuff here:\nhttp://www.kurthugoschneider.com/store\n\n\n--------------\n\nLinks\n\nKURT SCHNEIDER\nFacebook- http://www.facebook.com/KurtHugoSchneider\nTwitter- http://www.twitter.com/KurtHSchneider\n\nSAM TSUI\nFacebook- http://www.facebook.com/SamTsuiMusic\nTwitter- http://www.twitter.com/SamuelTsui\n\n---------------\n\n'Just A Dream' (originally Performed By Nelly)\nWritten By: Cornell Haynes, Frank Romano, Jim Jonsin, James Scheffer, Richard Butler\nPublished By: Universal Music Publishing / EMI Music Publishing / Reach Global Inc."}},"statistics":{"viewCount":"96352554","likeCount":"804825","dislikeCount":"8957","favoriteCount":"0","commentCount":"132350"}}]}





Tuesday 27 January 2015

Google trends api php - How to get hot trends

Google trends api php - How to get hot trends


Google Trends is a public web facility of Google Inc., based on Google Search, that shows how often a particular search-term is entered relative to the total search-volume across various regions of the world, and in various languages. 
From: en.wikipedia.org/wiki/Google_Trends


Use following code to get the hot trends from google.
  
try {            
            $url='http://www.google.com/trends/hottrends/atom/hourly';                        
            $client = new Zend_Http_Client($url);
            $response = $client->request('GET');
            $jsonData = ($response->getBody());
            echo 'Google Trends';            
            preg_match_all('/(.*)<\/a>/', $jsonData, $trends);
            /** preg_match_all('/(.*)<\/a>/', $jsonData, $trends);**/
             foreach($trends[0] as $trend) {
                echo "{$trend}";
                }

        } catch (Exception $e) {
            echo 'Error' . $e->getMessage();
        }     

Saturday 25 October 2014

How do I get a YouTube video thumbnail from the YouTube

How do I get a YouTube video thumbnail from the YouTube




How to get youtube video thumbnail
1. First Get the Video URL (Video URL is like https://www.youtube.com/v/J0Qu6eyyr4c)
2. Get the youtube video Id from Video URL (Video id is like J0Qu6eyyr4c)
3. Now video thumbnail is ready.


Small Video Image
How do I get a YouTube video thumbnail from the YouTube
http://img.youtube.com/vi/J0Qu6eyyr4c/default.jpg 



Bigger Video Thumbnail
How do I get a YouTube video thumbnail from the YouTube
http://img.youtube.com/vi/J0Qu6eyyr4c/mqdefault.jpg



Large Video Thumbnail
How do I get a YouTube video thumbnail from the YouTube
http://img.youtube.com/vi/J0Qu6eyyr4c/hqdefault.jpg



Tuesday 20 May 2014

Difference between WebService and API

Difference between WebService and API


S.No
Web Service
API
1
Interaction between two machines over a network. Interaction between two API.
2
Uses SOAP, REST, and XML-RPC as a means of communication. It may use any way to communication
3
Web Services involves calling of system. We can render form in one line, one by one element, element OR  decorator OR error separately.
4
Web service might not contain a complete set of specifications and sometimes might not be able to perform all the tasks that may be possible from a complete API. An API consists of a complete set of rules and specifications for a software program to follow in order to facilitate interaction.
5
All Web services are APIs All APIs are not Web services
6
A Web service always needs a network for its operation API doesn't need a network for its operation
7
WebServices are services available over internet. You can call these services and get so information in your application without know how it works. For example weather webservices gives you information about the city weather. API is a collection of class which provide you some functionality like Google api gives google-search.