
When thinking about a REST API and PHP, it's important to first understand that a PHP application can answer a REST API GET request, providing data to the requestor.
Or a PHP application can submit a GET request, requesting data from a REST API.
Answer a REST API GET request
Creating a REST API with PHP is actually incredibly easy. For example, www.freekb.net uses PHP to produce web pages. Let's say foo.php contains the following.
<?php
echo "Hello World";
?>
Navigating to http://www.freekb.net/foo.php displays Hello World.
Likewise, using a REST API, such as the curl command, submitting a GET request to www.freekb.net/foo.php also returns Hello World.
~]$ curl --request GET --url http://www.freekb.net/foo.php
Hello World
Almost always, a REST API returns JSON formatted data, so it probably makes sense for foo.php to return JSON formatted data.
<?php
$json = '{"foo":"Hello","bar":"World"}';
echo $json;
?>
Which should return the JSON data.
~]$ curl --request GET --url http://www.freekb.net/foo.php
{ "foo": "Hello", "bar": "World" }
Did you find this article helpful?
If so, consider buying me a coffee over at