Jump to content


Photo

Creating a Public API

api

  • Please log in to reply
12 replies to this topic

#1 computermax2328

computermax2328

    Advanced Member

  • Members
  • PipPipPip
  • 285 posts
  • LocationUnited States
  • Age:22

Posted 11 November 2013 - 04:28 PM

Hey All,

 

Does anyone have any good articles or books on how to create a public API with PHP. I understand how API's work, although it wouldn't hurt to read up on them, but I am really just looking to understand how one can be built with PHP.

 

Thanks in advance,


Follow me on Twitter @maxrbaldwin


#2 computermax2328

computermax2328

    Advanced Member

  • Members
  • PipPipPip
  • 285 posts
  • LocationUnited States
  • Age:22

Posted 11 November 2013 - 04:45 PM

I am gonna answer my own question on this, but if anyone wants to chime in with any best practices or experiences they have had building an API with PHP, please feel free.

 

Below is a link to an O'Reilly's book on creating API's with PHP. The link lets you download the ebook for free! #winning!

 

http://it-ebooks.info/book/2268/


Follow me on Twitter @maxrbaldwin


#3 ignace

ignace

    Now mod flavored

  • Moderators
  • 6,237 posts
  • LocationBelgium

Posted 12 November 2013 - 01:46 AM

guzzle

#4 computermax2328

computermax2328

    Advanced Member

  • Members
  • PipPipPip
  • 285 posts
  • LocationUnited States
  • Age:22

Posted 12 November 2013 - 09:12 AM

Solid! Thanks man!

 

Anyone else?


Follow me on Twitter @maxrbaldwin


#5 trq

trq

    Advanced Member

  • Administrators
  • 30,895 posts
  • LocationSydney, Australia.

Posted 12 November 2013 - 06:51 PM

I've not used it myself (and I'm not much of a ZF fan) but there is a lot of chatter around about Apigility at the moment.

http://thorpesystems.com | http://proemframework.org | http://github.com/trq

SmtpCatcher - A very simple mock sendmail useful for testing PHP mail scripts.
OPM - My Linux package manager.


#6 snoopytamp

snoopytamp

    Member

  • Members
  • PipPip
  • 13 posts

Posted 12 November 2013 - 11:08 PM

I have never used 9lessons, but my friend said it's a good site to learn public APIs for PHP. you might want to try it. you're welcome in advance. :)



#7 computermax2328

computermax2328

    Advanced Member

  • Members
  • PipPipPip
  • 285 posts
  • LocationUnited States
  • Age:22

Posted 13 November 2013 - 05:48 PM

Awesome! Thanks guys. I am gonna check out Apigility and 9lessons tonight.

 

Does anyone else have some input?


Follow me on Twitter @maxrbaldwin


#8 QuickOldCar

QuickOldCar

    Advanced Member

  • Members
  • PipPipPip
  • 1,702 posts
  • LocationNorthEast Pennsylvania

Posted 17 November 2013 - 10:19 PM

I made some php api's, aren't really that hard to do at all.

I guess the most important part is that you are using clean data.

 

First take a look at some of the links for json, xml and html formats

html

json

xml

 

Basically they are all simple GET requests, I check if they are set and not empty, for some I insert default values in case is not set.

 

Then you query your database and fetch some data.(yes did this a while ago and is mysql versus mysqli)

If no format is set I default to json

 

Use a switch or if/else statement and show different outputs.

 

I'll paste my entire api code here, seems easier than editing it with dummy values.

<?php

if(isset($_GET['format']) && trim($_GET['format']) != ''){
$format = trim($_GET['format']);
} else {
$format = "json";
}

$style_array = array("default","title","video");
if(!isset($_GET['style']) || trim($_GET['style']) == ''){
$style = "default";
} else {
$style = trim(strtolower($_GET['style']));
}

if(!in_array($style,$style_array)){
$style = "default";
}

if(!isset($_GET['max']) || trim($_GET['max']) == ''){
$max_results = 10;
} else {
$max_results = (int) trim($_GET['max']);
}

if($max_results > 50){
$max_results = 50;
}

if(!isset($_GET['startrow']) || trim($_GET['startrow']) == ''){
$startrow = 0;
} else {
$startrow = (int) trim($_GET['startrow']);
}

//$startrow = $startrow - $max_results;

if($startrow <= 0){
$startrow = 0;
}

if(!isset($_GET['display']) || trim($_GET['display']) == ''){
$display = "id";
} else {
$display = trim($_GET['display']);
}

if(!isset($_GET['order']) || trim($_GET['order']) == ''){
$order = "desc";
} else {
$order = trim($_GET['order']);
}

if($display !== "id" && !isset($_GET['order'])){
$order = "asc";
}

if(!isset($_GET['size']) || trim($_GET['size']) == ''){
$size = 190;
} else {
$size = (int) trim($_GET['size']);
}

$format_array = array("json","xml","html");
if(!in_array($format,$format_array )){
$format = "json";
}

