How To Build Your Own API Using PHP

I gotchu fam

If you’re reading this, then you have probably already been exposed to APIs; either by creating software to consume them, or in the apps that you use yourself.

Wikipedia describes an API as:

An application programming interface is a computing interface to a software component or a system, that defines how other components or systems can use it. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc

Yeah, I don’t know what any of that means either, and I know how to build them. Here in a few minutes you will, too!

Put simply, for our purposes, an API is a tool that you can use to retrieve data from some other source to use in your own applications. Many news sites, gaming apps, information collections and other types of application are built with data from APIs.

It’s worth noting that all the examples in that last paragraph were built by me.

So you’ve got the hang of consuming data distributed by APIs:

— You go to the provider’s documentation

— trudge through complicated instructions until you figure out the right calls to make

— weld together some fetches and parsers until you can get to the data you want

— and then present it to your own end users.

Remember when this was you?

By now, that process is probably old hat to you and, being the web-bro that you are, you want to make your own APIs to allow others access to data they might need in their own apps. Whatta guy!

There’s plenty of data to go around

You’ve seen API results in JSON format before:

You’re going to be able to produce the same output

All you need to be able to do is to produce data of your own in that same format, from a web URL that developers can call.

Let’s get started!

Here’s what you’re going to need:

— Notepad

— Someplace to host your terrific API

Got all that? Good!

So the examples I talked about mostly deliver data. That involves you possessing data that you want to deliver. Like in a database. On a server. Don’t worry, it’s not a dealbreaker.

If you followed the other types of application link from above you saw my “showerthoughts” page. That page uses a database I have with 924000 showerthoughts in it. I built an API to retrieve 20 random showerthoughts at a time and return them to the caller, which is also me. But you can call that URL yourself for your own application. It’s a free bonus!

The reason I only use 20 at a time is because that page uses “infinite scrolling” to show the results, so it doesn’t need to deliver more than 20 records at a time. Here’s where you can learn how to build an infinite scroller.

APIs can also be used to just deliver data that is produced at runtime. If you’re familiar with FOAAS then you already know you can just provide data functionality to people without having to actually own a large database.

Here’s another API I built to convert text into Pig Latin. Here’s what that previous paragraph looks like as API results.

For our example today, we’re going to build an API called “Rando” whose sole purpose is just to return an array of random numbers. That’s it. But you’d be surprised how many people can’t do that on their own, so you’ll be providing a valuable service!

You da real MVP

Thinking about our functionality; let’s set our parameters:

— let’s allow the caller to specify the length of the array they want (length)

— let’s only return whole numbers; you can add decimals later if you want

— let’s allow a minimum number (min)

— let’s allow a maximum number (max)

— and let’s allow the caller to tell us if they want the array to be sorted

— if so, is it ascending (asc) or descending (desc) order they want?

There are only like a bazillion other features you can add to this if you want to. For instance, my version allows the user to just call incremental numbers instead of random numbers, and they can also specify what step to use (1,2,3,… or 2,4,6…or 100,200,300…).

But we’re going to stick with an array of specified length that contains random numbers from min to max, sorted or not.

We’re going to call it like this:

That’ll return an array of 10000 numbers between 1 and 9999 in JSON format.

Here’s the first lines of code to accomplish this:

<?phpheader(‘Content-Type: application/json’);$results = array();

our file is called index.php and it’s located wherever you store it online. This one’s at and it’s the only file in that folder.

The first line, of course, tells it you’re using PHP. The second line tells it what type of response you’re providing, and the last line establishes the JSON array that we’re going to send back to the user.

Next we check to see if they’ve put any parameters in the URL (because if they didn’t, they ain’t gettin’ nuttin).

