I am new to restful architecture and i want to create an simple api for my application from scratch.....without any frameworks. At the moment i'm trying to understand how to get the "users" parameter in my URI so that i can route action to a controller that handles user login and registration. so far i have being able to view my URI with "$_SERVER['REQUEST_URI']" and the post method with "$_SERVER['REQUEST_METHOD']" but i'm unable to get the "users" parameter of the request ) when i add the "usesr" it return 404 error. Please can one enlighten me about....how this works and what i am doing wrong, thanks in advance.
Here is my code
$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['REQUEST_URI'];
$resource = array_shift($path);
if($resource == 'users'){
$name = array_shift($path);
if(empty($name)){
echo $method;
}else{
echo $method ." ".$name;
}
}else{
header('HTTP/1.1 404 Not Found');
}
When you go to the /users
url, the server tries to access that specific page, and there isn't anything there. You need to pass in whatever route you want using a query string.
So do /calendar_app_api?route=users
or /calendar_app_api?user_id=1
and then get the information through the $_GET
array.
Or what you can do is configure the server to route all requests to one index file and force anything after that to be passed as a query. check this resource out
$_SERVER['REQUEST_URI']
doesn't return an array, so I don't think array_shift
is going to return what you have in mind. You can use pathinfo
to get an array of all of the path components, including the filename, which would be the part of the path following the last slash in the URL:
$pathinfo = pathinfo($_SERVER['REQUEST_URI']);
$resource = $pathinfo['filename'];