$_GET['s'] = strtolower($_GET['s']);
    $var = @mysql_real_escape_string($_GET['s']);
    //$var = $_GET['s'];
    $trimmed = trim($var); //trim whitespace from the stored variable
    $trimmed_length = strlen($trimmed);
    if ($trimmed_length > 200) {
    //limit to 200 characters
        $trimmed = substr($trimmed, 0, 200);
    }

    //remove need for +
    $explode_trimmed = explode(" ", $trimmed);

    foreach ($explode_trimmed as $trim_words) {
        if (substr($trim_words, 0, 1) != "-" || substr($trim_words, 0, 1) != '"') {
            $trim_words = trim($trim_words);
            $trimmed_words .= " +$trim_words";
        } else {
            $trim_words = trim($trim_words);
            $trimmed_words .= " $trim_words";
        }
    }
    $trimmed_words = trim($trimmed_words);
    $trimmed_words = preg_replace('/\s+/', ' ', $trimmed_words);


    $trimmed_words = str_replace(array("  ", "  +", "+ +", "  -", "+++"), array(" ", " +", " +", " -", "++"), $trimmed_words);


mysql_connect("localhost", "username", "password");
mysql_select_db("mydatabase") or die("Unable to select database");

$display = mysql_real_escape_string($display);
$order = mysql_real_escape_string($order);
$startrow = mysql_real_escape_string($startrow);
$max_results = mysql_real_escape_string($max_results);
$trimmed_words = mysql_real_escape_string($trimmed_words);

if($var == ''){
$result = mysql_query("SELECT * FROM videolinks WHERE status='1' GROUP BY $display $order Limit $startrow ,$max_results");
} else {
$result = mysql_query("SELECT * FROM videolinks WHERE status='1' AND MATCH (title,description) AGAINST ('$trimmed_words' IN BOOLEAN MODE) GROUP BY $display $order Limit $startrow,$max_results");
}


switch ($format) {
//json api
            case 'json':
                // you can uncomment it for Live version
                header('Content-Type: application/json; charset=utf-8');
                if (count($result)) {
                while ($row = mysql_fetch_array($result)) {
                    echo json_encode(array('data' => $row ));
                    }
                } else {
                    echo json_encode(array('data' => 'Nothing found'));
                }
                break;
                
//xml api
            case 'xml':
                $sCode = '';

                if (count($result)) {
                function convertchar($chars){
                $chars =
                    $chars = str_replace(array("&&","<",">"),array("&","&lt","&gt"),$chars);
                    $chars = htmlspecialchars($chars,ENT_QUOTES);
                    return $chars;
                    }
                    
                while ($row = mysql_fetch_array($result)) {
                    $link_id = $row['id'];
    $link_url = convertchar($row['url']);
    $link_domain = convertchar($row['domain']);
    $link_title =  convertchar($row['title']);
    $link_description =  convertchar($row['description']);
    if($link_domain == "youtube.com"){
    $ytid = end(explode("~v=~",$link_url));
    $thumbnail = "http://img.youtube.com/vi/".$ytid."/0.jpg";
    $thumbnail_href = "<a href='$yturl' target='_blank'><img src='$thumbnail' border='0'></a>";
    }
    $video_display = @file_get_contents("http://dynainternet.com/dynavid/embed.php?video=$link_url&width=835&height=505");

                        $sCode .= <<<EOF

    <id>{$link_id}</id>
    <url>{$link_url}</url>
    <title>{$link_title}</title>
    <description>{$link_description}</description>
    <domain>{$link_domain}</domain>

EOF;
                    }
                }


                header('Content-Type: text/xml; charset=utf-8');
                echo <<<EOF
<?xml version="1.0" encoding="utf-8"?>
<videos>
{$sCode}
</videos>
EOF;
                break;
                
//html api  
            case 'html':
            ?>
            <style>
    p {
        color: white;
        background:black;
    }

    a {
        color: white;
        background:black;
    }
    
    a:hover {
        color: black;
        background:white;
    }
    .nav {
    font-size:18;
    text-align:center;
    background-color:black;
    }

</style>
            <?php
            if (count($result)) {
            //pagination
            $url = filter_var("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);
    if (!empty($_SERVER["QUERY_STRING"])) {
        $query_string = filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_STRING);
        $url .= "?" . $query_string;
        
        if (!preg_match("/startrow=/i", $url)) {
            $url = $url . "&startrow=$startrow";
        }
        
        if (!preg_match("/max=/i", $url)) {
            $url = $url . "&max=$max_results";
        }
        
        if (!preg_match("/size=/i", $url)) {
            $url = $url . "&size=$size";
        }
        
                
    }


    $url = preg_replace('/\s+/', ' ', $url);
    $url = str_replace(array("++", "+++", "+ +"), " +", $url);
    $url = str_replace(array("  ", "    "), " ", $url);
            
            $urlparse = parse_url($url);
            parse_str($urlparse[query], $query);
            $current_startrow = $query['startrow'];
            $next_set = $current_startrow + $max_results;
            $prev_set = $current_startrow - $max_results;
            
            $next_url = str_ireplace("startrow=$current_startrow","startrow=$next_set",$url);
            $prev_url = str_ireplace("startrow=$current_startrow","startrow=$prev_set",$url);
            
            
            ?>
    <form name="input" action="" method="get">
<input type="text" <?php if($var != ''){echo "value='".htmlentities(stripslashes($var))."'";}else{echo "placeholder='Search'";}?> name="s">
<input type="hidden" name="format" value="html">
<input type="hidden" name="size" value="<?php echo $size;?>">
<input type="hidden" name="startrow" value="0">
<input type="hidden" name="max" value="<?php echo $max_results;?>">
<input type="hidden" name="display" value="id">
<input type="hidden" name="order" value="desc">
<input type="submit" value="Go" style="background:white;font-size:18;text-align:center;width:36;">
</form>
    <?php
            echo "<div id='nav' class='nav'><a href='http://dynainternet.com/dynavid/api/index.php?format=html&size=$size&display=id&order=desc&startrow=0&max=$max_results' style='text-decoration: none'>ALL </a> <a href='$prev_url' style='text-decoration: none'>< PREV</a> -  <a href='$next_url' style='text-decoration: none'>NEXT ></a></div>";
                while ($row = mysql_fetch_array($result)) {
                    $link_id = $row['id'];
    $link_url = utf8_decode(urldecode($row['url']));
    $link_domain = $row['domain'];
    $link_title =  html_entity_decode($row['title']);
    $link_description =  html_entity_decode($row['description']);
    

    switch($style){
    
    case "default":
    echo "<a href='$link_url' target='_blank' style='text-decoration: none'>$link_title</a><br />";
    echo $video_display = @file_get_contents("http://dynainternet.com/dynavid/api-embed.php?video=$link_url&width=$size&height=$size");
    echo "<hr>";
    break;
    
    case "title":
    echo "<a href='$link_url' target='_blank' style='text-decoration: none;font-color:white;background:black;'>$link_title</a><br />";
    echo "<hr>";
    break;
    
    case "video":
    echo $video_display = @file_get_contents("http://dynainternet.com/dynavid/api-embed.php?video=$link_url&width=$size&height=$size");
    echo "<hr>";
    break;
    
    }
 
                    }
                    
                    echo "<div id='nav' class='nav'><a href='http://dynainternet.com/dynavid/api/index.php?format=html&size=190&display=id&order=desc&startrow=$startrow&max=$max_results' style='text-decoration: none'>ALL </a> <a href='$prev_url' style='text-decoration: none'>< PREV</a> -  <a href='$next_url' style='text-decoration: none'>NEXT ></a></div>";
                    
                } else {
                    echo 'Nothing found';
                }
            
            break;
            
}//end switch
mysql_close();
?>
 

