Create a simple API with PHP.

Today, we’ll show you how to create your own API that will output data in JSON.

 

For this, and if you want the API to exist on the web, you’ll want to have a web hosting solution (you can host it yourself but it’s a headache to configure properly). If you’re just starting out, you can go with Hostinger, they’ll give you absolutely free web hosting as well as a free subdomain on one of their domains, so you can literally have yourself a fully working API for no cost.

It is pretty simple and self explanatory to sign up with Hostinger, so we will not be explaining that, just follow their instructions. Instead, we’ll focus on getting the API part working.

 

Once you get your web hosting from Hostinger, on your FTP, in /public_html, create a file named demoapi.php, which will contain our API. Insert the following in the file:

<?php 

//Declaring an array of Strings
$strings = array("Paris", "Rome", "Timisoara");

//$theJson will be our return from the API
$theJson = array();

//Now we loop through the first array
foreach ($strings as $stringValue) {
	//And we push the cities as values, for the "city" names
	array_push($theJson, array("city" => $stringValue));
}

//finally, we encode the array and echo it. Do not forget json_encode!
echo json_encode($theJson);

?>

Now, use your browser and go to the domain you were given, and add the name of the file (/demoapi.php) at the end. This should display out the following:

[{"city":"Paris"},{"city":"Rome"},{"city":"Timisoara"}]

 

Congratulations! You just created a very simple API.

We'll show you, in a future post, how to make use of these API's to parse data, for example on a website or in a mobile app. We'll also show you how to connect to a database, get data from there, and output it using JSON. But for now, just play with your API, edit it, and make it do whatever you want!

Leave a Reply

Your email address will not be published. Required fields are marked *