Getting started with API’s and PHP

Discussion in 'Tutorials' started by kavin, Mar 9, 2012.

A forum by Ionicware
  1. kavin Member

    Message Count:
    266
    Likes Received:
    21
    This tutorial is created by kavin, and is exclusive to the AdminPeak.com community. Copying or re-publishing of this tutorial is strictly prohibited.

    An API (Application programming interface) is an interface between a software/service and external softwares or services accessing their data. Several softwares, and some sites like Facebook, Twitter, etc; provide API’s to enable external softwares to communicate with them. There are also various types of communication, example XML, JSON, and some provide HTML and text interfaces too. Its ultimately the developers decision which one to use among the ones provided by the specific API. Since XML is most commonly present in almost all API’s, I will explain about working with XML data.

    Every API have their own set of routines, variables etc; so its definitely not a “learn once…” thing. But the general concept involved is same.
    1) You make an API call.
    2) Parse the returned data for variables.
    3) Display those variables as we want.
    In this tutorial we will see, how to access Namecheap’s API and check for availability of some domains through it.
    Namecheap is a popular domain registrar, and they recently introduced an API feature. With their API you can do almost all operations like checking domain availability, register a domain, modify nameservers, modify contact details, etc; You can learn more about Namecheap API here.
    http://developer.namecheap.com/docs/doku.php?id=api-reference:index

    For our tutorial we will do the following:
    1) Check availability of two domains called, adminpeak.com and kavin12345.com.
    2) Parse the returned data using Simple XML (an inbuilt function of PHP to parse XML data).
    3) Display the domain availability in a table.
    From the reference page I linked above, we can see that namecheap.domains.check is the command for checking domains. Full details about how to build the command and an example return data is shown at its reference page.
    http://developer.namecheap.com/docs/doku.php?id=api-reference:domains:check

    The command is:
    https://api.namecheap.com/xml.response?ApiUser=apiexample&ApiKey=56b4c87ef4fd49cb96d915c0db68194&UserName=apiexample&Command=namecheap.domains.check&ClientIp=192.168.1.109&DomainList=domain1.com,availabledomain.com

    The API user and API key values can be obtained by registering a developer account at..
    http://developer.namecheap.com
    The Username is the username of your namecheap account (under which you registered the developer account).
    Namecheap.domains.check is the command for checking domain availability. If you need to do a different function (like changing nameservers), then you should consult the reference manual and use appropriate command for that function.
    ClientIP is the IP address of the user (your website visitor) currently running the command. In PHP you can get the client IP info by using $_SERVER['REMOTE_ADDR'].

    So, while coding, we would have a command like this (assigned to a variable named command for example).

    PHP:
    $command ‘https://api.namecheap.com/xml.response?ApiUser=apiexample&ApiKey=56b4c87ef4fd49cb96d915c0db68194&UserName=apiexample&Command=namecheap.domains.check&ClientIp='.$_SERVER['REMOTE_ADDR'].'&DomainList=adminpeak.com,kavin12345.com’;
    We can execute the command by loading it with file_get_contents like this…
    PHP:
    $data file_get_contents($command);
    The above code will execute the command, get returned XML data and store it to $data variable.
    So our $data variable will have an XML data like this.



    The following two lines have the actual data we want.
    <DomainCheckResult Domain="adminpeak.com" Available="false" />
    <DomainCheckResult Domain="kavin12345.com" Available="true" />

    The Available=”false” denotes adminpeak.com is not available and Available=”true” denotes kavin12345.com is available for register.

    In order to parse the data we should first load it in SimpleXML. As I previously said, SimpleXML is an inbuilt function of PHP to parse XML data.
    PHP:
    $xml simplexml_load_string($data);
    That command loads the XMl data stored in $data variable to $xml using SimpleXML.
    Next we should check whether the load is successful.


    PHP:
    if( ! $xml)
        {
    //code to do when load failed.
    //Example:
            
    echo 'unable to load XML file';
        }
        else
        {
    //code to do when load successful.
    //We can now use the parsed data.
    }
    Now since the parsed data is stored in $xml, we can access DomainCheckResult in the XML by the following variable.
    $xml ->CommandResponse->DomainCheckResult

    CommandResponse is parent of DomainCheckResult element which has the availability data.

    Since we have two DomainCheckResult’s, we can pass it through foreach, and echo individual results.
    PHP:

    foreach ($xml->CommandResponse->DomainCheckResult as $result)  {
    echo 
    $result['Domain'].:$result[‘Available'].’<br />’;
    }
    The above code will echo something like this..
    Adminpeak.com: false
    Kavin12345.com: true

    We have successfully used API to check the availability of a domain name. Every API will have their own XML structure which you can read from their manual and then access those values according to that.

    The complete code for the above example will look like this.
    PHP:
    <?php
    $command 
    [URL='https://api.namecheap.com/xml.response?ApiUser=apiexample&ApiKey=56b4c87ef4fd49cb96d915c0db68194&UserName=apiexample&Command=namecheap.domains.check&ClientIp=%27.%20$_SERVER%5b%27REMOTE_ADDR%27%5d.%27&DomainList=adminpeak.com,kavin12345.com']https://api.namecheap.com/xml.response?ApiUser=[B]apiexample[/B]&ApiKey=[B]56b4c87ef4fd49cb96d915c0db68194[/B]&UserName=[B]apiexample[/B]&Command=[B]namecheap.domains.check[/B]&ClientIp=[B]’.[/B] $_SERVER['REMOTE_ADDR'][B].’[/B]&DomainList=[B]adminpeak.com,kavin12345.com[/B][/URL]’;
    $data file_get_contents($command);
    $xml simplexml_load_string($data);
    if( ! 
    $xml)
        {
            echo 
    'unable to load XML file';
        }
        else
        {
    foreach (
    $xml->CommandResponse->DomainCheckResult as $result)  {
    echo 
    $result['Domain'].:$result[‘Available'].’<br />’;
    }
    }
     
    ?>

  2. karoshio Administrator

    Message Count:
    2,733
    Likes Received:
    125
    Great tutorial Kavin, definitely the perfect start to anyone looking to start working more with API's. I look forward to your next PHP tutorial.

  3. kavin Member

    Message Count:
    266
    Likes Received:
    21
    Glad it helps. :)
    Will be writing some more tutorials soon. :)

  4. sambling Member

    Message Count:
    274
    Likes Received:
    8
    Thanks a lot Kavin, when I keep going with my php learning I'll be sure to come back here- I was really kerfuffled as to how to use API's with php :)

  5. Alex Well-Known Member

    Message Count:
    2,676
    Likes Received:
    94
    Excellent tutorial Kavin, I can tell a lot of time was put into it. :)

  6. kavin Member

    Message Count:
    266
    Likes Received:
    21
    Glad to hear that Sambling. Let me know if you need any help with it. :)

    Did a project using Namecheap's API, but dropped in middle since Namecheap needs $50 to be deposited to use their API.
    Thought i can make it a tutorial so that i can help someone to work with API's.

  7. XLawlessBaronX Moderator

    Message Count:
    345
    Likes Received:
    28
    I am at the moment trying to integrate Battlefield 3 API in with my Xenforo site

  8. kavin Member

    Message Count:
    266
    Likes Received:
    21

  9. XLawlessBaronX Moderator

    Message Count:
    345
    Likes Received:
    28
    do i change the values and make this a .php file?

  10. kavin Member

    Message Count:
    266
    Likes Received:
    21
    Yes. the print_r($data) will print the $data array (which contains all info you need).
    Note down the specific varaibles which you will need, and then use them as you wish. Remember to remove or comment out the print_r($data) after you build the app (since its for debugging purpose only). :)

  11. XLawlessBaronX Moderator

    Message Count:
    345
    Likes Received:
    28
    Ok when i have the time i will give it a shot

  12. kavin Member

    Message Count:
    266
    Likes Received:
    21
    That's great. :)
    Good luck.

  13. TheModdersLounge Member

    Message Count:
    50
    Likes Received:
    1
    Great post looks like alot of time and effort was put into this keep up the good work :)

  14. kavin Member

    Message Count:
    266
    Likes Received:
    21
    Thanks TheModdersLounge. :)

  15. Anthony Ciulla Administrator

    Message Count:
    225
    Likes Received:
    10
    Really good tutorial, I had always wondered what an API is.

  16. kavin Member

    Message Count:
    266
    Likes Received:
    21
    Thanks Anthony. :)
    Glad it helps. Let me know if you have any doubt in future.

  17. Anthony Ciulla Administrator

    Message Count:
    225
    Likes Received:
    10
    Ok, Thank You.

  18. sambling Member

    Message Count:
    274
    Likes Received:
    8
    I do actually Kavin.... I am trying to do a charitable project with all affiliate earnings going toward poverty in NZ. The site is at http://thebookstore.co.nz but I can't seem to get the API to work. It returns a cannot load XML...

    My current code is:

    PHP:
    <?php
    $keywords
    =$_POST["keywords"];
    $ipadd=$_SERVER['REMOTE_ADDR'];
    $command "http://api.bookdepository.co.uk/search/books?clientId=thebookstorenz&authenticationKey=EDITEDOUT&IP=$ipadd&keywords=$keywords";
    $data =  @file_get_contents($command);
    $xml simplexml_load_string($data);
    if( ! 
    $xml)
        {
            echo 
    'unable to load XML file';
        }
        else
        {
    foreach (
    $xml -> result as $result)  {
    echo (
    $xml->title);
    }
    }
    ?>
    And here is part of the xml I am getting:

    Code:
    <result>
    <resultset>
    <status code="1">
    Success
    </status>
    <results>
    20
    </results>
    <totalResults>
    325
    </totalResults>
    <currentPage>
    1
    </currentPage>
    <totalPages>
    17
    </totalPages>
    </resultset>
    <items>
    <item>
    <identifiers>
    <isbn13>
    9780195204698
    </isbn13>
    </identifiers>
    <url type="direct">
    http://www.bookdepository.co.uk/Keywords-Raymond-Williams/9780195204698?utm_medium=api&utm_campaign=thebookstorenz&a_aid=thebookstorenz&utm_term=&utm_source=book_link&utm_content=Keywords
    </url>
    <biblio>
    <title>
    Keywords
    </title>
    <format>
    Paperback
    </format>
    </biblio>
    <availability>
    Usually dispatched within 48 hours
    </availability>
    <pricing>
    <price currency="GBP">
    <retail>
    12.79
    </retail>
    <selling>
    10.40
    </selling>
    </price>
    </pricing>
    <contributors>
    <contributor>
    <name>
    Raymond Williams
    </name>
    <roleDescription>
    By (author)
    </roleDescription>
    <url type="search">
    http://www.bookdepository.co.uk/search/advanced?searchAuthor=Raymond+Williams&utm_medium=api&utm_campaign=thebookstorenz&a_aid=thebookstorenz&utm_term=&utm_source=contributor_link&utm_content=Raymond-Williams
    </url>
    </contributor>
    </contributors>
    @kavin any help would be appreciated! :)

  19. allmyposts New Member

    Message Count:
    26
    Likes Received:
    0
    Liked the fact that you actually used an example for the tutorial.

    I was wondering if I can play with GFC API, I know, it is retired .. but my plan is .. if twitter user can follow a blog using GFC API, it means, the GFC is still working.. somehow it is internally able to access the API.

    So .. got any ideas, about how I can start with??

  20. dorothymoreno54 New Member

    Message Count:
    19
    Likes Received:
    1
    I never knew what API was until reading your tutorial, very interesting , Keep up the good work.

Share This Page