Jump to content

Creating a Public API


computermax2328

Recommended Posts

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/

Link to comment
Share on other sites

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.