Page 1 of 1

simple REST API in PHP by Geordy James

Posted: Thu May 23, 2019 1:50 pm
by Stevyn
api.php

Code: Select all

<?php
header("Content-Type:application/json");
require "data.php";

if(!empty($_GET['name']))
{
	$name=$_GET['name'];
	$price = get_price($name);
	
	if(empty($price))
	{
		response(200,"Product Not Found",NULL);
	}
	else
	{
		response(200,"Product Found",$price);
	}
	
}
else
{
	response(400,"Invalid Request",NULL);
}

function response($status,$status_message,$data)
{
	header("HTTP/1.1 ".$status);
	
	$response['status']=$status;
	$response['status_message']=$status_message;
	$response['data']=$data;
	
	$json_response = json_encode($response);
	echo $json_response;
}
data.php (or use a database)

Code: Select all

<?php

function get_price($name)
{
	$products = [
		"book"=>20,
		"pen"=>10,
		"pencil"=>5
	];
	
	foreach($products as $product=>$price)
	{
		if($product==$name)
		{
			return $price;
			break;
		}
	}
}

https://shareurcodes.com/blog/creating% ... 20in%20php

Re: simple REST API in PHP by Geordy James

Posted: Thu May 23, 2019 2:10 pm
by Stevyn