RESTful API package for Laravel 5
This is an API package for the Laravel framework. It allows you to build a flexible RESTful API that can be consumed externally and by your own application., (*1)
Installation
Composer
Add this to you composer.json file, in the require object:, (*2)
"mmanos/laravel-api": "dev-master"
After that, run composer install to install the package., (*3)
Service Provider
Register the Mmanos\Api\ApiServiceProvider in your app configuration file., (*4)
Class Alias
Add a class alias to app/config/app.php, within the aliases array., (*5)
'aliases' => array(
// ...
'Api' => 'Mmanos\Api\Api',
)
Laravel 4
Use the 1.0 branch or the v1.* tags for Laravel 4 support., (*6)
Configuration
Publish config files and migrations
Publish the lucadegasperi/oauth2-server-laravel config file and migrations to your application., (*7)
$ php artisan vendor:publish --provider="LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider"
Edit the published config file to fit your authentication needs. See this configuration options page for information., (*8)
Publish the mmanos/laravel-api config file and migrations to your application., (*9)
$ php artisan vendor:publish --provider="Mmanos\Api\ApiServiceProvider"
And then run the migrations., (*10)
$ php artisan migrate
Add the following line to your app/Http/Kernel.php file in the $middleware array to catch any OAuth error and respond appropriately:, (*11)
'LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware'
In order to make some the authorization and resource server work correctly with Laravel 5, remove the App\Http\Middleware\VerifyCsrfToken line from the $middleware array and place it in the $routeMiddleware array like this: 'csrf' => 'App\Http\Middleware\VerifyCsrfToken',., (*12)
Note: remember to add the csrf middleware manually on any route where it's appropriate., (*13)
Handling Exceptions
We need to modify the exception handler to properly format exceptions thrown by this package. Update the App/Exceptions/Handler.php file to use the exception handler from this package., (*14)
use Exception;
use Mmanos\Api\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
...
}
Then add the Mmanos\Api\Exceptions\HttpException exception class to the $dontReport array so regular HTTP Exceptions are not reported., (*15)
Controllers
Configuration
Add the ControllerTrait to each of your API controllers. You could optionally add this to a BaseController extended by all of your other controllers., (*16)
use Illuminate\Routing\Controller;
use Mmanos\Api\ControllerTrait;
class BaseController extends Controller
{
use ControllerTrait;
}
If you return a pagination object from your controller action this package will add the following headers to the response:, (*17)
- Pagination-Page
- Pagination-Num
- Pagination-Total
- Pagination-Last-Page
You may access the response object and set any additional headers directly from your controller action:, (*18)
$this->response()->header('Example-Header', 'Example value');
Errors
Dealing with errors when building your API is easy. Simply use the Api::abort method to throw an exception that will be formatted in a useful manner., (*19)
Throw a 404 Not Found error:, (*20)
Api::abort(404);
Or a 403 Access Denied error:, (*21)
Api::abort(403);
Customize the error message:, (*22)
Api::abort(403, 'Access denied to scope: users:write');
Pass the errors from a validation object to get a clean response with all validation errors:, (*23)
Api::abort(422, $validator->errors());
Protecting your API endpoints
You may use the protect route filter to ensure the request is authenticated:, (*24)
$this->beforeFilter('protect');
Or you may call the Api::protect() method directly., (*25)
If this check fails, a call to Api::abort(401) is made resulting in an Unauthorized error response., (*26)
Checking scope access
Use the checkscope route filter to ensure the requested resource is accessible:, (*27)
$this->beforeFilter('checkscope:users.write');
Or you may call the Api::checkScope('users:write') method directly., (*28)
If this check fails, a call to Api::abort(403) is made resulting in an Access Denied error response with the scope name., (*29)
Any model, collection, or pagination object returned by your controller action will be automatically sent through any bound transformer classes., (*30)
Transformers allow you to easily and consistently transform objects into an array. By using a transformer you can type-cast integers, type-cast booleans, and nest relationships., (*31)
Api::bindTransformer('User', 'Transformers\User');
Set a class property
Alternatively, you could add a transformer property to your class to be auto-recognized by this package:, (*32)
class User extends Eloquent
{
public $transformer = 'Transformers\User';
}
Ensure your transformer class has a transform static method:, (*33)
namespace Transformers;
class User
{
public function transform($object, $request)
{
$output = $object->toArray();
$output['id'] = (int) $output['id'];
$output['created_at'] = $object->created_at->setTimezone('UTC')->toISO8601String();
$output['updated_at'] = $object->updated_at->setTimezone('UTC')->toISO8601String();
if ($request->input('hide_email')) {
unset($output['email']);
}
return $output;
}
}
Internal Requests
A big part of this package is being able to perform requests on your API internally. This allows you to build your application on top of a consumable API., (*34)
Use the Api::internal() method to initiate an internal request:, (*35)
$users_array = Api::internal('api/users')->get();
$users_array = Api::internal('api/users', array('sort' => 'newest'))->get();
Specify HTTP method
$new_user_array = Api::internal('api/users', array('email' => 'test@example.com'))->post();
CORS Support
CORS support is enabled by default, but only if the Origin header is detected. Adjust the settings in the config file to control the behavior and header values., (*36)