how to create api in php json tutorial

Today, We want to share with you how to create api in php json.In this post we will show you how to create webservice in php using json, hear for how to make api in php tutorial we will give you demo and example for implement.In this post, we will learn about REST API CRUD Example in PHP with MySQLi with an example.

Restful web services php json tutorial

What is REST API?
REST (Representational State Transfer) is a way of accessing or get of the the web services. REST as an architecture style does not require processing as well as is more simple and great flexible than SOAP(Simple Object Access Protocol) which is another data & uniq standards-based Web services access protocol developed by Microsoft.

REST is much easier as well as more widely used than SOAP (about 80% web services API uses REST API) and is the freshcomer to the block which seeks to fix all issues or problems with SOAP. In this best tiny tutorial, I will learn you the easiest way to create your own REST API in PHP.

Before we start step by step implementation information let’s understand what is REST. We used REST API to get or give some information from a web service. It is as simple as giving an HTTP GET or POST or PUT or DELETE request from the client (Mobile Application, A website etc.) to the server to get some information from the server or to give some information to the server.

The REST based web services can give result in any format like Command Separated Value (CSV) file, JavaScript Object Notation (JSON) and Really Simple Syndication (RSS).

The point is that you can obtain the result you required in a form that’s easy to parse within the language you required for your application. A sample REST API diagram is given below.

Creating a simple REST API in PHP

The JSON is the most common result format of REST API and we are going to make a REST API which accepts GET request and gives JSON result.

We will create a REST API which requests a specific member age over URL. The name of the object will be passed as parameter and we will get the age of that member in JSON format.

The tutorial consist of mainly 2 parts. The first part deals with the creation of REST API in PHP and second part deals with consumption of REST API in PHP.

LET’S START CODING : create simple api in php

php rest api framework
php rest api framework

The rules include the following.

1. Use appropriate HTTP methods while performing API calls. The following are the four primary HTTP methods which should be used to send and receive API requests.

  • a. GET – To read single or multiple records.
  • b. POST – To create a new record.
  • c. PUT – To Update a record.
  • d. DELETE – To delete a record.

2. Use proper URL hierarchy instead of using URL query string for API URLs.

  • a. Good – http://yourdomainame.com/api/members/1
  • b. Bad – http://yourdomainame.com/api/members.php?id=1

3. Avoid using verbs as resource names in the API URL and use nouns and proper HTTP methods instead.

  • a. Good –http://yourdomainame.com/api/members
  • b. Bad –http://yourdomainame.com/api/members/add

4. Use plurals for the resource names in the API URL.

  • a. Good –http://yourdomainame.com/api/members
  • b. Bad –http://yourdomainame.com/api/member

5. Use HTTP response codes to indicate status of the requests.
6. Response data should be in either JSON or XML format.

Building a REST API using PHP

HTTP Method URL Action
GET /api/members Retrieves all members
GET /api/members/5 Retrieves a single member of primary key 5
POST /api/members Adds a new member
PUT /api/members/3 Updates a single member of primary key 3
DELETE /api/members/7 Deletes a single member of primary key 7
REST API CRUD Example in PHP with MySQLi
REST API CRUD Example in PHP with MySQLi

1) CREATION OF REST API IN PHP

The complete code inside api.php file is given below.


The above full PHP script file is responsible for dealing with HTTP GET requests as well as delivering JSON result to the user. We required to specify the data content type of this file as JSON since it gives JSON result for standardization. The API uses restcontent.php file to get age of specific member.

The complete code for the restcontent.php file is given below.

20,
		"kohali"=>10,
		"sachin"=>5
	];
	
	foreach($members as $member=>$age)
	{
		if($member==$name)
		{
			return $age;
			break;
		}
	}
}

For simplicity, We are getting the age from an array instead of the database. When you are creating API in real world you required to get data from the mysql database. If you are fresh to PHP then using PDO with Prepared Statement is the best way to get data from the database. I made a information post about PDO with Prepared Statement and you can look at it by visiting the following link.

Now you can get the member information by visiting following URL.

http://localhost/arityinfoway/api.php?name=kohali

But you can see that above URL is not standardized. So we can standardize the URL by using a simple .htaccess file to rewrite URL in apache server.

The complete code for .htaccess file is given below.

RewriteEngine On    # Turn on the rewriting engine

RewriteRule ^api/([a-zA-Z_-]*)$ api.php?name=$1 [NC,L]

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. Use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI.

2) Consuming REST API In PHP

Now we can get age information in our PHP website by calling REST API as HTTP GET request through CURL as given below.

data; 
	}
   ?>

Remember to set CURLOPT_RETURNTRANSFER as true since we required to give CURL result to a variable and normally CURL will not allow to store its result in a variable. A simple JSON decode will give us the age.

The HTML form is given below for references.




  Rest API Client Side Demo
  
  
  
  
  



Rest API Client Side Demo

 

UPDATE 28th Feb 2021

The current main root file .htaccess doesn't give support for integers as member name, hence it would throw a 404-Not found an error if you use an integer as the member name. So update the rewrite rule as below.

RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?name=$1 [NC,L]
WooCommerce REST API CRUD Tutorial From Scratch
WooCommerce REST API CRUD Tutorial From Scratch

I hope you get an idea about php web service json.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment