Home » PHP RESTful Web Services Tutorial for beginners

PHP RESTful Web Services Tutorial for beginners

Today, We want to share with you PHP RESTful Web Services Tutorial for beginners.
In this post we will show you php rest api framework, hear for php web service tutorial step by step we will give you demo and example for implement.
In this post, we will learn about Build your first web service with PHP, JSON, XML and MySql with an example.

PHP RESTful Web Services Tutorial for beginners

There are the Following The simple About PHP RESTful Web Services Tutorial for beginners Full Information With Example and source code.

As I will cover this Post with live Working example to develop php web service tutorial step by step, so the some major files and Directory structures for this example is following below.

  • Student.php
  • StudentRestHandler.php
  • StudentRest.php
  • RestController.php
  • .htaccess

PHP RESTful Web Services Example

Student.php

<?php
Class Student {
	
	private $students = array(
		1 => 'Jaydeep Gondaliya',  
		2 => 'Mayur Dhameliya',  
		3 => 'Krunal sisodaiya',  			
		4 => 'Yogesh padaliya',  			
		5 => 'Vishal Pandya',  
		6 => 'Bhavesh Maraviya');
		
	public function getAllStudent(){
		return $this->students;
	}
	
	public function getStudent($id){
		
		$student = array($id => ($this->students[$id]) ? $this->students[$id] : $this->students[1]);
		return $student;
	}	
}
?>

RESTful Web Service Controller

RestController.php

Read Also:  Create time slot using PHP Example

This is where I will make a simple HTML form and PHP server side source code for our web application. To make the forms simply all souce code copy and write it into your any text editor Like Notepad++, then save file it as RestController.php.

<?php
require_once("StudentRestHandler.php");
		
$view = "";
if(isset($_GET["view"]))
	$view = $_GET["view"];
/*
RESTful Services URI Mapping
*/
switch($view){

	case "all":
		// to handle REST Url /student/list/
		$studentRestHandler = new StudentRestHandler();
		$studentRestHandler->getAllStudents();
		break;
		
	case "single":
		// to handle REST Url /student/show/<id>/
		$studentRestHandler = new StudentRestHandler();
		$studentRestHandler->getStudent($_GET["id"]);
		break;

	case "" :
		//404 - not found;
		break;
}
?>

A simple RESTful base class

StudentRest.php

<?php 
class StudentRest {
	
	private $httpVersion = "HTTP/1.1";

	public function setHttpHeaders($contentType, $codeLiveStatus){
		
		$statusMessage = $this -> getHttpStatusMessage($codeLiveStatus);
		
		header($this->httpVersion. " ". $codeLiveStatus ." ". $statusMessage);		
		header("Content-Type:". $contentType);
	}
	
	public function getHttpStatusMessage($codeLiveStatus){
		$httpStatus = array(
			505 => 'HTTP Version Not Supported',
			504 => 'Gateway Timeout',  
			503 => 'Service Unavailable',  
			502 => 'Bad Gateway',  
			501 => 'Not Implemented',  
			500 => 'Internal Server Error',  
			417 => 'Expectation Failed',  
			416 => 'Requested Range Not Satisfiable',  
			415 => 'Unsupported Media Type',  
			414 => 'Request-URI Too Long',  
			413 => 'Request Entity Too Large',  
			412 => 'Precondition Failed',  
			411 => 'Length Required',  
			410 => 'Gone',  
			409 => 'Conflict',  
			408 => 'Request Timeout',  
			407 => 'Proxy Authentication Required',  
			406 => 'Not Acceptable',  
			405 => 'Method Not Allowed',  
			404 => 'Not Found',  
			403 => 'Forbidden',  
			402 => 'Payment Required',  
			401 => 'Unauthorized',  
			400 => 'Bad Request',  
			307 => 'Temporary Redirect',  
			306 => '(Unused)',  
			305 => 'Use Proxy',  
			304 => 'Not Modified',  
			303 => 'See Other',  
			302 => 'Found',  
			301 => 'Moved Permanently',  
			300 => 'Multiple Choices',  
			206 => 'Partial Content',  
			205 => 'Reset Content',  
			204 => 'No Content',  
			203 => 'Non-Authoritative Information',  
			202 => 'Accepted',  
			201 => 'Created',  
			200 => 'OK',
			101 => 'Switching Protocols',  
			100 => 'Continue');
		return ($httpStatus[$codeLiveStatus]) ? $httpStatus[$codeLiveStatus] : $status[500];
	}
}
?>

