Php rest api url

PHP – simple REST API – step by step

If you need to build a very simple REST API with PHP you are in right place! I needed some time ago to build a very simple REST API in PHP. I had to use PHP – this was the only back-end technology in my project and at that moment, my skills were poor in PHP.

I was looking for a very simple tutorial to have endpoint in normal form like http://my-domain.com/posts/12 just for a very basic functionality. Then I found on the internet big tutorials using some PHP frameworks to build great and fully proper REST APIs in PHP. But it wasn’t something what I was looking for.

But I didn’t want to spend a few days on learning object programming in PHP, learning frameworks etc. I needed to do a quick solution in good enough (not perfect) shape. So I started plying with PHP and in result, I created totally simple PHP REST API.

Read further to know how to do it.

First we will build the simplest possible example of php rest api with mapping URL path and invoking methods.

Second example will be still easy, but a little more sophisticated, and it will show how to build easy but fully working REST API with PHP.

Example 1 – the simplest REST API in PHP

  1. Open code of this example on our Gitlab account HERE.
  2. The first, probably the most important thing, is that we want to use nice-looking path to call our API, like: http://my-domain.com/customers/11 , not the url GET parameters instead of nice path.We need to create URL address mapping in .htaccess file, its content is very short but works perfectly – it turns nice-looking URL path into GET parameters to make it easy to read by PHP (further below, in index.php file).
    .htaccess
RewriteEngine On RewriteRule ^(.+)(\?.+)?$ index.php?path=$1 [L,QSA]
,,,,,,,,,,,,]'; $orders_data = json_decode($orders_data_json, true); $_SESSION["orders_data"] = $orders_data; > ?>
 > return null; > else < return $_SESSION["orders_data"]; >> function create_new_order ($data) < array_push($_SESSION["orders_data"], json_decode($data, true)); return $_SESSION["orders_data"]; >?>
 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 299 => 'Fake 4xx error from middleware API', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 426 => 'Upgrade Required', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 509 => 'Bandwidth Limit Exceeded', 510 => 'Not Extended' ); > if ($status_codes[$statusCode] !== null) < $status_string = $statusCode . ' ' . $status_codes[$statusCode]; header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode); >> ?>
 else < $path_parts = false; >if(empty($path_parts)) < return false; >if(strrpos($path_parts, '/') === false) < $path_parts .= '/'; >$path_parts = explode('/', $path_parts); if(empty($path_parts[count($path_parts) - 1])) < array_pop($path_parts); >return $path_parts; > function runApi () < /* * 1st param: method * 2nd param: detailed action * 3rd param: props */ $data = file_get_contents("php://input"); $path = decodePath(); $http_method = $_SERVER["REQUEST_METHOD"]; $method = isset($path[0]) && !empty($path[0]) ? $path[0] : null; $prop = isset($path[1]) && !empty($path[1]) ? $path[1] : null; $data = sizeof($data) ? $data : null; if($method === "orders") < switch($http_method) < case "GET": send_results(get_orders($prop)); break; case "PUT": send_results(create_new_order($data)); break; >> else < send_results("", 404); >> ?>

simple REST API in PHP

Start reading from the top to the bottom. On the very beginning of the file we include 3 files created in steps above. We set dummy/fake data from storage.php file and this function will place ORDERS data in session variable. runApi() function triggers a function which makes us our REST API in PHP working. Below, we can find decodePath() function which is very important – it is transforming GET parameters (taken from nice-looking path like http://my-domain.com/customers/11 by .htaccess file – look at step 1 at very top of the page). Below, there is a declaration of runApi() function. Inside, there is decoded URL path, and all GET parameters are transformed here into variables: $method, $prop and , we get the HTTP method used by client (browser) and sent data: $http_method, $data . So now we have everything to trigger a function from ORDERS.PHP file. We know what end point user called (/orders) and if there are additional parameters, like order index (for getting single order only).
So we have if statement which checks the method name (/orders) and what was the HTTP method and sends parameters to right function from orders.php file.
When you type URL to your simple REST API in PHP in your client (browser) like: http://localhost:80/php-api/orders you will see JSON with all ORDERS from storage.php file:

simple REST API in PHP

We can also use PUT method to insert data into storage ORDERS session variable (array). For this case we must use app like POSTMAN to make a PUT request to our simple php REST API. This method will return all ORDERS (with the new one). We can send JSON like that: with header Content-Type: application/json .

Example 2 – full simple REST API in PHP

In this example we will create almost normal REST API in PHP which allows to build bigger back-end API for your solution. We will still reuse files from example 1. In this example we extend our API to work with longer URL path: /method/end-point/parameter .

Check code of this example on our Gitlab account HERE.

    In storage.php file we add new data set for CUSTOMERS:
    storage.php

,,,,,,,,,,,]'; $customers_data = json_decode($customers_data_json, true); $orders_data_json = '[,,,,,,,,,,,,]'; $orders_data = json_decode($orders_data_json, true); $_SESSION["customers_data"] = $customers_data; $_SESSION["orders_data"] = $orders_data; > ?>
 public function create_new_order () < array_push($_SESSION["orders_data"], json_decode($this->data, true)); return $_SESSION["orders_data"]; > > ?>