Edited by QuickOldCar, 17 November 2013 - 10:26 PM.

DynaIndex.com
Dynamic search index of websites, links, feeds, title, description, keywords and thumbnail snapshot.

#9 trq

trq

    Advanced Member

  • Administrators
  • 30,895 posts
  • LocationSydney, Australia.

Posted 18 November 2013 - 06:36 AM

Basically they are all simple GET requests

 

API's can implement many different request methods.


http://thorpesystems.com | http://proemframework.org | http://github.com/trq

SmtpCatcher - A very simple mock sendmail useful for testing PHP mail scripts.
OPM - My Linux package manager.


#10 KevinM1

KevinM1

    Snarkimus Prime

  • Moderators
  • 5,191 posts
  • LocationNew Hampshire, USA

Posted 19 November 2013 - 11:14 PM

API's can implement many different request methods.


Yup. A good example is Stripe, a payment handling/gateway API.

#11 trq

trq

    Advanced Member

  • Administrators
  • 30,895 posts
  • LocationSydney, Australia.

Posted 20 November 2013 - 08:03 AM

Yup. A good example is Stripe, a payment handling/gateway API.

Github have the best API I've seen / used. Well documented, and well thought out.


http://thorpesystems.com | http://proemframework.org | http://github.com/trq

SmtpCatcher - A very simple mock sendmail useful for testing PHP mail scripts.
OPM - My Linux package manager.


#12 trq

trq

    Advanced Member

  • Administrators
  • 30,895 posts
  • LocationSydney, Australia.

Posted 21 November 2013 - 06:00 AM

This book is only brand new (so I haven't read it) and still a work in progress, but this guy knows his shit. Especially when it comes to API design.

 

https://leanpub.com/...s-you-wont-hate


http://thorpesystems.com | http://proemframework.org | http://github.com/trq

SmtpCatcher - A very simple mock sendmail useful for testing PHP mail scripts.
OPM - My Linux package manager.


#13 computermax2328

computermax2328

    Advanced Member

  • Members
  • PipPipPip
  • 285 posts
  • LocationUnited States
  • Age:22

Posted 24 November 2013 - 05:59 PM

Thanks Trq,

 

I was actually about to start a topic about web development books and web development theory. I will make sure I add this to my list.


Follow me on Twitter @maxrbaldwin





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com