Dingo API

repository·master·Indexed 43 days ago

https://github.com/api-ecosystem-for-laravel/dingo-api

A toolkit for Laravel developers to build professional APIs with built-in support for versioning, authentication, rate limiting, content negotiation, and internal requests via the Dispatcher. Includes CLI tools like api:cache, api:docs, and api:routes for route management and documentation generation.

Tokens
8.1K
Snippets
32
Records
40
Agent score
52%

What's inside Dingo API

  1. Overview of Dingo API features

    master

    The Dingo API package provides a suite of tools for building robust APIs in Laravel. Key features include:

    • Content Negotiation: Handle different response formats.
    • Authentication: Support for multiple authentication adapters.
    • Versioning: Manage multiple API versions.
    • Rate Limiting: Control request frequency.
    • Transformers & Formatters: Transform and format API responses.
    • Error Handling: Standardized error and exception handling.
    • Internal Requests: Ability to make requests within the application.
    • Documentation: Support for API Blueprint documentation.
  2. Migrate from dingo/api to api-ecosystem-for-laravel/dingo-api

    master

    This repository is an official fork of the original dingo/api package. To migrate, you only need to update your composer.json file. All namespaces and project aspects remain identical, ensuring a seamless transition.

    Note: Lumen support is not actively maintained. It is recommended to migrate to Laravel if you are currently using Lumen.

    composer remove dingo/api
    composer require api-ecosystem-for-laravel/dingo-api
  3. Configure OAuth 2.0 scopes for routes

    master

    You can restrict access to specific routes using OAuth 2.0 scopes. Use the scopes key in the route action to define the required scopes.

    If the controller uses the Dingo\Api\Helpers\Helpers trait, you can also define scopes via controller methods (e.g., getScopes()). The route will merge these properties. You can further refine scope application using only or except filters within the scope definition to target specific controller methods.

  4. Configure rate limiting and throttling

    master

    Dingo API provides mechanisms to limit request rates on a per-route basis. You can configure this using the following keys in the route action:

    • limit: The maximum number of requests allowed.
    • expires: The duration (in minutes) before the limit resets.
    • throttle: A specific throttle class or instance.

    If the controller uses the Dingo\Api\Helpers\Helpers trait, you can also define these via controller methods like getRateLimit(), getThrottles(), etc. Throttles defined via the throttle key take precedence over standard rate limits.

  5. Configure API route properties

    master

    When defining routes in Dingo API, you can pass specific keys within the route action array to configure API-specific behaviors. These properties can be set directly in the route definition or via the controller if the controller uses the Dingo\Api\Helpers\Helpers trait.

    Available action keys:

    • version: An array of API versions this route responds to.
    • conditionalRequest: Boolean indicating if the request is conditional (defaults to true).
    • middleware: Array of middleware to apply.
    • throttle: A throttle instance or a string representing the throttle class.
    • scopes: Array of OAuth 2.0 scopes required for the route.
    • providers: Array of authentication providers.
    • limit: The rate limit integer.
    • expires: The rate limit expiration time.
    • scopeStrict: Boolean determining if the route requires all scopes or just any valid scope.
  6. Handle API authorization in FormRequest

    master

    The authorize() method in a FormRequest determines if the current user is permitted to perform the requested action.

    • If authorize() returns true, validation proceeds.
    • If authorize() returns false, a Dingo\Api\Exception\AccessDeniedHttpException is thrown.

    This is useful for checking ownership or specific permissions before even checking if the input data is valid.

    public function authorize()
    {
        // Example: Only allow the owner of a post to update it
        return $this->user()->can('update', $this->route('post'));
    }
  7. Implement custom API request validation with FormRequest

    master

    To handle request validation in your API, extend Dingo\Api\Http\FormRequest. This class automates the validation process and ensures that if validation fails, a ValidationHttpException is thrown, which the Dingo API layer converts into a proper JSON error response.

    To use it, implement the following methods in your subclass:

    1. rules(): Return an array of validation rules.
    2. authorize(): Return true to allow the request or false to deny it (throws AccessDeniedHttpException).
    3. messages() (optional): Return an array of custom error messages.
    4. attributes() (optional): Return an array of custom attribute names for error messages.
    namespace App\Http\Requests;
    
    use Dingo\Api\Http\FormRequest;
    
    class StoreUserRequest extends FormRequest
    {
        public function authorize()
        {
            return true;
        }
    
        public function rules()
        {
            return [
                'email' => 'required|email|unique:users',
                'password' => 'required|min:8',
            ];
        }
    
        public function messages()
        {
            return [
                'email.required' => 'We need to know your email address.',
            ];
        }
    }
  8. Configure Formatter Options

    master

    You can define specific options for different response formats globally.

    • setFormatsOptions(array $formatsOptions): Sets an associative array where keys are format names and values are their respective option arrays.
    • getFormatsOptions($format): Retrieves the options for a specific format.
    • hasOptionsForFormat($format): Checks if options have been defined for a format.
    use Dingo\Api\Http\Response;
    
    Response::setFormatsOptions([
        'json' => ['indent' => 4, 'encode_ascii' => true],
        'xml'  => ['version' => '1.0'],
    ]);
  9. Customize FormRequest validation rules and messages

    master

    When extending Dingo\Api\Http\FormRequest, you can override several methods to customize how data is validated and how errors are presented:

    • rules(): Defines the validation logic.
    • messages(): Returns an associative array of custom error messages (e.g., ['field.rule' => 'Custom message']).
    • attributes(): Returns an associative array of custom attribute names (e.g., ['email' => 'email address']) to make error messages more readable.
    • validationData(): Overriding this allows you to change the data source being validated (defaults to $this->all()).
    public function rules()
    {
        return ['username' => 'required'];
    }
    
    public function messages()
    {
        return ['username.required' => 'Please provide a username.'];
    }
    
    public function attributes()
    {
        return ['username' => 'user handle'];
    }