$length = $_GET[“length”];if($_GET[“min”]) {
$min = $_GET[“min”];
} else $min = 1;
if($_GET[“max”]) {
$max = $_GET[“max”];
} else $max = $length;
$sort = “”;if($_GET[“sort”]) {
$sort = $_GET[“sort”];

What we’re doing here is setting a $length variable to the length the caller specified with the “length” parameter in the URL. Again, if it’s missing they’ll just get an empty array, but you can error-trap and send response messages all you want.

If you got parameters you’re unhappy with just set $response to “what kind of nonsense are you trying to pull” (or something a little more descriptive) and return that.

Next, we’re using $_GET statements to query the other parameters in the URL. We set a variable, $min, and if the caller has set “min=something” in the URL then we will use that value in this variable. Otherwise we set it to 1.

Then we check for a “max” parameter and set a variable $max to that value. If there is no “max” in the URL then we just set $max to the length of the array that the user set with the length parameter.

Finally we set a $sort variable to null. In the URL it’s going to be either “asc” or “desc” (without quotes) so we use a $_GET to see which it is.

Notice how we keep using the conditional:

if($_GET[“sort”]) {

That’s us just checking to see if the parameter even exists in the URL before bothering to get its value.

Now that we’ve set all the parameters for our API call, we implement the functionality:

for ($i=0;$i<$length;$i++) {
$results[] = rand($min,$max);
if ($sort==”asc”) {
} elseif ($sort==”desc”) {

That’s a loop to count up until the length specified, getting a random number between “min” and “max” and adding it to our array, “$results” that we’re going to send back.

Next, if the $sort variable is set to “asc” we sort the $results array in ascending numerical order, elseif it’s set to “desc” we sort it in reverse order.

Lastly, we’re going to pretty up the results so they look like a professional API JSON set by adding:

$endArray = array(‘array’ => $results);echo json_encode($endArray);?>

That just makes an array of key, value pairs and sets the key to “array” and the value to the array of random numbers we just came up with.

Then we use the json_encode command on our $endArray array to put it into proper JSON for the output and simply “echo” it back to the user.

That’s literally all there is to it. Here’s the API call we just built.

Now as an extra fun project, let’s do an API call to retrieve that data and use it somehow!

Here’s a replit I made to demonstrate this API returning results to be processed. Here’s the code:

.then(res => res.json())
.then(data => {
document.getElementById(“output”).innerHTML = data.array;
.catch(function(error) {

You may notice this mess in the URL:

That’s because some servers get into arguments with callers over whether or not they’re allowed to access cross-site data. It’s called Cross-Origin Resource Sharing errors.

The nice folks over at herokuapp have provided us all with that nice proxy URL to circumvent those conflicts. You may have already used it with other APIs. I know I have.

And all that code is doing is fetching the results from our nifty new API, parsing it, then posting the array of random numbers to a DIV called “output” on the HTML page.

From this code, you can easily expand the functionality (see the github repo) to include other features and return different data; decimals, letters, words..the sky’s the limit.

No it’s not.

So, you’re done. You’ve just built a genuine API, every bit as legitimate as anyone else’s, and now you know how to do it. If you had 924000 showerthoughts in a database you could just use one SELECT query, save it into the array just like we did, and you’d be returning showerthoughts. In our case, we’re returning random numbers.


Now the hard part comes. You have to document the requests a user can make, otherwise all your tasty data will just sit there waiting for a call that never comes.

You have to tell people to specify a length for their array, and basically that’s it. As you can see, calling the API with just “length” set will return an array, but we’ve added “min” “max” “sort” “asc” and “desc” as features to enrich their experience.

But if you don’t tell them those commands are available, they’ll never know to use them. That’s your job, my work here is done.

Have fun!

Here’s our API on github:

Here’s the whole file we just built:

<?phpheader(‘Content-Type: application/json’);$results = array();$length = $_GET[“length”];if($_GET[“min”]) {
$min = $_GET[“min”];
} else $min = 1;
if($_GET[“max”]) {
$max = $_GET[“max”];
} else $max = $length;
$sort = “”;if($_GET[“sort”]) {
$sort = $_GET[“sort”];
for ($i=0;$i<$length;$i++) {
$results[] = rand($min,$max);
if ($sort==”asc”) {
} elseif ($sort==”desc”) {
$endArray = array(‘array’ => $results);echo json_encode($endArray);?>
All this fun makes me thirsty



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

4a 75 73 74 20 61 6e 6f 74 68 65 72 20 63 6f 6d 70 75 74 65 72 20 6e 65 72 64 20 77 69 74 68 20 61 20 62 6c 6f 67