Create and Consume Simple REST API in PHP

Demo Download

In this tutorial, we will create and consume simple REST API in PHP. REST enables you to access and work with web based services. But before moving ahead let me explain what is REST and how does it work.

What is REST?

REST stands for Representational State Transfer, REST is an architectural style which defines a set of constraints for developing and consuming web services through standard protocol (HTTP). REST API is a simple, easy to implement and stateless web service. There is another web service available which is SOAP which stands for Simple Object Access Protocol which is created by Microsoft.

REST API is widely used in web and mobile applications as compared to SOAP. REST can provide output data in multiple formats such as JavaScript Object Notation (JSON), Extensible Markup Language (XML), Command Separated Value (CSV) and many others while SOAP described output in Web Services Description Language (WSDL).

How Does REST API Work

REST requests are related to CRUD operations (Create, Read, Update, Delete) in database, REST uses GET, POST, PUT and DELETE requests. Let me compare them with CRUD.

  • GET is used to retrieve information which is similar to Read
  • POST is used to create new record which is similar to Create
  • PUT is used to update record which is similar to Update
  • DELETE is used to delete record which is similar to Delete

How to Create and Consume Simple REST API in PHP

JSON format is the most common output format of REST API, we will use the JSON format to consume our simple REST API. We will developed an online transaction payment REST API for our example. I will try to keep it as simple as possible so i will use GET request to retrieve information.

  1. Create REST API in PHP
  2. Consume REST API in PHP

1. Create REST API in PHP

To create a REST API, follow these steps:

  1. Create a Database and Table with Dummy Data
  2. Create a Database Connection
  3. Create a REST API File

1. Create a Database and Table with Dummy Data

To create database run the following query.

To create a table run the following query. Note: I have already attached the SQL file of this table with dummy data, just download the complete zip file of this tutorial.

2. Create a Database Connection

Just create a db.php file and paste the following database connection in it. Make sure that you update these credentials with your database credentials.

3. Create a REST API File

Create a api.php file and paste the following script in it.

The above script will accept the GET request and return output in the JSON format.

I have created all these files in folder name rest, now you can get the transaction information by browsing the following URL.

You will get the following output.

Above URL is not user friendly, therefore we will rewrite URL through the .htaccess file, copy paste the following rule in  .htaccess file.

Now you can get the transaction information by browsing the following URL.

You will get the following output.

2. Consume REST API in PHP

To consume a REST API, follow these steps:

  1. Create an Index File with HTML Form
  2. Fetch Records through CURL

1. Create an Index File with HTML Form

2. Fetch Records through CURL

You can do anything with these output data, you can insert or update it into your own database if you are using REST API of any other service provider. Usually in case of online transaction, the service provider provides status of payment via API. You can check either payment is made successfully or not. They also provide a complete guide of it.

Make sure CURL is enabled on your web server or on your localhost when you are testing demo.

I try my best to explain this tutorial as simple as possible.

Demo Download

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

42 Comments

  1. Please remove this post
    It fails on numerous points of best practise and fundamental security.

    You have managed to create an article advising people to write code which features XSS & SQL Injection vulnerabilities, as well as not being particularly robust and prone to errors.

    You should never be outputting database error messages straight to the user
    You should be using prepared queries to parameterize user input going into the database to make it safe from injection
    You should be using html escaping (html_special_chars or htmlentities) before outputting any user input to a web browser.

    1. Kindly read my post title again, this is just simple tutorial example which means as simple as possible, yes you will need to secure your program too, this is only for basic concept for newcomers.

  2. dear Rehman,
    i’ve apreciated your tuto.
    i’m new in API development with PHP. i’m goint to ask a ridiculos questions:
    i was trying to define a variable containing the currant date, that i would use to build my insert request in the API source code.
    i’ve done that in my API:
    $curDate= now();
    but it generating an error.
    i do not understand why?
    should i always call the API with this current date as a parameter?
    no system function can be called in the API source code?
    thank you for your highlighting.
    Moussa
    regards

  3. Javed excelent tutorial !
    How do i adapt it to receive a Json input that contains several input values ?

    Thank you so much from Argentina!

  4. Notice: Trying to get property ‘order_id’ of non-object in C:\xampp\htdocs\rest\index.php on line 35

    Notice: Trying to get property ‘amount’ of non-object in C:\xampp\htdocs\rest\index.php on line 36

    Notice: Trying to get property ‘response_code’ of non-object in C:\xampp\htdocs\rest\index.php on line 37

    Notice: Trying to get property ‘response_desc’ of non-object in C:\xampp\htdocs\rest\index.php on line 38

  5. Hi Javed,
    I want to know how I can make this API get database credentials from a client side a shown below.

    // Enter your Host, username, password, database below.
    $con = mysqli_connect(“localhost”,”{$db_username}”,”{$db_pass}”,”{$db_name}”);
    if (mysqli_connect_errno()){
    echo “Failed to connect to MySQL: ” . mysqli_connect_error();
    die();
    }
    so how can I store those variables($db_username,$db_pass,$db_name) on the index.php file?

    1. You do not need credentials in API, API are used to interact with database, mostly to view data or if they gave you access, you can update the data too.
      You can see in my tutorial, it consist of two section, create and consume so if you are consuming API, you will get API to consume that do not required database credentials.

  6. Thanks a lot ! I liked this post so much.

    I have downloaded your code and it works fine in my testing environment, after updated “http://localhost/rest/api/” to “”http://localhost/rest/api.php?order_id=”.

    1. If you are sending order id it will fetch the record, keep in mind that you are fetching data using API, if you were using form submit method so records can be vanish after refresh.

  7. Hi sir my fields are shown null value please find out this. And also explain how i set my header.

    {“order_id”:null,”amount”:null,”response_code”:400,”response_desc”:”Invalid Request”}

    1. Guruveer you are getting Invalid Request, did you try to copy paste the same tutorial which i provided in download link? or you have made change in it? You are getting null because you are doing invalid request.

  8. How can i fix this error ??

    Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 32

    Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 33

    Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 34

    Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 35

    1. There is lot of benefit, now a days data sharing is very common, for example suppose you are going to integrate online payment system and you need to send or fetch data from online payment server which is paid service, they will provide you API for this purpose, they will not give you their database credentials, i hope you find this helpful.

  9. I am not getting the desired output for the .htaccess file. I am getting a invalid request response.What can I do to make it proper?Please help!

Leave a Reply

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