How To Use a REST API in PHP

Introduction: This tutorial is on how to use an API in PHP. What Is An API? An API is an Application Programming Interface and is used as a middle stepping stone for external applications to use the functions of an internal application. An example of this would be the Skype API. The Skype API allows external applications on the users computer to access their Skype account via the Skype4ComLib API. REST API: There are a few different types of APIs, we'll be using an example REST in this tutorial. REST APIs are online (HTTP) APIs and get the required information from the PHP GET parameters of the URL, for example; http://www.example.com/myAPI.php?user=tim&[email protected] The above link would send the information; user, tim email, [email protected] ... to the myAPI.php REST API page. File Get Contents: There is a built in function in PHP which will attempt to get the contents of the given URL. We can use to send the data to our API URL and receive the status/output of the API page. The file_get_contents function takes one parameter which is the URL to get the contents of. The below example would send the data; ref, yorkiebar user, admin to the REST API located at; http://www.example.com/api.php
  1. file_get_contents('http://www.example.com/api.php?ref=yorkiebar&user=admin');
We could also write the returned string to the screen by saving it to a variable...
  1. $data = file_get_contents('http://www.example.com/api.php?ref=yorkiebar&user=admin');
Then writing that variable to the screen using PHP's 'echo' keyword...
  1. echo $data;
Finished! Here is the full source code;
  1. <?php
  2. $data = file_get_contents('http://www.example.com/api.php?ref=yorkiebar&user=admin');
  3. echo $data;
  4. ?>

Add new comment