IWS2022 - Tutorial 7 - REST Web Service in PHP
IWS2022 - Tutorial 7 - REST Web Service in PHP
I’m going to attempt to explain how to create a REST API in the simplest way I
can. First thing I’ll do is create the API which I’ll call api.php in folder “tut7”.
The API has two functions: get_app_by_id() and get_app_list(). get_app_by_id()
expects an additional parameter called id to return the app info while get_app_list()
returns an array of apps. The API requires an action parameter to determine which
function to call. Requests made to this API utilize the GET HTTP verb and all
responses are returned using JSON. In the real world, your API would most likely
return data from a database. For this example, the return data is hardcoded into the
page.
Next I’ll create the client page that will be using the API.
As you can see, to use the API you’d simply send an HTTP request like so:
http://localhost/tut7/api.php?action=get_app_list. This URL would call the
get_app_list() and return data in JSON. PHP has a useful json_decode() function
that takes a JSON encoded string and converts it into a PHP variable. You can then
loop through your variable to display the data.
This is the simplest way to create and use a REST API.