simple REST API in PHP by Geordy James

Let us talk about scripts, HTML, Perl, PHP, apache, etc.
Post Reply
User avatar
Stevyn
SysOp
Posts:1786
Joined:Mon Nov 09, 2009 10:03 am
Location:Japan
Contact:
simple REST API in PHP by Geordy James

Post by Stevyn » Thu May 23, 2019 1:50 pm

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
Contact me directly: Ironfeatherbooks (@) gmail.com

Image

User avatar
Stevyn
SysOp
Posts:1786
Joined:Mon Nov 09, 2009 10:03 am
Location:Japan
Contact:

Re: simple REST API in PHP by Geordy James

Post by Stevyn » Thu May 23, 2019 2:10 pm

Contact me directly: Ironfeatherbooks (@) gmail.com

Image

Post Reply