Reputation: 122
I want to create a pure PHP REST API and I am quite new in backend development field, but I am experienced software developer, so some concepts are known to me.
However, after watching several tutorials on how to create REST API with PHP, all instructors were using simpler examples, where no nesting exists.
Simple Example:
GET /api/category/read.php
However, I want to create something like this:
GET /api/{user_id}/{folder_id}/{file_name}/read.php
I am struggling to find any tutorial covering this with PHP. And I have spent several hours trying to figure it out by myself by trying to modify the code I have seen in Tutorial videos. I mean if I do like they do, this would mean manually creating folders in my Project Folder for each {user_id}
and so forth for each sub-folder... but I do not think that such hardcoding is the solution.
I have found some Stack Overflow questions here relating closely to my question, but none have satisfying answers - makes me wonder that this if this is possible to do at all, but it seems so common (for example, I know that GitHub API has just that support /{user}/repos
) so I think it should be doable.
I would be really grateful if someone could help me out how to accomplish my goal. If not else, pointing to a tutorial / documentation that does just that is equivalently appreciated!
Upvotes: 0
Views: 1939
Reputation: 10971
Create a PHP script that receives every request (have Apache direct all requests to it), and then process the $_SERVER['REQUEST_URI']
variable to split the path into segments, storing the parts in variables of your choice. Then dispatch the request to sub-components as necessary.
Upvotes: 0
Reputation: 1418
You do not need to create the folder structure to achieve this. It would be more advantageous to use something like Apache Mod Rewrite or a framework like Laravel to help avoid the need to create the file structure you are describing and have a single endpoint for handling specific routes:
Using mod rewrite with Apache2 would work something like:
.htaccess
RewriteEngine On
RewriteBase /
RewriteRule ^api/(.+)/(.+)/(.+)/read /api/read.php?user_id=$1&folder_id=$2&file_name=$3
This would provide the URI variables in the $_GET and $_REQUEST supergobals in /api/read.php
Using the Laravel framework you can leverage their MVC approach and create dynamic routes which can capture the URL vars and deliver them to the desired Controller endpoint:
in your routes file:
Route::get('api/{user_id}/{folder_id}/{file_name}/read', Controller@read)
in the Controller:
public function read(user_id,folder_id,file_name){ /* do stuff */ }
There is alot more to know about the specifics of MVC and using Laravel to create an API, however, they have great documentation and tutorials.
Upvotes: 1