### Install Dependencies and Run Tests Source: https://github.com/dingo/api/blob/master/CONTRIBUTING.md Installs project dependencies using Composer and then executes the test suite using PHPUnit. This ensures the project's code quality and functionality. ```bash $ composer install $ vendor/bin/phpunit ``` -------------------------------- ### Add Dingo API Composer Requirement Source: https://github.com/dingo/api/wiki/Installation Specifies the Dingo API package version required in the `composer.json` file. This ensures the correct version of the API package is installed for your project. ```JSON { "require": { "dingo/api": "^3.0.0" } } ``` -------------------------------- ### Publish Dingo API Configuration (Laravel) Source: https://github.com/dingo/api/wiki/Installation Artisan command to publish the Dingo API configuration file for Laravel projects. This step is optional if you do not need to make custom configuration changes. ```Shell php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider" ``` -------------------------------- ### Register Dingo API Service Provider (Lumen) Source: https://github.com/dingo/api/wiki/Installation Code snippet to register the Dingo API service provider in Lumen's `bootstrap/app.php` file. This makes the Dingo API functionalities available within your Lumen application. ```PHP $app->register(Dingo\Api\Provider\LumenServiceProvider::class); ``` -------------------------------- ### Custom Exception Response Example Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses Example JSON output for a custom exception response, showing a personalized error message and status code. ```json { "error": "Hey, what do you think you are doing!?" } ``` -------------------------------- ### OAuth 2.0 Service Provider Configuration Source: https://github.com/dingo/api/wiki/Authentication This example shows how to register the OAuth 2.0 authentication provider within a Laravel Service Provider. It defines the necessary user and client resolvers to handle authentication requests. ```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 Request Validator Source: https://github.com/dingo/api/wiki/Extending-The-Core Provides an example of creating a custom validator by implementing the `Dingo\Api\Contract\Http\Validation\Validator` interface. This interface requires a `validate` method that returns a boolean indicating success or failure. The example checks for the presence of specific headers. ```php headers = $headers; } public function validate(Request $request) { foreach ($this->headers as $header) { if (! $request->headers->has($header)) { return false; } } return true; } } ``` -------------------------------- ### Making API Requests with cURL Source: https://github.com/dingo/api/wiki/Making-Requests-To-Your-API Demonstrates how to use the cURL command-line tool to send a request to the API, including the necessary 'Accept' header for versioning and content negotiation. ```bash $ curl -v -H "Accept: application/vnd.YOUR_SUBTYPE.v1+json" http://example.app/users ``` -------------------------------- ### Make Internal GET Request Source: https://github.com/dingo/api/wiki/Internal-Requests Demonstrates making an internal GET request to an API endpoint using the dispatcher. The response received is the pre-transformed data, not a raw HTTP response object. ```php Route::get('/', function () use ($dispatcher) { $users = $dispatcher->get('api/users'); return View::make('index')->with('users', $users); }); ``` -------------------------------- ### api:docs Command Source: https://github.com/dingo/api/wiki/Commands Generates API documentation from annotated controllers into an API Blueprint 1A compliant document. It's available in both Laravel 5.1+ and Lumen 5.1+. By default, output goes to `stdout`, but can be directed to a file using `--output-file`. Configuration defaults can be set for name and version. ```bash $ php artisan api:docs --name Example --use-version v2 ``` ```bash $ php artisan api:docs --name Example --use-version v2 --output-file /path/to/documentation.md ``` -------------------------------- ### API Action Annotations (HTTP Verbs) Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Represents API actions (routable methods) using standard HTTP verbs. Each action requires a URI path. ```APIDOC Action Annotations: @Get(uri: string) @Post(uri: string) @Put(uri: string) @Patch(uri: string) @Delete(uri: string) Description: Defines an API endpoint for a controller method using a specific HTTP verb and URI path. PHPDoc comments can provide short and long descriptions for the action. Parameters: uri: The URI path for the action (e.g., "/"). Example: /** * Show all users * * Get a JSON representation of all the registered users. * * @Get("/") */ public function index() { // ... } ``` -------------------------------- ### Target Specific Domain Source: https://github.com/dingo/api/wiki/Internal-Requests Allows targeting a specific domain for the internal API request. This is useful in multi-domain API setups and is done by chaining the `on` method. ```php $dispatcher->on('api.example.com')->get('users'); ``` -------------------------------- ### API Documentation Generation Command Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Details the Artisan command used to generate API documentation. It requires the documentation name and version as arguments. ```APIDOC Artisan Command: api:docs Description: Generates API documentation based on controller annotations. Arguments: documentation_name: The name for the generated documentation. version: The version of the API documentation to generate. Usage Example: php artisan api:docs MyApi v1 Reference: See https://github.com/dingo/api/wiki/Commands#apidocs for more details. ``` -------------------------------- ### Handle ResponseWasMorphed Event Source: https://github.com/dingo/api/wiki/Responses Provides an example of creating a listener for the `ResponseWasMorphed` event to modify the response headers, such as adding pagination links to the 'Link' header. This allows for custom response manipulation before it's sent. ```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']) ); } } } ``` ```php protected $listen = [ 'Dingo\Api\Event\ResponseWasMorphed' => [ 'App\Listeners\AddPaginationLinksToResponse' ] ]; ``` -------------------------------- ### Configure API Domain Source: https://github.com/dingo/api/wiki/Configuration Sets a domain for the API, such as 'api.myapp.com'. This is an alternative to using a URL prefix. ```env API_DOMAIN=api.myapp.com ``` -------------------------------- ### Creating API Endpoints Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Illustrates how to define API endpoints using HTTP verbs within version groups, including controller routing and resource registration. ```php $api->version('v1', function ($api) { // Define a GET endpoint for users $api->get('users/{id}', 'App\Api\Controllers\UserController@show'); // Define a POST endpoint for users $api->post('users', 'App\Api\Controllers\UserController@store'); // Register a resource controller $api->resource('posts', 'App\Api\Controllers\PostController'); }); // Example of same URI for different versions $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'); }); ``` -------------------------------- ### Publish Configuration File Source: https://github.com/dingo/api/wiki/Configuration Command to publish the Dingo API configuration file for Laravel. This allows for manual configuration outside of .env variables. ```shell php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider" ``` -------------------------------- ### Configure Fractal Adapter in Lumen Source: https://github.com/dingo/api/wiki/Transformers Configure the Fractal adapter for Lumen applications by manually instantiating it in the bootstrap file to customize include key and separator. ```PHP app('DingoApiTransformerFactory')->setAdapter(function ($app) { return new DingoApiTransformerAdapterFractal(new LeagueFractalManager, 'include', ','); }); ``` -------------------------------- ### Apply Middleware to Controller Methods Source: https://github.com/dingo/api/wiki/Authentication Shows how to apply the 'api.auth' middleware to controller methods, either globally within the controller's constructor or selectively to specific methods using '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() { // This method requires authentication. } public function posts() { // This method does not require authentication if 'only' is used above. } } ``` -------------------------------- ### Define API Query Parameters Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Shows how to define query string parameters for API endpoints using Dingo API's `@Parameters` and `@Parameter` annotations. Parameters can be defined at resource or action levels and include descriptions and defaults. ```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() { } ``` ```php /** * @Parameters({ * @Parameter("example", type="integer", required=true, description="This is an example.", default=1) * }) */ public function index() { } ``` -------------------------------- ### Configure API Prefix Source: https://github.com/dingo/api/wiki/Configuration Sets a URL prefix for all API routes, such as 'api'. This is an alternative to using a subdomain. ```env API_PREFIX=api ``` -------------------------------- ### API Resource Annotation Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Defines a resource in the API, specifying its identifier and an optional base URI. Descriptions can be provided before the annotation. ```APIDOC Resource Annotation: @Resource(name: string, uri?: string) Description: Marks a controller as an API resource. The 'name' is the resource identifier, and 'uri' sets the base path for its routes. Parameters: name: The identifier for the resource (e.g., "Users"). uri: (Optional) The base URI for the resource's routes (e.g., "/users"). Example: /** * User resource representation. * * @Resource("Users", uri="/users") */ class UserController extends Controller { // ... } ``` -------------------------------- ### Viewing API Routes in Console Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Provides the Artisan command to list all registered API routes, similar to Laravel's built-in route listing. ```bash $ php artisan api:routes ``` -------------------------------- ### Register Custom Authentication Provider Programmatically Source: https://github.com/dingo/api/wiki/Authentication Demonstrates registering a custom authentication provider dynamically via the application's bootstrap file or service provider using the Dingo API authentication manager. ```php app('Dingo\Api\Auth\Auth')->extend('custom', function ($app) { return new CustomProvider; }); ``` -------------------------------- ### Named Routes and URL Generation Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Explains how to assign names to API routes for easier URL generation and how to generate version-specific URLs. ```php // Naming a route $api->get('users/{id}', ['as' => 'users.index', 'uses' => 'Api\V1\UserController@show']); // Generating a URL to a named route for a specific version $url = app('Dingo\Api\Routing\UrlGenerator')->version('v1')->route('users.index'); // The version must be supplied to ensure the correct route is resolved, // especially when the same name is used across multiple API versions. ``` -------------------------------- ### Configure API Name for Documentation Source: https://github.com/dingo/api/wiki/Configuration Sets the name of your API, primarily used as a default when generating API documentation via commands. ```env API_NAME=My API ``` ```env API_NAME="My API" ``` -------------------------------- ### Configure Default API Version Source: https://github.com/dingo/api/wiki/Configuration Sets the default API version, used as a fallback when no version is specified and for generating API documentation. ```env API_VERSION=v1 ``` -------------------------------- ### Configure API Standards Tree Source: https://github.com/dingo/api/wiki/Configuration Sets the standards tree for API versioning and identification. Options include 'x' (unregistered), 'prs' (personal), and 'vnd' (vendor). 'x' is recommended for general use. ```env API_STANDARDS_TREE=vnd ``` -------------------------------- ### Implement Custom Authentication Provider Source: https://github.com/dingo/api/wiki/Authentication Demonstrates implementing a custom authentication provider by extending the DingoApiContractAuthProvider interface. It includes logic for authentication and throwing an 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.'); } } ``` -------------------------------- ### Use Dingo API Response Builder Source: https://github.com/dingo/api/wiki/Responses Explains how to use the Dingo API Response Builder via the `Dingo\Api\Routing\Helpers` trait. Controllers should extend a base controller that includes this trait to access the `$response` property for fluent response construction. ```php use Dingo\Api\Routing\Helpers; use Illuminate\Routing\Controller; class BaseController extends Controller { use Helpers; } ``` -------------------------------- ### API Version Grouping Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Defines how to create version groups for API routes, allowing for multiple versions or applying group attributes like middleware. ```php $api = app('Dingo\Api\Routing\Router'); // Define a single version group $api->version('v1', function ($api) { // Endpoints for v1 }); // Define a group for multiple versions $api->version(['v1', 'v2'], function ($api) { // Endpoints for v1 and v2 }); // Define a version group with attributes (e.g., middleware) $api->version('v1', ['middleware' => 'foo'], function ($api) { // Endpoints for v1 with 'foo' middleware }); // Nest regular groups within version groups $api->version('v1', function ($api) { $api->group(['middleware' => 'foo'], function ($api) { // Endpoints registered here will have the "foo" middleware applied. }); }); ``` -------------------------------- ### Configure Fractal Adapter with Custom Include Key Source: https://github.com/dingo/api/wiki/Transformers Manually configure the Fractal adapter to customize the include key and separator used for embedding relationships. This is done by instantiating the adapter in a service provider or bootstrap file. ```PHP $this->app['DingoApiTransformerFactory']->setAdapter(function ($app) { return new DingoApiTransformerAdapterFractal(new LeagueFractalManager, 'include', ','); }); ``` -------------------------------- ### Return Eloquent Models Directly Source: https://github.com/dingo/api/wiki/Responses Demonstrates returning Eloquent models or collections directly from a controller. The package automatically formats these as JSON and sets the Content-Type header. Ensure models implement Arrayable or ArrayObject interfaces. ```php class UserController { public function index() { return User::all(); } } class UserController { public function show($id) { return User::findOrFail($id); } } ``` -------------------------------- ### Configure OAuth 2.0 Authentication Source: https://github.com/dingo/api/wiki/Authentication This snippet illustrates the configuration for OAuth 2.0 authentication using the 'lucadegasperi/oauth2-server-laravel' bridge package. It includes setting up user and client resolvers, which are crucial for authenticating users and clients. ```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; }); ``` -------------------------------- ### API Request Annotation Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Defines the request details for an API action, including the body, content type, headers, and an optional identifier for distinguishing multiple requests. ```APIDOC Request Annotation: @Request(body: string|array, contentType?: string, headers?: array, identifier?: string) Description: Specifies the expected request format for an API endpoint. The body can be a string or an array (automatically JSON encoded). Content type and custom headers can also be defined. Parameters: body: The request payload. Can be a URL-encoded string, a JSON-serializable array, or a raw string. contentType: (Optional) The MIME type of the request body (defaults to 'application/json' for arrays). headers: (Optional) An associative array of custom request headers. identifier: (Optional) A string to uniquely identify this request definition, useful for multiple request variations. Examples: // Form URL Encoded Request @Request("username=foo&password=bar", contentType="application/x-www-form-urlencoded") // JSON Request (auto-encoded) @Request({"username": "foo", "password": "bar"}) // JSON Request with custom headers @Request({"username": "foo", "password": "bar"}, headers={"X-Custom": "FooBar"}) // Request with identifier @Request({"username": "foo", "password": "bar"}, identifier="A") ``` -------------------------------- ### API Version Annotation Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Specifies the API versions for which an action is available. This annotation helps in version management during documentation generation. ```APIDOC Version Annotation: @Versions(versions: string[]) Description: Indicates the API versions that a particular action supports. If an action is available across all versions, this annotation can be omitted. Parameters: versions: An array of strings representing the API versions (e.g., ["v1", "v2"]). Example: /** * Show all users * * @Get("/") * @Versions({"v1"}) */ public function index() { // ... } ``` -------------------------------- ### Configure Custom Authentication Provider Source: https://github.com/dingo/api/wiki/Authentication Illustrates how to register a custom authentication provider in the Dingo API configuration file (`config/api.php`) by mapping a key to the provider class. ```php 'auth' => [ 'custom' => 'CustomProvider', ], ``` -------------------------------- ### Protect All Routes in a Version Group Source: https://github.com/dingo/api/wiki/Authentication Shows how to apply the 'api.auth' middleware to all routes within a specific API version group, requiring authentication for every route defined in that group. ```php $api->version('v1', ['middleware' => 'api.auth'], function ($api) { // Routes within this version group will require authentication. }); ``` -------------------------------- ### Protect Specific Routes with Middleware Source: https://github.com/dingo/api/wiki/Authentication Illustrates how to apply the 'api.auth' middleware to individual routes, ensuring only authenticated requests can access them, while other routes remain unprotected. ```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. }); }); ``` -------------------------------- ### Register Custom Request Class Alias Source: https://github.com/dingo/api/wiki/Extending-The-Core Demonstrates how to register your custom request class with the application container using an alias. This is typically done in a service provider's `boot` method to ensure the API package uses your custom implementation. ```php $this->app->alias('MyApp\Request', 'Dingo\Api\Contract\Http\Request'); ``` -------------------------------- ### api:routes Command Source: https://github.com/dingo/api/wiki/Commands Generates a table list of API routes. This command is available in Laravel 5.1+ and behaves similarly to Laravel's `route:list` command. It supports additional filters like `--versions` and `--scopes`. ```bash $ php artisan api:routes ``` ```bash $ php artisan api:routes --versions v1 ``` ```bash $ php artisan api:routes --scopes read_user_data --scopes write_user_data ``` -------------------------------- ### Create Custom API Request Class Source: https://github.com/dingo/api/wiki/Extending-The-Core Shows how to create a custom request class by extending the base `Dingo\Api\Http\Request` class. This allows for adding custom methods or modifying request handling. The custom class should ideally extend the base request class or implement the `Dingo\Api\Contract\Http\Request` interface. ```php namespace MyApp; use Dingo\Api\Http\Request as DingoRequest; class Request extends DingoRequest { public function hasSomething() { return $this->checkSomethingElse(); } } ``` -------------------------------- ### Define API Transactions with Requests and Responses Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Demonstrates how to define API transactions using Dingo API's `@Transaction` annotation. It specifies requests and multiple possible responses, including status codes and response bodies, for a single API endpoint. ```php /** * Register user * * Register a new user with a `username` and `password`. * * @Post("/") * @Versions({"v1"}) * @Transaction({ * @Request({"username": "foo", "password": "bar"}), * @Response(200, body={"id": 10, "username": "foo"}), * @Response(422, body={"error": {"username": {"Username is already taken."}}}) * }) */ public function store() { } ``` -------------------------------- ### Respond With Created Status Source: https://github.com/dingo/api/wiki/Responses Returns a 201 Created response. Optionally, a location header can be provided to specify the URI of the newly created resource. ```php return $this->response->created(); // With location return $this->response->created($location); ``` -------------------------------- ### Custom Throttle Configuration Source: https://github.com/dingo/api/wiki/Rate-Limiting Configure custom throttles either by registering them in the configuration file under the 'throttling' key or by extending the rate limiting handler directly 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 API Subtype Source: https://github.com/dingo/api/wiki/Configuration Defines a short, lowercase name for your application or project, used as part of the API's subtype identifier. ```env API_SUBTYPE=myapp ``` -------------------------------- ### Respond With Collection Source: https://github.com/dingo/api/wiki/Responses Creates a response for a collection of resources. It accepts a collection of items and a transformer to format each item in the collection. Ideal for listing multiple records. ```php class UserController extends BaseController { public function index() { $users = User::all(); return $this->response->collection($users, new UserTransformer); } } ``` -------------------------------- ### API Request Accept Header Format Source: https://github.com/dingo/api/wiki/Making-Requests-To-Your-API Specifies the required 'Accept' header format for requesting a specific API version. It includes a custom subtype and version number, allowing for content negotiation. ```text Accept: application/vnd.YOUR_SUBTYPE.v1+json ``` -------------------------------- ### Configure Response Transformer Adapter Source: https://github.com/dingo/api/wiki/Configuration Configures the response transformer adapter, setting the Fractal manager and serializer for transforming API responses. ```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); }); ``` -------------------------------- ### Configure Strict Mode Source: https://github.com/dingo/api/wiki/Configuration Enables strict mode, requiring clients to send the 'Accept' header. If enabled and an invalid header is used, a BadRequestHttpException is thrown. ```env API_STRICT=false ``` -------------------------------- ### Configure JWT Authentication Source: https://github.com/dingo/api/wiki/Authentication This section demonstrates how to configure JSON Web Token (JWT) authentication for Dingo API. It involves using the 'tymon/jwt-auth' package and registering the JWT provider. Configuration can be done in the API config file or a service 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']); }); ``` -------------------------------- ### api:cache Command Source: https://github.com/dingo/api/wiki/Commands Caches API routes alongside the main application routes. This command automatically executes the `route:cache` command. Routes must be in `app/Http/routes.php` or included within it for caching to apply. Running `route:cache` alone will make API routes inaccessible. ```bash $ php artisan api:cache ``` -------------------------------- ### Symfony HTTP Exception Mapping Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses A reference table mapping common Symfony HTTP exception classes to their corresponding HTTP status codes, useful for understanding automatic error handling. ```APIDOC SymfonyHttpExceptions: Description: Built-in Symfony exceptions that can be thrown to automatically handle API error responses. Exceptions: Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: StatusCode: 403 Description: Indicates that the authenticated user lacks the necessary permissions. Symfony\Component\HttpKernel\Exception\BadRequestHttpException: StatusCode: 400 Description: Represents a generic bad request error. Symfony\Component\HttpKernel\Exception\ConflictHttpException: StatusCode: 409 Description: Used when the request conflicts with the current state of the resource (e.g., concurrent modification). Symfony\Component\HttpKernel\Exception\GoneHttpException: StatusCode: 410 Description: Indicates that the requested resource is no longer available and will not be available again. Symfony\Component\HttpKernel\Exception\HttpException: StatusCode: 500 Description: A generic HTTP exception, often used as a base class or for server errors. Symfony\Component\HttpKernel\Exception\LengthRequiredHttpException: StatusCode: 411 Description: The server refuses to accept the request without a defined Content-Length. Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: StatusCode: 405 Description: The HTTP method used in the request is not allowed for the target resource. Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException: StatusCode: 406 Description: The server cannot produce a response matching the list of acceptable values defined in the request's proactive negotiation headers. Symfony\Component\HttpKernel\Exception\NotFoundHttpException: StatusCode: 404 Description: The requested resource could not be found on the server. Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException: StatusCode: 412 Description: The precondition given in one or more of the request header fields evaluated to false when it is tested on the server. Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException: StatusCode: 428 Description: The server requires the request to be conditional. Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException: StatusCode: 503 Description: The server is currently unable to handle the request due to a temporary overload or maintenance. Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException: StatusCode: 429 Description: The user has sent too many requests in a given amount of time. Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException: StatusCode: 401 Description: The request requires user authentication. Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException: StatusCode: 415 Description: The server does not support the media format of the request payload. ``` -------------------------------- ### Instantiate Dingo API Dispatcher Source: https://github.com/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. ```php $dispatcher = app('Dingo\Api\Dispatcher'); ``` -------------------------------- ### Symfony HTTP Exceptions for API Errors Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses Demonstrates throwing a Symfony HttpException subclass to automatically generate API error responses with appropriate status codes. The package catches these exceptions and formats them into JSON. ```php $api->version('v1', function ($api) { $api->put('user/{id}', function ($id) { $user = User::find($id); if ($user->updated_at > app('request')->get('last_updated')) { throw new Symfony\Component\HttpKernel\Exception\ConflictHttpException('User was updated prior to your request.'); } // No error, we can continue to update the user as per usual. }); }); ``` ```json { "message": "User was updated prior to your request.", "status_code": 409 } ``` -------------------------------- ### Response Builder: Collection with Callback Source: https://github.com/dingo/api/wiki/Transformers Utilize the response builder's 'collection' method with a callback to perform advanced operations on the Fractal resource, such as setting cursors for pagination. ```PHP return $this->collection($users, new UserTransformer, [], function ($resource, $fractal) { $resource->setCursor($cursor); }); ``` -------------------------------- ### Allow Specific Authentication Providers for Routes Source: https://github.com/dingo/api/wiki/Authentication Demonstrates how to restrict access to a route or group of routes to only specific authentication providers by using the 'providers' key in the route definition. ```php $api->version('v1', function ($api) { $api->get('user', ['middleware' => 'api.auth', 'providers' => ['basic', 'oauth'], function () { // This route requires authentication and only allows 'basic' or 'oauth' providers. }]); }); ``` -------------------------------- ### Extend Authorization Provider for Header Authentication Source: https://github.com/dingo/api/wiki/Authentication Shows how to extend the DingoApiAuthProviderAuthorization abstract class for providers using the Authorization header. It utilizes validateAuthorizationHeader and defines 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'; } } ``` -------------------------------- ### Custom Throttle Implementation Source: https://github.com/dingo/api/wiki/Rate-Limiting Create custom rate limiting logic by extending the abstract 'Throttle' class and implementing the 'match' method. The 'match' method should return true if the throttle conditions are met, allowing for complex matching scenarios. ```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. } } ``` -------------------------------- ### Respond With Array Source: https://github.com/dingo/api/wiki/Responses Shows how to return a plain array response using the response builder. This method can optionally accept a transformer to format the array data before serialization. ```php class UserController extends BaseController { public function show($id) { $user = User::findOrFail($id); return $this->response->array($user->toArray()); } } class UserController extends BaseController { public function show($id) { $setOfThings = [ 'a' => 1, 'b' => 2 ]; return $this->response->array($setOfThings, new ArbitraryTransformer); } } ``` -------------------------------- ### Force HTTPS Url Generation Source: https://github.com/dingo/api/wiki/Misc This snippet demonstrates how to force Dingo API to generate URLs using the HTTPS scheme. It should be placed at the bottom of the map function within your `RouteServiceProvider.php` file. This ensures all generated API URLs use HTTPS. ```PHP app('Dingo\Api\Routing\UrlGenerator')->forceScheme('https'); ``` -------------------------------- ### Retrieve Authenticated User via Controller Trait Source: https://github.com/dingo/api/wiki/Authentication Shows how to access the authenticated user instance directly as a property (`$this->auth->user()`) within controllers that use the DingoApiRoutingHelpers trait. ```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; } } ``` -------------------------------- ### Bind ScopeFactoryInterface in AppServiceProvider Source: https://github.com/dingo/api/wiki/Known-Issues This code snippet resolves an instantiation error in Dingo API where the League Fractal ScopeFactoryInterface is not recognized. It involves binding the interface to its concrete implementation within the register() method of your AppServiceProvider. This ensures that the necessary components for Dingo API's transformer adapter can be correctly instantiated. ```php public function register() { $this->app->bind("League\\Fractal\\ScopeFactoryInterface", "\\League\\Fractal\\ScopeFactory"); // } ``` -------------------------------- ### Enable Debug Mode (.env) Source: https://github.com/dingo/api/wiki/Configuration Control the inclusion of detailed stack trace information in generic error responses by setting the API_DEBUG variable in your .env file. When enabled, the 'debug' key in error responses will be populated with relevant debugging details. ```.env API_DEBUG=true ``` -------------------------------- ### Configure Default Response Format (.env) Source: https://github.com/dingo/api/wiki/Configuration Set the default response format for API requests by defining the API_DEFAULT_FORMAT variable in your .env file. This ensures consistent data output. ```.env API_DEFAULT_FORMAT=json ``` -------------------------------- ### Retrieve Authenticated User via Auth Manager Source: https://github.com/dingo/api/wiki/Authentication Demonstrates how to retrieve the currently authenticated user instance from within a protected API endpoint using the Dingo API's authentication manager. ```php $api->version('v1', ['middleware' => 'api.auth'], function ($api) { $api->get('user', function () { $user = app('Dingo\Api\Auth\Auth')->user(); return $user; }); }); ``` -------------------------------- ### Response Builder: Collection with Serializer Callback Source: https://github.com/dingo/api/wiki/Transformers Return a collection using the response builder and a callback to dynamically set a custom serializer for the Fractal manager. ```PHP return $this->collection($users, new UserTransformer, function ($resource, $fractal) { $fractal->setSerializer(new CustomSerializer); }); ``` -------------------------------- ### Pretend Authenticated User Source: https://github.com/dingo/api/wiki/Internal-Requests Shows how to authenticate internal requests as a specific user, useful for testing protected endpoints. The `be` method authenticates for subsequent requests, while `once` authenticates for a single request. ```php $dispatcher->be(auth()->user())->get('posts'); ``` ```php $dispatcher->be(auth()->user())->once()->get('posts'); ```