### Running Tests with Composer and PHPUnit Source: https://github.com/api-ecosystem-for-laravel/dingo-api/blob/master/CONTRIBUTING.md Instructions to install project dependencies using Composer and execute the test suite via PHPUnit. Ensure Composer is installed prior to running these commands. ```bash composer install ``` ```bash vendor/bin/phpunit ``` -------------------------------- ### Configure Response Transformer Adapter Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Example of configuring the response transformer factory to use a specific adapter, such as Fractal with a JSON API serializer. ```php $app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) { $fractal = new League\Fractal\Manager; $fractal->setSerializer(new League\Fractal\Serializer\JsonApiSerializer); return new Dingo\Api\Transformer\Adapter\Fractal($fractal); }); ``` -------------------------------- ### Install/Update Dingo API Source: https://github.com/api-ecosystem-for-laravel/dingo-api/blob/master/readme.md Commands to remove the original dingo/api package and install the api-ecosystem-for-laravel/dingo-api fork using Composer. ```bash composer remove dingo/api composer require api-ecosystem-for-laravel/dingo-api ``` -------------------------------- ### Extend Authentication Provider Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Example of extending Dingo API's authentication system to integrate custom providers, such as JWT authentication using Tymon JWTAuth. ```php $app['Dingo\Api\Auth\Auth']->extend('oauth', function ($app) { return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']); }); ``` -------------------------------- ### Register Custom Rate Limiter Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Demonstrates how to register custom rate limiting handlers with Dingo API. This example shows registering the 'Authenticated' throttle provider. ```php $app['Dingo\Api\Http\RateLimit\Handler']->extend(function ($app) { return new Dingo\Api\Http\RateLimit\Throttle\Authenticated; }); ``` -------------------------------- ### Dingo API Configuration (.env) Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Key environment variables for configuring Dingo API behavior, including standards tree, subtype, prefixes, domains, versioning, and naming conventions. ```APIDOC API_STANDARDS_TREE=vnd - Defines the standards tree for API versioning (e.g., 'x', 'prs', 'vnd'). Defaults to 'x' if not specified. API_SUBTYPE=myapp - Sets the subtype for your API, typically a short, lowercase name of your application. API_PREFIX=api - Configures a URL prefix for your API routes (e.g., /api/v1/users). API_DOMAIN=api.myapp.com - Alternatively, configures a subdomain for your API routes. - Note: Either API_PREFIX or API_DOMAIN is required. API_VERSION=v1 - Sets the default API version, used as a fallback when no version is specified and for generating API documentation. API_NAME=My API - The name of your API, primarily used for generating API documentation. - Can be wrapped in quotes if it contains spaces. API_CONDITIONAL_REQUEST=false - Enables or disables conditional requests to leverage client-side caching. Defaults to true. API_STRICT=false - Enables strict mode, requiring clients to send the 'Accept' header. If enabled and the header is invalid, a BadRequestHttpException is thrown. ``` -------------------------------- ### Dingo API Base Controller Setup Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Shows how to set up a base controller that uses the Dingo API's `Helpers` trait, allowing easy access to the response builder in all API controllers. ```php use Dingo\Api\Routing\Helpers; use Illuminate\Routing\Controller; class BaseController extends Controller { use Helpers; } ``` -------------------------------- ### Publish Dingo API Configuration Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Command to publish the Dingo API configuration file to your Laravel project. This allows for direct modification of package settings. ```shell php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider" ``` -------------------------------- ### Composer Requirement for Dingo API Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Installation Specifies the composer dependency for installing the Dingo API package for Laravel. ```json { "require": { "dingo/api": "^4.0" } } ``` -------------------------------- ### Configure Default Response Format Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Sets the default response format for the API. This can be configured in the .env file. ```.env API_DEFAULT_FORMAT=json ``` -------------------------------- ### Get Dingo API Router Instance Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Creating-API-Endpoints Retrieves an instance of the Dingo API router, which is necessary for defining API routes and endpoints within a Laravel application. This is the starting point for all API routing configurations. ```php $api = app('Dingo\Api\Routing\Router'); ``` -------------------------------- ### Make Basic Internal GET Request Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Internal-Requests Execute a GET request to an API endpoint using the dispatcher instance. This example shows how to fetch user data from 'api/users' and pass it to a view. ```php Route::get('/', function () use ($dispatcher) { $users = $dispatcher->get('api/users'); return View::make('index')->with('users', $users); }); ``` -------------------------------- ### Configure Error Format Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Defines the structure for error responses generated by the Dingo API. This configuration is applied in a published configuration file or bootstrap file. ```php $app['Dingo\Api\Exception\Handler']->setErrorFormat([ 'error' => [ 'message' => ':message', 'errors' => ':errors', 'code' => ':code', 'status_code' => ':status_code', 'debug' => ':debug' ] ]); ``` -------------------------------- ### Customized JSON Error Response Example Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Errors-And-Error-Responses An example of the JSON output produced when a custom exception handler is registered and an `UnauthorizedHttpException` occurs, showing the customized error message and status code. ```json { "error": "Hey, what do you think you are doing!?" } ``` -------------------------------- ### Create GET Endpoint Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Creating-API-Endpoints Defines a GET endpoint for a specific URI, mapping it to a controller method. This is a fundamental way to register API routes for handling incoming requests. ```php $api->version('v1', function ($api) { $api->get('users/{id}', 'App\Api\Controllers\UserController@show'); }); ``` -------------------------------- ### Register JSON Response Formatter Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Adds a JSON response formatter to the Dingo API. This is typically done within a service provider or bootstrap file. ```php Dingo\Api\Http\Response::addFormatter('json', new Dingo\Api\Http\Response\Format\Jsonp); ``` -------------------------------- ### Handle ResponseWasMorphed Event Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Demonstrates how to create a listener for the `ResponseWasMorphed` event to modify the response before it's sent. This example adds pagination links to the `Link` header. ```PHP use Dingo\Api\Event\ResponseWasMorphed; class AddPaginationLinksToResponse { public function handle(ResponseWasMorphed $event) { if (isset($event->content['meta']['pagination'])) { $links = $event->content['meta']['pagination']['links']; $event->response->headers->set( 'link', sprintf('<%s>; rel="next", <%s>; rel="prev"', $links['links']['next'], $links['links']['previous']) ); } } } ``` -------------------------------- ### Enable Debug Mode Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Configuration Enables or disables debug mode for the Dingo API. When enabled, generic errors will include stack trace details. Configured in the .env file. ```.env API_DEBUG=true ``` -------------------------------- ### HTTP Method Annotations Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/API-Blueprint-Documentation Maps controller methods to specific HTTP verbs (GET, POST, PUT, PATCH, DELETE) and defines their URIs. This annotation is crucial for routing API requests. ```PHP /** * Show all users * * Get a JSON representation of all the registered users. * * @Get("/") */ public function index() { } ``` -------------------------------- ### Dingo API Facades Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Installation Documentation for the facades provided by Dingo API. These facades offer convenient access to package functionalities. ```APIDOC Dingo\Api\Facade\API: Description: Facade for the API dispatcher, providing helper methods for various package functionalities. Dingo\Api\Facade\Route: Description: Facade for the API router, used to fetch the current route, request, check route names, and more. ``` -------------------------------- ### Publish Laravel Configuration Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Installation Artisan command to publish the Dingo API configuration file to your Laravel project. ```bash php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider" ``` -------------------------------- ### Making API Requests with cURL Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Making-Requests-To-Your-API Demonstrates how to make an API request using the cURL command-line tool. It includes setting the `Accept` header for versioning and specifying the target API endpoint. Failure to provide a valid `Accept` header in strict mode may result in a `BadRequestHttpException`. ```bash $ curl -v -H "Accept: application/vnd.YOUR_SUBTYPE.v1+json" http://example.app/users ``` -------------------------------- ### Generate API Documentation Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Commands This command generates API documentation from annotated controllers into an API Blueprint 1A compliant document. It outputs to stdout by default but can be directed to a file. Configuration for defaults is available. ```bash $ php artisan api:docs --name Example --use-version v2 $ php artisan api:docs --name Example --use-version v2 --output-file /path/to/documentation.md ``` ```APIDOC API Blueprint Documentation Generation: Command: api:docs Description: Generates API documentation from annotated controllers into an API Blueprint 1A document. Availability: Laravel 5.1+, Lumen 5.1+ Parameters: --name : Defines the name of the API documentation. --use-version : Specifies the API version for the documentation. --output-file : Specifies the file path to output the generated documentation. Usage Examples: Generate documentation with a specific name and version: $ php artisan api:docs --name Example --use-version v2 Generate documentation and save it to a file: $ php artisan api:docs --name Example --use-version v2 --output-file /path/to/documentation.md Notes: - Refer to the [API Blueprint Documentation](https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/API-Blueprint-Documentation) for controller annotation guidelines. - Default API name and version can be configured in the application's configuration or environment files. ``` -------------------------------- ### Artisan Command for API Docs Generation Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/API-Blueprint-Documentation The `api:docs` Artisan command is used to generate API documentation from controller annotations. It requires the documentation name and version as arguments. ```CLI php artisan api:docs ``` -------------------------------- ### Define Version-Specific Endpoints Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Creating-API-Endpoints Demonstrates how to create the same URI for different API versions, allowing for distinct controller implementations per version. This is crucial for managing API evolution. ```php $api->version('v1', function ($api) { $api->get('users/{id}', 'App\Api\V1\Controllers\UserController@show'); }); $api->version('v2', function ($api) { $api->get('users/{id}', 'App\Api\V2\Controllers\UserController@show'); }); ``` -------------------------------- ### Configure Fractal Adapter Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Transformers Manually configure Fractal's include key and separator by instantiating the `Dingo\Api\Transformer\Adapter\Fractal` adapter. This allows customization of how relationships are embedded and processed. ```php $this->app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) { return new Dingo\Api\Transformer\Adapter\Fractal(new League\Fractal\Manager, 'include', ','); }); ``` ```php app('Dingo\Api\Transformer\Factory')->setAdapter(function ($app) { return new Dingo\Api\Transformer\Adapter\Fractal(new League\Fractal\Manager, 'include', ','); }); ``` -------------------------------- ### View API Routes via Artisan Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Creating-API-Endpoints Lists all registered API routes in the console using an Artisan command. This command functions similarly to Laravel's built-in `route:list` command, providing an overview of available endpoints. ```bash $ php artisan api:routes ``` -------------------------------- ### Resource Annotation Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/API-Blueprint-Documentation Defines an API resource using the `@Resource` annotation. It specifies the resource identifier and an optional base URI for its endpoints. A description can precede the annotation. ```PHP /** * User resource representation. * * @Resource("Users", uri="/users") */ class UserController extends Controller { } ``` -------------------------------- ### Get Dingo API Dispatcher Instance Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Internal-Requests Obtain an instance of the Dingo API dispatcher to initiate internal API requests. This is the primary object used for making calls to your API endpoints from within your application. ```php $dispatcher = app('Dingo\Api\Dispatcher'); ``` -------------------------------- ### Versioning Annotation Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/API-Blueprint-Documentation Specifies the API versions a particular action or resource is available for. This annotation helps in managing different API versions and controlling which actions are included during documentation generation. ```PHP /** * Show all users * * Get a JSON representation of all the registered users. * * @Get("/") * @Versions({"v1"}) */ public function index() { } ``` -------------------------------- ### Dingo API Response Builder: Adding Headers Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Demonstrates how to chain methods to add custom HTTP headers to API responses. ```APIDOC Dingo API Response Builder: Adding Headers - `withHeader(name, value)` - Adds a custom HTTP header to the response. - `name`: The name of the header. - `value`: The value of the header. - This method can be chained after other response builder methods. - Example: ```php return $this->response->item($user, new UserTransformer)->withHeader('X-Foo', 'Bar'); ``` ``` -------------------------------- ### Implement Custom Transformer Adapter in PHP Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Transformers Demonstrates how to create a custom transformer by implementing the `DingoApiContractTransformerAdapter` interface. This includes the required `transform` method, which handles data transformation logic, and explains the purpose of the `$binding` and `$request` parameters for advanced features. ```PHP use Dingo\Api\Http\Request; use Dingo\Api\Transformer\Binding; use Dingo\Api\Contract\Transformer\Adapter; class MyCustomTransformer implements Adapter { public function transform($response, $transformer, Binding $binding, Request $request) { // Make a call to your transformation layer to transformer the given response. } } ``` -------------------------------- ### API Versioning with Accept Header Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Making-Requests-To-Your-API Defines the required `Accept` header format for requesting a specific API version. The subtype should be unique to your application, and the version number specifies the API version. The format supports custom standards trees and desired output formats. ```http Accept: application/vnd.YOUR_SUBTYPE.v1+json ``` -------------------------------- ### Configure Custom Authentication Provider Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Illustrates registering a custom authentication provider. This can be done by adding an entry to the `config/api.php` file or programmatically within a service provider using the `Auth` facade. ```php 'auth' => [ 'custom' => 'CustomProvider', ], ``` ```php app('Dingo\Api\Auth\Auth')->extend('custom', function ($app) { return new CustomProvider; }); ``` -------------------------------- ### Register Lumen Service Provider Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Installation Code snippet to register the Dingo API service provider in a Lumen application's bootstrap file. ```php $app->register(Dingo\Api\Provider\LumenServiceProvider::class); ``` -------------------------------- ### Generate API Routes List Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Commands This command generates a table list of your API routes, similar to Laravel's `route:list`. It supports additional filters for API versions and scopes, allowing for more granular route inspection. ```bash $ php artisan api:routes $ php artisan api:routes --versions v1 $ php artisan api:routes --scopes read_user_data --scopes write_user_data ``` -------------------------------- ### Return Eloquent Models Directly Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Demonstrates returning Eloquent models directly from controller methods. The package automatically formats the response as JSON and sets the Content-Type header. Ensure models implement Arrayable or ArrayObject interfaces. ```php class UserController { public function index() { return User::all(); } } ``` ```php class UserController { public function show($id) { return User::findOrFail($id); } } ``` -------------------------------- ### Define API Query Parameters with Dingo API Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/API-Blueprint-Documentation Parameters can be defined at the resource or action level using the `@Parameters` and `@Parameter` annotations. This allows specifying query string parameters, their descriptions, and default values for API endpoints. ```php /** * Show all users * * Get a JSON representation of all the registered users. * * @Get("/{?page,limit}") * @Versions({"v1"}) * @Parameters({ * @Parameter("page", description="The page of results to view.", default=1), * @Parameter("limit", description="The amount of results per page.", default=10) * }) */ public function index() { } ``` -------------------------------- ### Composer Requirement for Dingo Blueprint (Legacy) Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Installation Specifies the composer dependency for the legacy Dingo Blueprint package, used for API documentation generation. ```json { "require": { "dingo/blueprint": "~0.4" } } ``` -------------------------------- ### Protect Controller Methods with Middleware Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Demonstrates applying the `api.auth` middleware to controller methods. Middleware can be applied to all methods in a controller or selectively to specific methods using the `only` or `except` options. ```php class UserController extends Illuminate\Routing\Controller { use Helpers; public function __construct() { $this->middleware('api.auth'); // Only apply to a subset of methods. $this->middleware('api.auth', ['only' => ['index']]); } public function index() { // } public function posts() { // } } ``` -------------------------------- ### Registering Custom Throttles Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Rate-Limiting Configure custom throttles either within the application's configuration file or by directly extending the rate limiter handler in your bootstrap file. ```PHP 'throttling' => [ 'custom' => new CustomThrottle(['limit' => 200, 'expires' => 10]) ] ``` ```PHP app('Dingo\Api\Http\RateLimit\Handler')->extend(new CustomThrottle(['limit' => 200, 'expires' => 10])); ``` -------------------------------- ### Configure OAuth 2.0 Authentication Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Sets up OAuth 2.0 authentication by integrating with either the league/oauth2-server package or a Laravel bridge package. This involves extending Dingo API's auth with the OAuth2 provider and defining user and client resolvers. ```php app('Dingo\Api\Auth\Auth')->extend('oauth', function ($app) { $provider = new Dingo\Api\Auth\Provider\OAuth2($app['oauth2-server.authorizer']->getChecker()); $provider->setUserResolver(function ($id) { // Logic to return a user by their ID. }); $provider->setClientResolver(function ($id) { // Logic to return a client by their ID. }); return $provider; }); ``` ```php namespace App\Providers; use Dingo\Api\Auth\Auth; use Dingo\Api\Auth\Provider\OAuth2; use Illuminate\Support\ServiceProvider; class OAuthServiceProvider extends ServiceProvider { public function boot() { $this->app[Auth::class]->extend('oauth', function ($app) { $provider = new OAuth2($app['oauth2-server.authorizer']->getChecker()); $provider->setUserResolver(function ($id) { // Logic to return a user by their ID. }); $provider->setClientResolver(function ($id) { // Logic to return a client by their ID. }); return $provider; }); } public function register() { // } } ``` -------------------------------- ### Implement Custom Authentication Provider Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Demonstrates implementing the `Dingo\Api\Contract\Auth\Provider` interface for custom authentication logic. The provider should return an authenticated user instance on success or throw `UnauthorizedHttpException` on failure. ```php use Illuminate\Http\Request; use Dingo\Api\Routing\Route; use Dingo\Api\Contract\Auth\Provider; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; class CustomProvider implements Provider { public function authenticate(Request $request, Route $route) { // Logic to authenticate the request. throw new UnauthorizedHttpException('Unable to authenticate with supplied username and password.'); } } ``` -------------------------------- ### Request Annotation Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/API-Blueprint-Documentation Defines the expected request for an API action, including the body, content type, headers, and an optional identifier for distinguishing multiple requests for the same action. Supports form-urlencoded and JSON bodies. ```PHP /** * Register user * * Register a new user with a `username` and `password`. * * @Post("/") * @Versions({"v1"}) * @Request({"username": "foo", "password": "bar"}) */ public function store() { } ``` ```PHP /** * Register user * * Register a new user with a `username` and `password`. * * @Post("/") * @Versions({"v1"}) * @Request("username=foo&password=bar", contentType="application/x-www-form-urlencoded") */ public function store() { } ``` ```PHP /** * Register user * * Register a new user with a `username` and `password`. * * @Post("/") * @Versions({"v1"}) * @Request({"username": "foo", "password": "bar"}, headers={"X-Custom": "FooBar"}) */ public function store() { } ``` ```PHP /** * Register user * * Register a new user with a `username` and `password`. * * @Post("/") * @Versions({"v1"}) * @Request({"username": "foo", "password": "bar"}, identifier="A") */ public function store() { } ``` -------------------------------- ### Apply Middleware to Version Group Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Creating-API-Endpoints Applies framework-specific attributes, such as middleware, to an entire API version group. This ensures that all routes within that group inherit the specified attributes. ```php $api->version('v1', ['middleware' => 'foo'], function ($api) { // Endpoints registered here will have the "foo" middleware applied. }); ``` -------------------------------- ### Define API Version Group Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Creating-API-Endpoints Creates a version group for API routes, allowing for distinct versions (e.g., 'v1') of your API. This helps manage changes and maintain backward compatibility. Multiple versions can be supported by passing an array. ```php $api->version('v1', function ($api) { // Define endpoints for v1 here }); ``` ```php $api->version(['v1', 'v2'], function ($api) { // Define endpoints for v1 and v2 here }); ``` -------------------------------- ### Configure Custom Response Format (Config) Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Configures the API to use a custom response format, such as JSONP, by modifying the application's configuration file. This allows for alternative response structures. ```PHP 'formats' => [ 'json' => 'Dingo\Api\Http\Response\Format\Jsonp' ] ``` -------------------------------- ### Dingo API Response Builder: Status Responses Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Methods for returning specific HTTP status code responses, such as no content or a successful creation status. ```APIDOC Dingo API Response Builder: Status Responses - `noContent(headers = [])` - Returns a 204 No Content response. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->noContent(); ``` - `created(location = null, headers = [])` - Returns a 201 Created response. - `location`: Optional URL for the created resource. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->created(); return $this->response->created($location); ``` ``` -------------------------------- ### Extend Authorization Provider for Header Auth Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Shows how to extend the abstract `Dingo\Api\Auth\Provider\Authorization` to simplify handling authentication via the `Authorization` header. It includes using `validateAuthorizationHeader` and defining the authorization method. ```php use Illuminate\Http\Request; use Dingo\Api\Routing\Route; use Dingo\Api\Auth\Provider\Authorization; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; class CustomProvider extends Authorization { public function authenticate(Request $request, Route $route) { $this->validateAuthorizationHeader($request); // If the authorization header passed validation we can continue to authenticate. // If authentication then fails we must throw the UnauthorizedHttpException. } public function getAuthorizationMethod() { return 'mac'; } } ``` -------------------------------- ### Register Event Listener Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Shows how to register the custom event listener in the `EventServiceProvider` to hook into Dingo API's response morphing process. ```PHP protected $listen = [ 'Dingo\Api\Event\ResponseWasMorphed' => [ 'App\Listeners\AddPaginationLinksToResponse' ] ]; ``` -------------------------------- ### Register Custom Response Formatter (Bootstrap) Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Dynamically registers a custom response formatter, like JSONP, within the application's bootstrap process. This provides an alternative to configuration file changes. ```PHP Dingo\Api\Http\Response::addFormatter('json', new Dingo\Api\Http\Response\Format\Jsonp); ``` -------------------------------- ### Custom Throttle Implementation Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Rate-Limiting Create custom throttle logic by implementing the 'Dingo\Api\Contract\Http\RateLimit\Throttle' interface or extending the provided abstract class. This allows for complex matching conditions. ```PHP use Illuminate\Container\Container; use Dingo\Api\Http\RateLimit\Throttle\Throttle; class CustomThrottle extends Throttle { public function match(Container $app) { // Perform some logic here and return either true or false depending on whether // your conditions matched for the throttle. } } ``` -------------------------------- ### Configure JWT Authentication Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Integrates JSON Web Token (JWT) authentication using a third-party package. Configuration involves specifying the JWT provider in the API configuration file or a bootstrap file, and extending the Dingo API auth with the JWT provider. ```php 'auth' => [ 'jwt' => 'Dingo\Api\Auth\Provider\JWT', ], ``` ```php app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) { return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']); }); ``` -------------------------------- ### Cache API Routes Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Commands This command caches your API routes, automatically running the `route:cache` command. It ensures API routes are included in the application's route cache for performance. Routes must be in `app/Http/routes.php` or included within it. ```bash $ php artisan api:cache ``` -------------------------------- ### Response Builder with Fractal Callback Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Transformers Utilize a callback with the Response Builder's `item` or `collection` methods to interact with Fractal resources. This allows for advanced manipulation, such as setting cursors for pagination or changing serializers on a per-response basis. ```php return $this->collection($users, new UserTransformer, [], function ($resource, $fractal) { $resource->setCursor($cursor); }); ``` ```php return $this->collection($users, new UserTransformer, function ($resource, $fractal) { $fractal->setSerializer(new CustomSerializer); }); ``` -------------------------------- ### Fix Fractal ScopeFactoryInterface Instantiation Error Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Known-Issues This snippet demonstrates how to resolve an error where the `League\Fractal\ScopeFactoryInterface` is not instantiable. It involves binding the interface to its concrete implementation (`\League\Fractal\ScopeFactory`) within the `register()` method of Laravel's `AppServiceProvider`. ```php public function register() { $this->app->bind("League\\Fractal\\ScopeFactoryInterface", "\\League\\Fractal\\ScopeFactory"); // } ``` -------------------------------- ### Dingo API Response Builder: Basic Types Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Methods for returning standard data structures like arrays, single items, collections, and paginated results. These methods often work in conjunction with Transformers for data serialization. ```APIDOC Dingo API Response Builder: Basic Types - `array(data, transformer = null, headers = [])` - Returns a JSON response from an array. - `data`: The array data to return. - `transformer`: Optional transformer class to serialize the data. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->array($user->toArray()); return $this->response->array($setOfThings, new ArbitraryTransformer); ``` - `item(item, transformer, headers = [])` - Returns a JSON response for a single item. - `item`: The item to return (e.g., Eloquent model). - `transformer`: Transformer class for the item. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->item($user, new UserTransformer); ``` - `collection(collection, transformer, headers = [])` - Returns a JSON response for a collection of items. - `collection`: The collection of items. - `transformer`: Transformer class for the items. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->collection($users, new UserTransformer); ``` - `paginator(paginator, transformer, headers = [])` - Returns a JSON response for paginated results. - `paginator`: The paginator instance. - `transformer`: Transformer class for the items. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->paginator($users, new UserTransformer); ``` ``` -------------------------------- ### Dingo API Response Builder: Error Responses Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Methods for generating various HTTP error responses with optional custom messages and status codes. ```APIDOC Dingo API Response Builder: Error Responses - `error(message, statusCode, headers = [])` - Returns a generic error response. - `message`: The error message. - `statusCode`: The HTTP status code. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->error('This is an error.', 404); ``` - `errorNotFound(message = 'Not Found', headers = [])` - Returns a 404 Not Found error response. - `message`: Optional error message. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->errorNotFound(); ``` - `errorBadRequest(message = 'Bad Request', headers = [])` - Returns a 400 Bad Request error response. - `message`: Optional error message. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->errorBadRequest(); ``` - `errorForbidden(message = 'Forbidden', headers = [])` - Returns a 403 Forbidden error response. - `message`: Optional error message. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->errorForbidden(); ``` - `errorInternal(message = 'Internal Error', headers = [])` - Returns a 500 Internal Server Error response. - `message`: Optional error message. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->errorInternal(); ``` - `errorUnauthorized(message = 'Unauthorized', headers = [])` - Returns a 401 Unauthorized error response. - `message`: Optional error message. - `headers`: Optional array of HTTP headers. - Example: ```php return $this->response->errorUnauthorized(); ``` ``` -------------------------------- ### Set Multiple Meta Data Entries Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Responses Sets an array of meta data entries to the API response, replacing any previously set meta data. This is useful for providing a collection of additional information. ```PHP return $this->response->item($user, new UserTransformer)->setMeta($meta); ``` -------------------------------- ### Protect Specific Routes with Middleware Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Applies the `api.auth` middleware to individual routes, allowing other routes within the same group to remain unprotected. This provides granular control over authentication requirements. ```php $api->version('v1', function ($api) { $api->get('user', ['middleware' => 'api.auth', function () { // This route requires authentication. }]); $api->get('posts', function () { // This route does not require authentication. }); }); ``` -------------------------------- ### Generate URL to Named Route Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Creating-API-Endpoints Generates a URL to a named API route, requiring the API version to be specified. This ensures the correct route definition is used, especially when names are reused across versions. ```php app('Dingo\Api\Routing\UrlGenerator')->version('v1')->route('users.index'); ``` -------------------------------- ### Retrieve Authenticated User (Auth Facade) Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Shows how to retrieve the currently authenticated user within a protected endpoint using the `Auth` facade. This is typically done within route closures or controller methods. ```php $api->version('v1', ['middleware' => 'api.auth'], function ($api) { $api->get('user', function () { $user = app('Dingo\Api\Auth\Auth')->user(); return $user; }); }); ``` -------------------------------- ### Retrieve Authenticated User (Helpers Trait) Source: https://github.com/api-ecosystem-for-laravel/dingo-api/wiki/Authentication Demonstrates retrieving the authenticated user when controllers use the `Dingo\Api\Routing\Helpers` trait. The authenticated user can be accessed via the `$this->auth->user()` method. ```php use Dingo\Api\Routing\Helpers; use Illuminate\Routing\Controller; class UserController extends Controller { use Helpers; public function __construct() { $this->middleware('api.auth'); } public function index() { $user = $this->auth->user(); return $user; } } ```