RESTful Web Service Handler

StudentRestHandler.php

<?php
require_once("StudentRest.php");
require_once("Student.php");
		
class StudentRestHandler extends StudentRest {

	function getAllStudents() {	

		$student = new Student();
		$studData = $student->getAllStudent();

		if(empty($studData)) {
			$codeLiveStatus = 404;
			$studData = array('error' => 'No students found!');		
		} else {
			$codeLiveStatus = 200;
		}

		$dataContentRequest = $_SERVER['HTTP_ACCEPT'];
		$this ->setHttpHeaders($dataContentRequest, $codeLiveStatus);
				
		if(strpos($dataContentRequest,'application/json') !== false){
			$resultse = $this->encodeJson($studData);
			echo $resultse;
		} else if(strpos($dataContentRequest,'text/html') !== false){
			$resultse = $this->encodeHtml($studData);
			echo $resultse;
		} else if(strpos($dataContentRequest,'application/xml') !== false){
			$resultse = $this->encodeXml($studData);
			echo $resultse;
		}
	}
	
	public function encodeHtml($resultseData) {
	
		$htmlResponse = "<table border='1'>";
		foreach($resultseData as $key=>$value) {
    			$htmlResponse .= "<tr><td>". $key. "</td><td>". $value. "</td></tr>";
		}
		$htmlResponse .= "</table>";
		return $htmlResponse;		
	}
	
	public function encodeJson($resultseData) {
		$jsonResponse = json_encode($resultseData);
		return $jsonResponse;		
	}
	
	public function encodeXml($resultseData) {
		// creating object of SimpleXMLElement
		$xml = new SimpleXMLElement('<?xml version="1.0"?><student></student>');
		foreach($resultseData as $key=>$value) {
			$xml->addChild($key, $value);
		}
		return $xml->asXML();
	}
	
	public function getStudent($id) {

		$student = new Student();
		$studData = $student->getStudent($id);

		if(empty($studData)) {
			$codeLiveStatus = 404;
			$studData = array('error' => 'No students found!');		
		} else {
			$codeLiveStatus = 200;
		}

		$dataContentRequest = $_SERVER['HTTP_ACCEPT'];
		$this ->setHttpHeaders($dataContentRequest, $codeLiveStatus);
				
		if(strpos($dataContentRequest,'application/json') !== false){
			$resultse = $this->encodeJson($studData);
			echo $resultse;
		} else if(strpos($dataContentRequest,'text/html') !== false){
			$resultse = $this->encodeHtml($studData);
			echo $resultse;
		} else if(strpos($dataContentRequest,'application/xml') !== false){
			$resultse = $this->encodeXml($studData);
			echo $resultse;
		}
	}
}
?>

RESTful php web service XML – Output

RESTful-Web-Service-GET-1
RESTful-Web-Service-GET-1

php web service json JSON – Output

RESTful-Web-Service-JSON-Output
RESTful-Web-Service-JSON-Output

PHP RESTful Web Services – Output

PHP RESTful Web Service
PHP RESTful Web Service
Angular 6 CRUD Operations Application Tutorials

Read :

Read Also:  Laravel Supervisor start stop restart and update database queue

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Creating Web Service Using PHP.
I would like to have feedback on my Pakainfo.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.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  VueJS nested child, template, inner template, components
  2. Read Also:  Http Post and Get Web Api Calls using Vuejs
  3. Read Also:  Convert number to words in PHP
  4. Read Also:  Create RESTful API using PHP
  5. Read Also:  How to Fetch data from an External JSON in VueJS
  6. Read Also:  PHP Image Resize, Crop, Thumbnail, Watermark
  7. Read Also:  PHP Table Insert Tr After Every Third Loop
  8. Read Also:  How to Upload Images on Server in PHP?
  9. Read Also:  REST API Insert Update Delete using PHP
  10. Read Also:  Create Dynamic XML Sitemaps Using PHP MYSQL

Leave a Comment

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