Build an API

Links

Notes

To make an API, you ideally want to take some input and produce some output. To take input over the web, you create what's called a CGI. In perl, that means including a line that gets you functionality to process inputs. The module is CGI and we use a subset of it in this example. It gives us &param which lets us process name/value pairs that are input parameters.


#!/usr/bin/perl
use CGI qw(:standard);

$age = &param('age');

print "Hi, you are $age years old!\n";

&param is a function that you give the name of an input field and it gets the value. One the command line, you can send that data this way:
perl age.pl age=21
If this is sitting on a web server, you can put the parameters in the URL like this:
http://example.com/age.cgi?age=21
It's common to use .cgi as the extension on CGIs on the web, but your server may let them work with .pl.

You want to create documentation for your API. This will list:

  • A name of the API or the specific function
  • What it does
  • The endpoint - this is the basic URL. Examples from above are http://itsthisforthat.com/api.php or http://belikebill.azurewebsites.net/billgen-API.php
  • The parameters. For each, you list the name (like age in our example above) and the expected value. Also, list if they are required
Documentation for our API would be something like:
Jen's Age Stating API

Description: Tells someone their age

Endpoint: http://example.com/age.cgi

Parameters:
age (required) - value is age in years
format - the format of the data. Options include XML or text. text is default
You can see I added in a format option there. That's something we should handle. It's common to return data in different formats. For this example, we would want to see what they sent (if they sent anything) and print out something different in each case. In the code below, note I use the function lc() which converts the argument to lower case.

#!/usr/bin/perl
use CGI qw(:standard);


$format="text";

$age = &param('age');
$format = lc(&param('format'));



if ($format eq "xml") {
	print "<age>$age</age>";
} else {
	print "Hi, you are $age years old!\n";
}

Subroutines

Subroutines let you create a named block of code. It can take values as input. Those are accessible in a special array called @_. The first thing you send is in @_[0], the second in @_[1], and so on.

The subroutine can do anything you want, but you can have it send back a value. When you call the subroutine it gets replaced by the value you return.


#!/usr/bin/perl
use CGI qw(:standard);

$x = &param("number");
print square($x);

sub square {
	$in = @_[0];
	return $in*$in;
}