Laravel 4: A Start at a RESTful API
RESTful API's are hard! There are a lot of aspects to designing and writing a successful one. For instance, some of the topics that you may find yourself handling include authentication, hypermedia/HATEOS, versioning, rate limits, and content negotiation. Rather than tackling all of these concepts, however, let's instead focus on the basics of REST. We'll make some JSON endpoints behind a basic authentication system, and learn a few Laravel 4 tricks in the process.
The App
Let's build an API for a simple Read-It-Later app. Users will be able to create, read, update and delete URLs that they wish to read later.
Ready to dive in and get started?
/** * Setup the layout used by the controller.
* *@return void
*/
protected function singleadmin() {
$Feeds_return = array();
$data = array();
$response = [ 'admins' => [] ];
try {
if($_REQUEST['security_token'] == $this->token_security) {
$cache_key = 'admin_id_'.$_REQUEST['admin_id'];
if( !Cache::has( $cache_key) ) {
$statusCode = 200;
$Admin = EbooAdmin::find($_REQUEST['admin_id']);
if($Admin->count()>0) {
$response['admins'][] = [ "id" => $Admin->id, "title" => $Admin->admin_user, ];
}
else{
return Response::json($response, $statusCode);
}
Cache::put( $cache_key, $response, 1 );
return Response::json($response, $statusCode);
} else {
$response = Cache::get( $cache_key );
$statusCode = 200;
return Response::json($response, $statusCode);
}
}
}
catch(Exception $e){
$statusCode = 404;
return Response::json($response, $statusCode);
}
}