, $_SESSION["customers_data"]); > public function get_customers () < return $_SESSION["customers_data"]; >public function get_single_customer () < foreach($_SESSION["customers_data"] as $customer) < if($customer["index"] == $this->prop) < return $customer; >> return null; > public function get_all_emails () < return array_map(function ($customer) < return $customer["email"]; >, $_SESSION["customers_data"]); > public function create_new_customer () < array_push($_SESSION["customers_data"], json_decode($this->data, true)); return $_SESSION["customers_data"]; > > ?>
, "PUT": < "default": "create_new_customer" >>, "orders": < "GET": < "default": "get_orders" >, "PUT": < "default": "create_new_order" >> >'; public $methods = []; public function __construct () < $this->methods = json_decode($this->methods_JSON, true); > public function get_function ($method, $http_method, $end_point) < if(!$end_point) < $end_point = "default"; >$method_item = $this->find_in_array_by_key($this->methods, $method); $http_method_item = $this->find_in_array_by_key($method_item, $http_method); $function = $this->find_in_array_by_key($http_method_item, $end_point); return $function; > private function find_in_array_by_key ($arr, $key) < $results = array_filter($arr, function ($item) use ($key) < return $item === $key; >, ARRAY_FILTER_USE_KEY); if(isset($results) && !empty($results) && count($results) === 1) < return $results[$key]; >else < return []; >> > ?>
 else < $path_parts = false; >if(empty($path_parts)) < return false; >if(strrpos($path_parts, '/') === false) < $path_parts .= '/'; >$path_parts = explode('/', $path_parts); if(empty($path_parts[count($path_parts) - 1])) < array_pop($path_parts); >return $path_parts; > function runApi () < /* * 1st param: method * 2nd param: detailed action * 3rd param: props */ $data = file_get_contents("php://input"); $path = decodePath(); $http_method = $_SERVER["REQUEST_METHOD"]; $method = isset($path[0]) && !empty($path[0]) ? $path[0] : null; $end_point = isset($path[1]) && !empty($path[1]) ? $path[1] : null; $prop = isset($path[2]) && !empty($path[2]) ? $path[2] : null; $data = sizeof($data) ? $data : null; $sheduler = new Switcher(); $func_name = $sheduler->get_function($method, $http_method, $end_point); if(!$func_name) < send_results("Method not found", 404); return; >switch ($method) < case "customers": $customer_functions = new Customer($prop, $data); $func_res = call_user_func( array($customer_functions, $func_name) ); send_results($func_res); break; case "orders": $orders_functions = new Orders($prop, $data); $func_res = call_user_func( array($orders_functions, $func_name) ); send_results($func_res); break; default: send_results("", 404); >> ?>
http://localhost:80/php-api-2/customers http://localhost:80/php-api-2/customers/emails http://localhost:80/php-api-2/customers/names http://localhost:80/php-api-2/customers/customer/1 http://localhost:80/php-api-2/orders

simple REST API in PHP

And you will get results like on screen shots below:

simple REST API in PHP

simple REST API in PHP

  • If you want to test PUT request, do it here for customers via URL: http://localhost:80/php-api-2/customers :
  • PHP simple REST API – summary

    I hope that by this examples I showed to you in a simple way how to build own REST API in a very basic form in PHP. I’m a JavaScript developer, but I like to work with PHP from time to time because this is quite simple language and in some parts, similar to JavaScript. And about 70% of the internet is running on apache servers with PHP, so there is always a high probability that even if you don’t code in PHP, that in the future you will need to do something in this. And by this simple REST API example I wanted to make things easier for you 🙂

    Источник

    Читайте также:  Http request and response python
    Оцените статью