### Install project dependencies Source: https://github.com/dingo/api/blob/master/CONTRIBUTING.md Use Composer to install the necessary project dependencies before running tests. ```bash $ composer install ``` -------------------------------- ### Make API Request with cURL Source: https://github.com/dingo/api/wiki/Making-Requests-To-Your-API Example of using cURL to perform a request with the required Accept header. ```bash $ curl -v -H "Accept: application/vnd.YOUR_SUBTYPE.v1+json" http://example.app/users ``` -------------------------------- ### Configure JWT Authentication Provider Source: https://github.com/dingo/api/wiki/Authentication Configuration examples for integrating JWT authentication via the config file or 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']); }); ``` -------------------------------- ### Define Request Annotations Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Use @Request to define example request bodies, content types, headers, and identifiers. ```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"}) */ 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() { } ``` -------------------------------- ### Custom Exception JSON Response Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses Example of the JSON output returned by the custom exception handler. ```json { "error": "Hey, what do you think you are doing!?" } ``` -------------------------------- ### Returning an Error Response in an Endpoint Source: https://github.com/dingo/api/wiki/Internal-Requests Example of an endpoint using the response builder to trigger an error. ```php public function show($id) { return $this->response->errorNotFound('Could not find the user.'); } ``` -------------------------------- ### Throwing a Conflict Exception in an Endpoint Source: https://github.com/dingo/api/wiki/Internal-Requests Example of an endpoint throwing a ConflictHttpException that must be caught by the internal dispatcher. ```php public function store() { throw new Symfony\\\Component\\\HttpKernel\\\Exception\\\ConflictHttpException('We got a conflict!'); } ``` -------------------------------- ### Generate API documentation Source: https://github.com/dingo/api/wiki/Commands Generates API Blueprint documentation from annotated controllers. Output defaults to stdout unless an output file is specified. ```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 ``` -------------------------------- ### Initialize API Router Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Retrieve an instance of the Dingo API router to begin defining endpoints. ```php $api = app('Dingo\Api\Routing\Router'); ``` -------------------------------- ### Configure API Prefix and Domain Source: https://github.com/dingo/api/wiki/Configuration Set the API prefix or domain in the .env file. ```text API_PREFIX=api ``` ```text API_DOMAIN=api.myapp.com ``` -------------------------------- ### View Routes via Artisan Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints List all registered API routes using the Artisan command line interface. ```bash $ php artisan api:routes ``` -------------------------------- ### Execute test suite Source: https://github.com/dingo/api/blob/master/CONTRIBUTING.md Run the PHPUnit test suite to verify the local environment. ```bash $ vendor/bin/phpunit ``` -------------------------------- ### Respond with No Content Source: https://github.com/dingo/api/wiki/Responses Return an empty response. ```php return $this->response->noContent(); ``` -------------------------------- ### Configure API Name Source: https://github.com/dingo/api/wiki/Configuration Set the API name for documentation generation in the .env file. ```text API_NAME=My API ``` ```text API_NAME="My API" ``` -------------------------------- ### Implement a Custom Authentication Provider Source: https://github.com/dingo/api/wiki/Authentication Create a custom provider by implementing the Dingo\Api\Contract\Auth\Provider interface. Throw an UnauthorizedHttpException if authentication fails. ```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.'); } } ``` -------------------------------- ### Describe Controller Actions Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Document controller methods using PHPDoc descriptions and HTTP verb annotations. ```php /** * Show all users * * Get a JSON representation of all the registered users. */ public function index() { } ``` ```php /** * Show all users * * Get a JSON representation of all the registered users. * * @Get("/") */ public function index() { } ``` -------------------------------- ### Configure Strict Mode Source: https://github.com/dingo/api/wiki/Configuration Enable or disable strict mode in the .env file. ```text API_STRICT=false ``` -------------------------------- ### Configure API Version Source: https://github.com/dingo/api/wiki/Configuration Set the default API version in the .env file. ```text API_VERSION=v1 ``` -------------------------------- ### Initialize API Dispatcher Source: https://github.com/dingo/api/wiki/Internal-Requests Obtain an instance of the Dingo API dispatcher from the application container. ```php $dispatcher = app('Dingo\Api\Dispatcher'); ``` -------------------------------- ### Publish Laravel Configuration Source: https://github.com/dingo/api/wiki/Installation Use the Artisan command to publish the configuration file for customization. ```bash php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider" ``` -------------------------------- ### Configure Base Controller for Dingo API Source: https://github.com/dingo/api/wiki/Responses Implement the Helpers trait in a base controller to enable the $response property in child controllers. ```php use Dingo\Api\Routing\Helpers; use Illuminate\Routing\Controller; class BaseController extends Controller { use Helpers; } ``` -------------------------------- ### List API routes Source: https://github.com/dingo/api/wiki/Commands Generates a table of API routes with optional filtering by version or scope. ```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 ``` -------------------------------- ### Configure API Standards Tree Source: https://github.com/dingo/api/wiki/Configuration Set the standards tree in the .env file. ```text API_STANDARDS_TREE=vnd ``` -------------------------------- ### Configure Default Response Format Source: https://github.com/dingo/api/wiki/Configuration Set the default API response format using environment variables. ```text API_DEFAULT_FORMAT=json ``` -------------------------------- ### Configure API Subtype Source: https://github.com/dingo/api/wiki/Configuration Set the application subtype in the .env file. ```text API_SUBTYPE=myapp ``` -------------------------------- ### Configure Fractal Adapter Source: https://github.com/dingo/api/wiki/Transformers Manually configures the Fractal adapter to customize the include key and separator, typically performed in a service provider or bootstrap file. ```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', ','); }); ``` -------------------------------- ### Define API Parameters with PHP Annotations Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Use the @Parameters annotation to document URI query string parameters, including descriptions and default values. ```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() { } ``` -------------------------------- ### Throwing a StoreResourceFailedException Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses Demonstrates throwing a StoreResourceFailedException when validation fails during user creation. ```php $api->version('v1', function ($api) { $api->post('users', function () { $rules = [ 'username' => ['required', 'alpha'], 'password' => ['required', 'min:7'] ]; $payload = app('request')->only('username', 'password'); $validator = app('validator')->make($payload, $rules); if ($validator->fails()) { throw new Dingo\Api\Exception\StoreResourceFailedException('Could not create new user.', $validator->errors()); } // Create user as per usual. }); }); ``` -------------------------------- ### Respond with Created Response Source: https://github.com/dingo/api/wiki/Responses Return a 201 Created response, optionally specifying a location header. ```php return $this->response->created(); ``` ```php return $this->response->created($location); ``` -------------------------------- ### Implement a custom throttle class Source: https://github.com/dingo/api/wiki/Rate-Limiting Defines a custom throttle by extending the base Throttle class and implementing the match method. ```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. } } ``` -------------------------------- ### Name Routes and Generate URLs Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Assign names to routes for easy URL generation, requiring a version specification. ```php $api->get('users/{id}', ['as' => 'users.index', 'uses' => 'Api\V1\UserController@show']); ``` ```php app('Dingo\Api\Routing\UrlGenerator')->version('v1')->route('users.index'); ``` -------------------------------- ### Implement a Custom Transformer Adapter Source: https://github.com/dingo/api/wiki/Transformers Create a class implementing the Adapter interface to define custom transformation logic. The transform method must return an array containing the transformed response. ```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. } } ``` -------------------------------- ### Configure Conditional Requests Source: https://github.com/dingo/api/wiki/Configuration Enable or disable conditional requests in the .env file. ```text API_CONDITIONAL_REQUEST=false ``` -------------------------------- ### Implement a custom request class Source: https://github.com/dingo/api/wiki/Extending-The-Core Create a custom request class by extending the base Dingo request class to add custom functionality. ```php namespace MyApp; use Dingo\/Api\Http\Request as DingoRequest; class Request extends DingoRequest { public function hasSomething() { return $this->checkSomethingElse(); } } ``` -------------------------------- ### Respond with a Collection Source: https://github.com/dingo/api/wiki/Responses Return a collection of items using a transformer. ```php class UserController extends BaseController { public function index() { $users = User::all(); return $this->response->collection($users, new UserTransformer); } } ``` -------------------------------- ### Utilize Fractal Callbacks Source: https://github.com/dingo/api/wiki/Transformers Executes a callback after resource creation to perform complex operations like setting cursors or custom serializers. ```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); }); ``` -------------------------------- ### Respond with an Array Source: https://github.com/dingo/api/wiki/Responses Return an array response, optionally including a transformer. ```php class UserController extends BaseController { public function show($id) { $user = User::findOrFail($id); return $this->response->array($user->toArray()); } } ``` ```php class UserController extends BaseController { public function show($id) { $setOfThings = [ 'a' => 1, 'b' => 2 ]; return $this->response->array($setOfThings, new ArbitraryTransformer); } } ``` -------------------------------- ### Return Eloquent Collection as JSON Source: https://github.com/dingo/api/wiki/Responses Returning a collection directly from a controller method allows the package to automatically format it as JSON. ```php class UserController { public function index() { return User::all(); } } ``` -------------------------------- ### Response Builder Methods Source: https://github.com/dingo/api/wiki/Responses Methods available via the $response property in controllers using the Dingo\Api\Routing\Helpers trait. ```APIDOC ## Response Builder Methods ### array($array, $transformer = null) Returns an array response, optionally using a transformer. ### item($item, $transformer) Returns a single item response using a transformer. ### collection($collection, $transformer) Returns a collection of items using a transformer. ### paginator($paginator, $transformer) Returns a paginated collection of items using a transformer. ### noContent() Returns a 204 No Content response. ### created($location = null) Returns a 201 Created response, optionally with a location header. ### error($message, $statusCode) Returns a generic error response with a custom message and status code. ### errorNotFound($message = null) Returns a 404 Not Found error. ### errorBadRequest($message = null) Returns a 400 Bad Request error. ### errorForbidden($message = null) Returns a 403 Forbidden error. ### errorInternal($message = null) Returns a 500 Internal Server Error. ### errorUnauthorized($message = null) Returns a 401 Unauthorized error. ### withHeader($key, $value) Adds an additional header to the response. ### addMeta($key, $value) Adds a single piece of meta data to the response. ### setMeta(array $meta) Sets an array of meta data for the response. ### setStatusCode($code) Sets the HTTP status code for the response. ``` -------------------------------- ### Register a custom throttle Source: https://github.com/dingo/api/wiki/Rate-Limiting Configures or registers a custom throttle instance with specific limits and expiration settings. ```php 'throttling' => [ 'custom' => new CustomThrottle(['limit' => 200, 'expires' => 10]) ] ``` ```php app('Dingo\Api\Http\RateLimit\Handler')->extend(new CustomThrottle(['limit' => 200, 'expires' => 10])); ``` -------------------------------- ### Throwing a ConflictHttpException Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses Demonstrates throwing a ConflictHttpException when a resource update conflict is detected. ```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. }); }); ``` -------------------------------- ### Add Meta Data Source: https://github.com/dingo/api/wiki/Responses Attach meta data to a resource response. ```php return $this->response->item($user, new UserTransformer)->addMeta('foo', 'bar'); ``` ```php return $this->response->item($user, new UserTransformer)->setMeta($meta); ``` -------------------------------- ### Catching Exceptions from Internal Requests Source: https://github.com/dingo/api/wiki/Internal-Requests Demonstrates wrapping an internal dispatch call in a try-catch block to handle specific HTTP exceptions. ```php try { app('Dingo\\\Api\\\Dispatcher')->with($payload)->post('users'); } catch (Symfony\\\Component\\\HttpKernel\\\Exception\\\ConflictHttpException $e) { // Do something here, like return with an error. } ``` -------------------------------- ### Register API Endpoints Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Define routes within a version group closure using the $api instance. ```php $api->version('v1', function ($api) { $api->get('users/{id}', 'App\Api\Controllers\UserController@show'); }); ``` -------------------------------- ### Target API Version and Domain Source: https://github.com/dingo/api/wiki/Internal-Requests Specify the API version or domain for internal requests. ```php $dispatcher->version('v2')->get('users'); ``` ```php $dispatcher->on('api.example.com')->get('users'); ``` -------------------------------- ### Extend Rate Limiting Source: https://github.com/dingo/api/wiki/Configuration Register a custom throttle in a service provider or bootstrap file. ```php $app['Dingo\Api\Http\RateLimit\Handler']->extend(function ($app) { return new Dingo\Api\Http\RateLimit\Throttle\Authenticated; }); ``` -------------------------------- ### Enable rate limiting on all routes Source: https://github.com/dingo/api/wiki/Rate-Limiting Applies the api.throttle middleware to an entire version group. ```php $api->version('v1', ['middleware' => 'api.throttle'], function ($api) { // Routes within this version group will require authentication. }); ``` -------------------------------- ### Implement ResponseWasMorphed Listener Source: https://github.com/dingo/api/wiki/Responses Create a listener to intercept the response after it has been morphed, allowing for header manipulation such as adding pagination links. ```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']) ); } } } ``` -------------------------------- ### Register Custom Authentication Provider Source: https://github.com/dingo/api/wiki/Authentication Register the provider in the configuration file or via the application bootstrap/service provider. ```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/dingo/api/wiki/Installation Register the Dingo API service provider in the bootstrap/app.php file for Lumen projects. ```php $app->register(Dingo\Api\Provider\LumenServiceProvider::class); ``` -------------------------------- ### Apply Controller Scopes Source: https://github.com/dingo/api/wiki/OAuth-2.0 Use the Dingo\Api\Routing\Helpers trait in a controller to enforce scopes on all methods or specific subsets of methods. ```php use Dingo\Api\Routing\Helpers; class UserController extends Controller { use Helpers; public function __construct() { $this->scopes('read_user_data'); } } ``` ```php use Dingo\Api\Routing\Helpers; class UserController extends Controller { use Helpers; public function __construct() { // Only apply to the index method. $this->scopes('read_user_data', 'index'); // Apply to every method except the store method. $this->scopes('read_user_data', ['except' => 'store']); // Apply only to the store method. $this->scopes('write_user_data', ['only' => ['store']]); } public function index() { // } public function store() { // } } ``` -------------------------------- ### Configure route-specific throttling limits Source: https://github.com/dingo/api/wiki/Rate-Limiting Sets custom request limits and expiration times for specific routes or groups. ```php $api->version('v1', function ($api) { $api->get('users', ['middleware' => 'api.throttle', 'limit' => 100, 'expires' => 5, function () { return User::all(); }]); }); ``` ```php $api->version('v1', ['middleware' => 'api.throttle', 'limit' => 100, 'expires' => 5], function ($api) { $api->get('users', function () { return User::all(); }); $api->get('posts', function () { return Post::all(); }); }); ``` -------------------------------- ### Simulate Authenticated User Source: https://github.com/dingo/api/wiki/Internal-Requests Pretend to be a specific user for internal requests, either globally or for a single request. ```php $dispatcher->be(auth()->user())->get('posts'); ``` ```php $dispatcher->be(auth()->user())->once()->get('posts'); ``` -------------------------------- ### Retrieve Raw Response Object Source: https://github.com/dingo/api/wiki/Internal-Requests Prefix calls with raw() to receive the raw response object instead of transformed data. ```php $response = $dispatcher->raw()->get('users'); ``` -------------------------------- ### Define Response Annotations Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Use @Response to define the expected status code and body for an action. ```php /** * Register user * * Register a new user with a `username` and `password`. * * @Post("/") * @Versions({"v1"}) * @Request({"username": "foo", "password": "bar"}) * @Response(200, body={"id": 10, "username": "foo"}) */ public function store() { } ``` -------------------------------- ### Extend Authentication Providers Source: https://github.com/dingo/api/wiki/Configuration Register a custom authentication provider in a service provider or bootstrap file. ```php $app['Dingo\Api\Auth\Auth']->extend('oauth', function ($app) { return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']); }); ``` -------------------------------- ### Register JSONP Response Formatter Source: https://github.com/dingo/api/wiki/Responses Register the JSONP formatter via configuration or the bootstrap file to enable callback wrapping. ```php 'formats' => [ 'json' => 'Dingo\Api\Http\Response\Format\Jsonp' ] ``` ```php Dingo\Api\Http\Response::addFormatter('json', new Dingo\Api\Http\Response\Format\Jsonp); ``` -------------------------------- ### Perform Internal Requests via Helpers Trait Source: https://github.com/dingo/api/wiki/Internal-Requests Use the $api property in controllers that implement the Dingo Helpers trait. ```php use Dingo\Api\Routing\Helpers; class HomeController extends Controller { use Helpers; public function index() { $users = $this->api->get('users'); return view('index')->with('users', $users); } } ``` -------------------------------- ### Respond with a Single Item Source: https://github.com/dingo/api/wiki/Responses Return a single resource item using a transformer. ```php class UserController extends BaseController { public function show($id) { $user = User::findOrFail($id); return $this->response->item($user, new UserTransformer); } } ``` -------------------------------- ### Attach Files to Internal Requests Source: https://github.com/dingo/api/wiki/Internal-Requests Attach files using UploadedFile instances, file paths, or paths with metadata. ```php $dispatcher->attach(Input::files())->post('photos'); ``` ```php $dispatcher->attach(['photo' => 'photos/me.jpg'])->post('photos'); ``` ```php $dispatcher->attach([ 'photo' => [ 'path' => 'photos/me.jpg', 'mime' => 'image/jpeg', 'size' => '49430' ] ])->post('photos'); ``` -------------------------------- ### Generic Resource Exceptions Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses List of available resource exceptions that return an HTTP 422 status code. ```php Dingo\Api\Exception\DeleteResourceFailedException Dingo\Api\Exception\ResourceException Dingo\Api\Exception\StoreResourceFailedException Dingo\Api\Exception\UpdateResourceFailedException ``` -------------------------------- ### Enable API Debug Mode Source: https://github.com/dingo/api/wiki/Configuration Toggle debug mode to include stack trace details in error responses. ```text API_DEBUG=true ``` -------------------------------- ### Define a Resource Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Use the @Resource annotation to identify a controller as an API resource. ```php /** * @Resource("Users") */ class UserController extends Controller { } ``` ```php /** * @Resource("Users", uri="/users") */ class UserController extends Controller { } ``` ```php /** * User resource representation. * * @Resource("Users", uri="/users") */ class UserController extends Controller { } ``` -------------------------------- ### Set Resource Key in Response Builder Source: https://github.com/dingo/api/wiki/Transformers Provides a resource key when returning an item through the response builder. ```php return $this->item($user, new UserTransformer, ['key' => 'user']); ``` -------------------------------- ### Register a custom request class alias Source: https://github.com/dingo/api/wiki/Extending-The-Core Use the application container to alias your custom request class to the Dingo request contract. ```php $this->app->alias('MyApp\Request', 'Dingo\Api\Contract\Http\Request'); ``` -------------------------------- ### Respond with Paginated Items Source: https://github.com/dingo/api/wiki/Responses Return a paginated collection of items using a transformer. ```php class UserController extends BaseController { public function index() { $users = User::paginate(25); return $this->response->paginator($users, new UserTransformer); } } ``` -------------------------------- ### Perform Internal Requests via Dispatcher Source: https://github.com/dingo/api/wiki/Internal-Requests Execute internal requests using standard HTTP verbs within a route definition. ```php Route::get('/', function () use ($dispatcher) { $users = $dispatcher->get('api/users'); return View::make('index')->with('users', $users); }); ``` -------------------------------- ### Versioned Endpoint Overrides Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Define the same URI for different versions to handle API changes. ```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'); }); ``` -------------------------------- ### Register a custom rate limiter resolver Source: https://github.com/dingo/api/wiki/Rate-Limiting Overrides the default IP-based rate limiting by registering a custom resolver that returns a unique string key. ```php app('Dingo\Api\Http\RateLimit\Handler')->setRateLimiter(function ($app, $request) { return $app['example']->getRateLimiterKey(); }); ``` -------------------------------- ### Add Dingo API to composer.json Source: https://github.com/dingo/api/wiki/Installation Include the package in your project dependencies by updating the composer.json file. ```json "require": { "dingo/api": "^3.0.0" } ``` -------------------------------- ### Configure Response Transformer Source: https://github.com/dingo/api/wiki/Configuration Set a custom response transformer adapter in a service provider or bootstrap file. ```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); }); ``` -------------------------------- ### Define Accept Header Source: https://github.com/dingo/api/wiki/Making-Requests-To-Your-API The required format for the Accept header to specify API version and subtype. ```http Accept: application/vnd.YOUR_SUBTYPE.v1+json ``` -------------------------------- ### Define Version Groups Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Create versioned route groups to manage API evolution. Supports single versions, multiple versions, and group attributes. ```php $api->version('v1', function ($api) { }); ``` ```php $api->version(['v1', 'v2'], function ($api) { }); ``` ```php $api->version('v1', ['middleware' => 'foo'], function ($api) { }); ``` -------------------------------- ### Register Response Formatter Source: https://github.com/dingo/api/wiki/Configuration Register a custom response formatter in a service provider or bootstrap file. ```php Dingo\Api\Http\Response::addFormatter('json', new Dingo\Api\Http\Response\Format\Jsonp); ``` -------------------------------- ### Send Data with Internal Requests Source: https://github.com/dingo/api/wiki/Internal-Requests Pass data to internal requests using the with() method or as the second parameter of the HTTP verb method. ```php $dispatcher->with(['name' => 'Jason', 'location' => 'Australia'])->post('users'); ``` ```php $dispatcher->post('users', ['name' => 'Jason', 'location' => 'Australia']); ``` -------------------------------- ### Bind ScopeFactoryInterface in AppServiceProvider Source: https://github.com/dingo/api/wiki/Known-Issues Resolves the 'not instantiable' error by explicitly binding the Fractal ScopeFactoryInterface in the service provider. ```php public function register() { $this->app->bind("League\\Fractal\\ScopeFactoryInterface", "\\League\\Fractal\\ScopeFactory"); // } ``` -------------------------------- ### Cache API routes Source: https://github.com/dingo/api/wiki/Commands Caches API routes alongside application routes. Do not run route:cache separately as this command handles it automatically. ```bash $ php artisan api:cache ``` -------------------------------- ### Respond with an Error Source: https://github.com/dingo/api/wiki/Responses Generate various standard API error responses. ```php // A generic error with custom message and status code. return $this->response->error('This is an error.', 404); // A not found error with an optional message as the first parameter. return $this->response->errorNotFound(); // A bad request error with an optional message as the first parameter. return $this->response->errorBadRequest(); // A forbidden error with an optional message as the first parameter. return $this->response->errorForbidden(); // An internal error with an optional message as the first parameter. return $this->response->errorInternal(); // An unauthorized error with an optional message as the first parameter. return $this->response->errorUnauthorized(); ``` -------------------------------- ### Nest Route Groups Source: https://github.com/dingo/api/wiki/Creating-API-Endpoints Apply additional configuration like middleware to nested groups within a version. ```php $api->version('v1', function ($api) { $api->group(['middleware' => 'foo'], function ($api) { // Endpoints registered here will have the "foo" middleware applied. }); }); ``` -------------------------------- ### Customize Error Response Format Source: https://github.com/dingo/api/wiki/Configuration Define the structure of error responses within a 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' ] ]); ``` -------------------------------- ### Protect Controller Methods Source: https://github.com/dingo/api/wiki/Authentication Apply authentication middleware to controllers using the middleware method in the constructor. ```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() { // } } ``` -------------------------------- ### Extend Authorization Provider for Token-based Auth Source: https://github.com/dingo/api/wiki/Authentication Extend the Authorization class to handle tokens in the Authorization header. Use validateAuthorizationHeader to verify the header's presence. ```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'; } } ``` -------------------------------- ### Resource Exception JSON Response Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses The default JSON output format for resource exceptions including validation errors. ```json { "message": "Could not create new user.", "status_code": 422, "errors": { "username": [ "The username field is required." ], "password": [ "The password field is required." ] } } ``` -------------------------------- ### Catching InternalHttpException Source: https://github.com/dingo/api/wiki/Internal-Requests Handling Dingo-specific exceptions to access the underlying response object and status codes. ```php try { app('Dingo\\\Api\\\Dispatcher')->get('users/1'); } catch (Dingo\\\Api\\\Exception\\\InternalHttpException $e) { // We can get the response here to check the status code of the error or response body. $response = $e->getResponse(); } ``` -------------------------------- ### Implement a custom request validator Source: https://github.com/dingo/api/wiki/Extending-The-Core Create a custom validator by implementing the Validator interface to perform specific request checks. ```php headers = $headers; } public function validate(Request $request) { foreach ($this->headers as $header) { if (! $request->headers->has($header)) { return false; } } return true; } } ``` -------------------------------- ### Register HTTP Basic Authentication Provider Source: https://github.com/dingo/api/wiki/Authentication Registers the HTTP Basic provider using Laravel's auth instance and a specified identifier field. ```php app('Dingo\Api\Auth\Auth')->extend('basic', function ($app) { return new Dingo\Api\Auth\Provider\Basic($app['auth'], 'email'); }); ``` -------------------------------- ### Specify API Versions Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Use the @Versions annotation to restrict an action to specific API versions. ```php /** * Show all users * * Get a JSON representation of all the registered users. * * @Get("/") * @Versions({"v1"}) */ public function index() { } ``` -------------------------------- ### Protect API Routes with Middleware Source: https://github.com/dingo/api/wiki/Authentication Apply the api.auth middleware to entire route groups or specific routes to enforce authentication. ```php $api->version('v1', ['middleware' => 'api.auth'], function ($api) { // Routes within this version group will require authentication. }); ``` ```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. }); }); ``` -------------------------------- ### Enable rate limiting on specific routes Source: https://github.com/dingo/api/wiki/Rate-Limiting Applies the api.throttle middleware to individual routes within a version group. ```php $api->version('v1', function ($api) { $api->get('user', ['middleware' => 'api.throttle', function () { // This route requires authentication. }]); $api->get('posts', function () { // This route does not require authentication. }); }); ``` -------------------------------- ### Return Single Eloquent Model as JSON Source: https://github.com/dingo/api/wiki/Responses Returning a single model instance from a controller method triggers automatic JSON formatting. ```php class UserController { public function show($id) { return User::findOrFail($id); } } ``` -------------------------------- ### Add Additional Headers Source: https://github.com/dingo/api/wiki/Responses Append custom headers to a response. ```php return $this->response->item($user, new UserTransformer)->withHeader('X-Foo', 'Bar'); ``` -------------------------------- ### Restrict Authentication Providers for Routes Source: https://github.com/dingo/api/wiki/Authentication Use the providers key to limit which authentication methods are accepted for specific routes. ```php $api->version('v1', function ($api) { $api->get('user', ['middleware' => 'api.auth', 'providers' => ['basic', 'oauth'], function () { // This route requires authentication. }]); }); ``` -------------------------------- ### Register a Transformer for a Class Source: https://github.com/dingo/api/wiki/Transformers Registers a transformer class to a model, enabling automatic transformation when the model is returned from a route. ```php app('Dingo\Api\Transformer\Factory')->register('User', 'UserTransformer'); ``` -------------------------------- ### ConflictHttpException JSON Response Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses The default JSON output format for a ConflictHttpException. ```json { "message": "User was updated prior to your request.", "status_code": 409 } ``` -------------------------------- ### Register OAuth 2.0 Authentication Provider Source: https://github.com/dingo/api/wiki/Authentication Registers the OAuth 2.0 provider with user and client resolvers to handle identity retrieval. ```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() { // } } ``` -------------------------------- ### Register Custom Exception Handler Source: https://github.com/dingo/api/wiki/Errors-And-Error-Responses Registers a custom handler for specific exceptions to return a tailored JSON response. ```php app('Dingo\Api\Exception\Handler')->register(function (Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException $exception) { return Response::make(['error' => 'Hey, what do you think you are doing!?'], 401); }); ``` -------------------------------- ### Force HTTPS URL Generation in RouteServiceProvider Source: https://github.com/dingo/api/wiki/Misc Use this to ensure all URLs generated by the Dingo API use the HTTPS scheme. Place this code at the bottom of the map function in RouteServiceProvider.php. ```php app('Dingo\Api\Routing\UrlGenerator')->forceScheme('https'); ``` -------------------------------- ### Retrieve Authenticated User Source: https://github.com/dingo/api/wiki/Authentication Access the authenticated user via the Auth service or the auth property when using the Helpers trait. ```php $api->version('v1', ['middleware' => 'api.auth'], function ($api) { $api->get('user', function () { $user = app('Dingo\Api\Auth\Auth')->user(); return $user; }); }); ``` ```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; } } ``` -------------------------------- ### Set Response Status Code Source: https://github.com/dingo/api/wiki/Responses Manually set the HTTP status code for a response. ```php return $this->response->item($user, new UserTransformer)->setStatusCode(200); ``` -------------------------------- ### Define Specific Route Scopes Source: https://github.com/dingo/api/wiki/OAuth-2.0 Apply scopes to an individual route definition within an API version group. ```php $api->version('v1', ['middleware' => 'api.auth'], function ($api) { $api->get('user', ['scopes' => 'read_user_data', function () { // Only access tokens with the "read_user_data" scope will be given access. }]); }); ``` -------------------------------- ### Register a custom request validator Source: https://github.com/dingo/api/wiki/Extending-The-Core Extend the request validator service in your service provider to include your custom validator. ```php $this->app['Dingo\Api\Http\RequestValidator']->extend(new MyApp\Http\Validation\Headers(['x-api'])); ``` -------------------------------- ### Register Event Listener in EventServiceProvider Source: https://github.com/dingo/api/wiki/Responses Register the custom listener within the EventServiceProvider to trigger the logic during the response lifecycle. ```php protected $listen = [ 'Dingo\Api\Event\ResponseWasMorphed' => [ 'App\Listeners\AddPaginationLinksToResponse' ] ]; ``` -------------------------------- ### Define Route Group Scopes Source: https://github.com/dingo/api/wiki/OAuth-2.0 Apply scopes to an entire API version group to restrict access to tokens containing the specified permissions. ```php $api->version('v1', ['middleware' => 'api.auth', 'scopes' => ['read_user_data', 'write_user_data']], function ($api) { // Only access tokens with the "read_user_data" scope will be given access. }); ``` -------------------------------- ### Define API Transactions with PHP Annotations Source: https://github.com/dingo/api/wiki/API-Blueprint-Documentation Use the @Transaction annotation to group multiple request and response scenarios for a single 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() { } ``` -------------------------------- ### Conditionally modify response based on authentication status Source: https://github.com/dingo/api/wiki/Authentication Use the Dingo Auth service to check for an authenticated user inside an unprotected route. This allows hiding sensitive fields like email addresses from unauthenticated requests. ```php $api->version('v1', function ($api) { $api->get('users/{id}', function ($id) { $user = User::findOrFail($id); // Attempt to authenticate the request. If the request is not authenticated // then we'll hide the e-mail from the response. Only authenticated // requests can see other users e-mails. if (! app('Dingo\Api\Auth\Auth')->user()) { $hidden = $user->getHidden(); $user->setHidden(array_merge($hidden, ['email'])); } return $user; }); }); ``` -------------------------------- ### Send JSON Data Source: https://github.com/dingo/api/wiki/Internal-Requests Send JSON payloads by using the json() method; arrays are automatically encoded. ```php $data = ['name' => 'bill', 'password' => 12345]; $dispatcher->json($data)->post('users'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.