Add to Favorites

Creating your own API

You've heard the lingo, you may have even integrated with a few different API's to enrich your website experience. There are many services out there that offer API access; from payment processors to spam blocking everyone these days has an API.

Creating a very simple API can be fairly straightforward. Let's consider the following scenario: you have a website that allows users to post a contact message through a form into a central database. This database has a single table with three fields: id, message, and creation date.

Your service has now become popular with your customer base, and one of your customers would like a way to submit these messages to you directly from their desktop software. Now you have a dilemma, you have a web form that allows submission of these messages to your database, but you don't have an official way to allow other software developers to create messages in your system from their software. Here is where an API comes in handy.

For the purposes of this example, we will keep everything very basic and straightforward. You want to spec out your API with a quick API document that you can distribute to your customers.

In this case, we'll keep our API doc nice and short:

Message API URL:

Post parameters:


The developer will then create their software to send a message to that URL in standard http post format. Your system should have a script like below living in a folder named api at postmessage.php

if ( array_key_exists('apikey',$_POST) && array_key_exists('message',$_POST) && is_valid_api_key($_POST['apikey']) ) {
if ( create_message($_POST['message']) ) echo '1|success';
else echo '0|failed';
} else echo '0|invalid api key or missing api parameter';

From the above, you should create a function named is_valid_api_key that ensures that the apikey being provided is valid by whatever means you want to enforce, whether it's a general global apikey or individual customer assigned api keys.

You should implement the create_message function to insert the message into your database and return true or false for failure.

The customer, if they were using php could implement a connection to this api using curl like the following:

$ch = curl_init('');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('apikey'=>'mykey','message'=>'Hello there!'));

Of course they would want to implement some error checking in addition to the above general call in order to handle error or success types, but we've kept the example simple in this run.


Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up