Making an API

Associate
Joined
20 Oct 2012
Posts
457
Location
west sussex
Hi all im very interested in having a crack at making a basic API but not sure were to start?
What software is out there that is free or cheap to have ago with.

Thanks
 
Man of Honour
Joined
13 Oct 2006
Posts
92,043
An API for... what?

Generally its a collection of functions that can be interfaced with via a DLL which can be built using any free C compiler, etc. and IIRC some other stuff like powerbasic, etc.
 
Soldato
Joined
20 Dec 2004
Posts
16,027
An API can just be a document, in fact that's precisely what you would start with. It's not specific to any technology.

At it's simplest it's a list of methods, with their parameters and return values.
 
Associate
Joined
28 May 2008
Posts
346
Start with something that accepts a post(s)

You could use Spring, PHP and many things to achieve this.

My weapon of choice is usually PHP but for bigger projects/ enterprise level usually a framework that can work more structured (MVC, application + database layer etc) would be used.

Take a look at this very simple API in php to give you an idea of how something like this could work:

Code:
<?php
header('Content-type: application/json');
include("App.php");

/**
 * User: Darryl
 * Date: 26/04/13
 * Time: 15:17
 */



$request = $_SERVER['REQUEST_URI'];
$request = explode("/", $request);

foreach ($request as $key => $value) {

}

if (isset($_POST['apikey'])) {
    $apikey = $_POST['apikey'];
} else {
    $apikey = "null";

    $return_array['code'] = "404";
    $return_array['msg'] = "method not found";
    $return_array['apikey'] = $apikey;
    $return_array['data'] = "";
    $return_array['authorised'] = false;
}


if ($apikey == "12345") {
    
    $return_array['authorised'] = true;
    
} else {
	
    $return_array['code'] = "404";
    $return_array['msg'] = "invalid api key";
    $return_array['authorised'] = false;
    echo json_encode($return_array);
    return false;
}

if ($return_array['authorised'] == true) {
    if ($request[2] == "request") {
        switch ($request[3]) {
            case "login":
                $tryLogin = App::checkLogin($_POST['email'], $_POST['password']);
                if ($tryLogin == false) {
                    $return_array['code'] = "400";
                    $return_array['msg'] = "login checked, failed";
                    $return_array['data'] = false;
                } else {
                    $return_array['code'] = "100";
                    $return_array['msg'] = "login checked, returning result";
                    $return_array['data'] = $tryLogin;
                }

                break;

            default:
                $return_array['code'] = "404";
                $return_array['msg'] = "method not found";
                break;
        }
    } else {

        $return_array['code'] = "404";
        $return_array['msg'] = "method not found";
        $return_array['apikey'] = $apikey;
        $return_array['data'] = "";
    }

} else {
    $return_array['msg'] = "Unauthorised request to API";
    $return_array['code'] = "500";
}
//generate json array
echo json_encode($return_array);

?>

I wrote this when I first started getting into PHP so it may be a bit shoddy but good starting ground. Accepts posts of apikey, email and password so I can hit whatever method is defined by the URL so in this case login is the only one implemented and we would be triggering that for a successful API hit. This is calling an external class that will have a method executing MySQL to query the database for the requested information/ authentication. See below:

Code:
<?php
/**
 * Created by PhpStorm.
 * User: Darryl
 * Date: 26/04/14
 * Time: 15:17
 */

include("../classes/Config.php");
include("../classes/DB.php");
// Standard includes

function hashPassword($password)
{
    return hash("sha512", $password);
}

class App
{


    public static function checkLogin($email, $password)
    {

        if ($email != "" && $password != "") {
            $email = htmlentities(strtolower($email));
            $password = hashPassword($password);
            $sql = "SELECT * FROM `users` WHERE `email` = :email AND `password` = :password";
            $core = DB::getInstance();
            $stmt = $core->dbh->prepare($sql);
            $result = $stmt->execute(array(
                ':email' => $email,
                ':password' => $password
            ));
            $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if (!$stmt) {
                
                print_r($core->dbh->errorInfo());
            }

            if ($row) {
                $user = array();
                $user["email"] = $row[0]['email'];
                $user["forename"] = $row[0]['forename'];
                $user["surname"] = $row[0]['surname'];
                $user["level"] = $row[0]['level'];
                $user["avatar"] = $row[0]['avatar'];
                $user["confirmed"] = $row[0]['confirmed'];

                return $user;
            } else {
                $fail_message = "invalid email / password";
                return false;
            }
        } else {
            $null_message = "Error";
            return false;
        }
    }
}

?>

The end result will be a json array which can be decoded by pretty much any framework/ language these days - you will also need a DB config file with your MySQL database username and password

Some good tools: PHP Storm, Online tool for testing posts, and a PHP enabled instance of apache server to test, instance of MySQL for database
 
Last edited:
Associate
OP
Joined
20 Oct 2012
Posts
457
Location
west sussex
hehe ok this is way over my head should do more googling i guess. Maybe its not an API needed? but this is a quick breakdown of what im trying to achieve.
Basically i was looking to take an online order lets say of 3 items it email a print server and print 2 sheets. then to produce a bar code/number code to then input that into epos to then deduct the 3 items from the stock system.

I knew this was going to be way over my head but though if i started to learn this kind of thing then i may be able to explain/help make something.
 
Man of Honour
Joined
30 Oct 2003
Posts
13,329
Location
Essex
hehe ok this is way over my head should do more googling i guess. Maybe its not an API needed? but this is a quick breakdown of what im trying to achieve.
Basically i was looking to take an online order lets say of 3 items it email a print server and print 2 sheets. then to produce a bar code/number code to then input that into epos to then deduct the 3 items from the stock system.

I knew this was going to be way over my head but though if i started to learn this kind of thing then i may be able to explain/help make something.

I think you could probably do it all in the back end of the site and sql servers running the epos and stock systems. Presumably the site will have a mysql or sql back end, if so you could write a stored procedure that runs on each order and sends an email etc. Most other systems particularly epos etc are also sql back ended or at least database driven. What you need here is some transact sql skills.

Edit: What i think you actually need to write are some interface scripts.
 
Last edited:
Associate
Joined
26 Apr 2012
Posts
1,197
I have used Laravel which is a php framework for writing an api I use on my own website. Great framework to use and lots of support and documentation I have also used codeignitor is the past.

The api I wrote is just for my own personal consumption so I can change when I want but if you are looking to create an api which you would make public I think the biggest step in the whole process is design, you want to get it right as any changes could have huge impacts on users consuming it.
 
Associate
Joined
24 Sep 2008
Posts
1,756
Aye, I take it your talking about Gorilla mux?


There's faster routers, but lets be honest unless your serving stack overflow levels of traffic Gorilla mux is a nice simple but flexible router.

Yeah, its an internal developer API for putting JSON and mustache templates into Amazon S3, maybe a few requests a second with some bursts of up to 20 when Jenkins pushes to it.
 
Back
Top Bottom