Simple REST Demo\n"); // html tags only needed for browsers
echo("
URL = https://host/index.php?/users or https://host/index.php?/users/id
\n");
$url = $_SERVER['REQUEST_URI']; //get whole url - note that the demo resource is 'users'
$http = $_SERVER['REQUEST_METHOD']; // get http method verb
$p = parse_url( $url ); // http://php.net/manual/en/function.parse-url.php
print_r($p); // print out hash representation of the parsed url
$q=explode('/', $p['query']); // http://www.w3schools.com/php/func_string_explode.asp
print_r($q); // print out array representation of the querystring
$c=count($q); // length of array - lowest count is 2 - http://www.w3schools.com/php/func_array_count.asp
if ($q[1]!="users") { // any string will work but this demo is for 'users'
echo("
\nThe resource is 'users', not '$q[1]'");
}
else if($c<3) { // no id in the url - e.g. http://host/index.php?/users - do not use a trailing slash anywhere
if ($http=='GET') { // GET method etc.
echo("
\nGet all users - 200 (OK)"); // correct http return code included
}
else if ($http=='POST') {
echo("
\nCreate a user w/id generated on server - 201 (Created)");
}
else {
echo("
\nImproper verb use - 404 (Not Found)");
}
}
else // has id in the url - note count will be 3 - e.g. http://host/index.php?/users/3
{
if ($http=='GET') {
echo("
\nGet a specific user w/id=$q[2] - 200 (OK)");
}
else if ($http=='PUT') { // PUT and DELETE typically not supported in browsers except w/ajax but curl works
echo("
\nUpdate a specific user w/id=$q[2] - 200 (OK)");
} // PATCH is a variation of PUT
else if ($http=='DELETE') {
echo("
\nDelete a specific user w/id=$q[2] - 200 (OK)");
}
else {
echo("
\nImproper verb use - 404 (Not Found)");
}
}
/*
Homework Instructions:
1. Experiment with this very simple program and understand all parts of it using curl.
2. Develop an actual model in mysql based on your catalog from last week. See: http://www.php.net/manual/en/ref.mysql.php, http://www.w3schools.com/php/php_mysql_insert.asp, and http://www.w3schools.com/php/php_functions.asp for any needed reference.
3. Write a REST API for your catalog model with all CRUD functions (GET, POST, PUT, DELETE, PATCH) to mysql and deploy on gl. Be sure to include PATCH. Additional code to make this work is given to you in the book.
4. Make sure you return JSON. Every request to the API should do it job (like insert) and then return the JSON (if relevant) and the status code.
5. Use curl to test all parts of it and keep a text transcript that shows this in a file restapi.txt. Note the url.
6. Note the php and text url to your REST API for 'get all the resources' through the index.php router.
7. Include three urls from #5,6 in your hw toc.
*/
?>