• We just launched and are currently in beta. Join us as we build and grow the community.

How To Use a REST API in PHP

aldofeikLH

Esports Pro
A Rep
0
0
0
Rep
0
A Vouches
0
0
0
Vouches
0
Posts
156
Likes
187
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
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;

  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. ?>

 

452,292

323,340

323,349

Top