Laravel applications often manage multiple APIs, beneficial for versioning, separating public and internal access, or catering to different frontend/backend needs. Scramble simplifies documenting these diverse APIs.
Scramble's default setup documents an "default" API, encompassing endpoints starting with api/
. Adding more APIs involves registration, configuration, and documentation exposure.
Example: Documenting Multiple API Versions
Consider an application with two API versions:
// routes/api.php Route::prefix('v1')->group(function () { // v1 routes }); Route::prefix('v2')->group(function () { // v2 routes });
To document v1
, adjust the Scramble config:
// config/scramble.php ... 'api_path' => 'api/v1', ...
For v2
, register it explicitly within a service provider's boot
method:
// app/Providers/AppServiceProvider.php use Dedoc\Scramble\Facades\Scramble; public function boot() { Scramble::registerApi('v2', ['api_path' => 'api/v2']); }
Register the v2
documentation routes in routes/web.php
:
// routes/web.php use Dedoc\Scramble\Facades\Scramble; Scramble::registerUiRoute('docs/v2', api: 'v2'); Scramble::registerJsonSpecificationRoute('docs/v2/api.json', api: 'v2');
Now, both APIs are documented:
v1 Documentation:
GET docs/api
: UI for v1 documentationGET docs/api.json
: OpenAPI 3.1.0 specification for v1v2 Documentation:
GET docs/v2
: UI for v2 documentationGET docs/v2/api.json
: OpenAPI 3.1.0 specification for v2Controlling Documentation Access
For public and private APIs, manage middleware. By default, documentation is limited to non-production environments via RestrictedDocsAccess
middleware.
To make v1
public, remove RestrictedDocsAccess
from the default configuration:
// config/scramble.php ... 'middleware' => [ 'web', ], ...
To restrict v2
to non-production:
// app/Providers/AppServiceProvider.php use Dedoc\Scramble\Http\Middleware\RestrictedDocsAccess; public function boot() { Scramble::registerApi('v2', [ 'api_path' => 'api/v2', 'middleware' => [ 'web', RestrictedDocsAccess::class, ], ]); }
Now, v1
is publicly accessible in production, while v2
remains restricted to non-production.
Customizing v1 Documentation Routes
To customize the default v1
routes (GET docs/api
, GET docs/api.json
), disable default route registration:
// app/Providers/AppServiceProvider.php public function register() { Scramble::disableDefaultRoutes(); }
Then, register them manually:
// routes/web.php Scramble::registerUiRoute('docs/v1', api: 'default'); Scramble::registerJsonSpecificationRoute('docs/v1/api.json', api: 'default');
Conclusion
Scramble efficiently handles multiple API documentation within a single Laravel application, offering granular control over routes, middleware, and configuration for each API. Learn more at: https://www.php.cn/link/0fcbc3c0cf262c771001930af2406bbc
The above is the detailed content of How to document multiple APIs in Laravel with Scramble. For more information, please follow other related articles on the PHP Chinese website!