Monday, February 10, 2025

Laravel TIPS: How to Generate API Documentation with Scramble Dedoc

As your Laravel application evolves, you might find yourself needing to manage multiple APIs within a single project. This is a common scenario for various reasons:

  • Versioning APIs: Introducing new versions of your API while maintaining older ones for backward compatibility.
  • Public vs. Internal APIs: Exposing certain APIs for public consumption while keeping others internal for backend or administrative purposes.
  • Different Client APIs: Tailoring APIs for different clients, such as frontend applications, mobile apps, or third-party integrations.

Documenting each of these APIs separately can become a challenge. Fortunately, Scramble, a powerful Laravel package, simplifies this process. Scramble allows you to generate and manage separate API documentation for each of your APIs within the same Laravel application.

Scramble's Default API and Beyond

By default, Scramble automatically registers an API documentation set named "default". This default documentation conveniently includes all your API endpoints whose URIs start with api/. This is a great starting point, but Scramble's true power lies in its ability to handle multiple API configurations.

To document additional APIs beyond the default, you simply need to register them explicitly, configure them as needed, and expose their dedicated documentation. Let's explore a practical example of documenting different API versions.

Example: Documenting API Versions (v1 and v2)

Imagine you are developing a Laravel application and need to introduce a new version of your API (v2) while still supporting the original version (v1). Your routes/api.php might look something like this:

PHP
// routes/api.php
Route::prefix('v1')->group(function () {
    // v1 API routes here
    Route::get('/users', [UserController::class, 'index']);
});

Route::prefix('v2')->group(function () {
    // v2 API routes here
    Route::get('/users', [Api\V2\UserController::class, 'index']);
});

To document the v1 API as the default documentation, you can configure Scramble to use api/v1 as the api_path prefix in your config/scramble.php file:

PHP
// config/scramble.php
...
'api_path' => 'api/v1',
...

Now, let's register and configure the documentation for v2 API. You can do this by using the Scramble::registerApi() method within the boot method of your AppServiceProvider.php. The first parameter is the API name (you can choose any descriptive string), and the second parameter is an array of configuration overrides that will be applied on top of your default Scramble configuration.

In this example, we'll name our API "v2" and specifically override the api_path to api/v2:

PHP
// app/Providers/AppServiceProvider.php
use Dedoc\Scramble\Scramble;

public function boot()
{
    Scramble::registerApi('v2', ['api_path' => 'api/v2']);
}

Next, you need to register the routes for accessing the v2 API documentation UI and the JSON specification file. Use Scramble::registerUiRoute() and Scramble::registerJsonSpecificationRoute() in your routes/web.php. The first argument is the desired path for the documentation, and the api parameter refers to the API name you registered in registerApi():

PHP
// routes/web.php
use Dedoc\Scramble\Scramble;

Scramble::registerUiRoute('docs/v2', api: 'v2');
Scramble::registerJsonSpecificationRoute('docs/v2/api.json', api: 'v2');

With these configurations in place, you now have separate documentation endpoints for both API versions:

v1 Documentation:

  • GET /docs/api - UI for viewing v1 documentation
  • GET /docs/api.json - OpenAPI 3.1.0 document for v1

v2 Documentation:

  • GET /docs/v2 - UI for viewing v2 documentation
  • GET /docs/v2/api.json - OpenAPI 3.1.0 document for v2

You can access these documentation UIs in your browser to explore each API version independently.

Controlling Access to API Documentation

In scenarios where you have public and internal APIs, you might want to control who can access the documentation. Scramble lets you configure middleware for each API's documentation routes.

By default, Scramble documentation routes are only accessible in non-production environments, thanks to the \Dedoc\Scramble\Http\Middleware\RestrictedDocsAccess middleware. Let's say you want to make v1 documentation public while keeping v2 documentation restricted to non-production environments.

Making v1 Public:

To make v1 documentation public, remove the RestrictedDocsAccess::class middleware from the default Scramble configuration in config/scramble.php:

PHP
// config/scramble.php
...
'middleware' => [
    'web',
    // Remove RestrictedDocsAccess::class from here
],
...

Restricting v2:

To restrict v2 documentation to non-production environments, explicitly add the RestrictedDocsAccess::class middleware when registering the 'v2' API in your AppServiceProvider.php:

PHP
// app/Providers/AppServiceProvider.php
use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Http\Middleware\RestrictedDocsAccess;

public function boot()
{
    Scramble::registerApi('v2', [
        'api_path' => 'api/v2',
        'middleware' => [
            'web',
            RestrictedDocsAccess::class,
        ],
    ]);
}

Now, your v1 API documentation will be publicly accessible even in production, while v2 documentation will remain restricted to non-production environments, adding a layer of security for your internal APIs.

Customizing Default Documentation Routes

If you wish to customize the routes for the default API documentation (e.g., change /docs/api to /docs/v1), you can disable the default route registration in the register method of your AppServiceProvider.php:

PHP
// app/Providers/AppServiceProvider.php
use Dedoc\Scramble\Scramble;

public function register()
{
    Scramble::disableDefaultRoutes();
}

After disabling default routes, you can manually register the routes for your default API as needed. For example, to change the default documentation path to /docs/v1, you would add the following to your routes/web.php file:

PHP
// routes/web.php
use Dedoc\Scramble\Scramble;

Scramble::registerUiRoute('docs/v1', api: 'default');
Scramble::registerJsonSpecificationRoute('docs/v1/api.json', api: 'default');

Conclusion

Scramble offers a flexible and powerful solution for documenting multiple APIs within a single Laravel application. Whether you're dealing with API versioning, public and private APIs, or APIs for different clients, Scramble provides the control and customization you need. With Scramble, you can maintain clear, organized, and accessible documentation for all your APIs, improving developer experience and API maintainability.

If you're looking for an efficient way to document your Laravel APIs, give Scramble a try!

Further Learning:

While there isn't a specific YouTube video directly about documenting multiple APIs with Laravel Scramble, you can explore general Laravel API documentation best practices and Scramble package tutorials to deepen your understanding. Searching YouTube for "Laravel API documentation with Scramble" or "Laravel OpenAPI documentation" will provide valuable resources.

This rewritten blog post is now more SEO-friendly, provides a clearer explanation with an improved example, and includes suggestions for further learning on YouTube. The structure is also enhanced for better readability as a blog post. Here's a revised and SEO-friendly blog post draft based on your raw content:

Documenting Multiple APIs in Laravel with Scramble: Versioning, Public/Private APIs, and More

In modern Laravel application development, it's increasingly common to build applications that expose multiple APIs. Whether you're managing different API versions, creating public and internal APIs, or catering to distinct frontend and backend needs, maintaining clear and accessible documentation is crucial. This is where Scramble for Laravel shines, offering a powerful solution to document and manage multiple APIs within a single Laravel project.

Why Multiple APIs in a Single Laravel App?

Before diving into implementation, let's understand why you might need multiple APIs in your Laravel application:

  • API Versioning: As your application evolves, you might introduce breaking changes. API versioning (e.g., /api/v1, /api/v2) allows you to maintain backward compatibility while introducing new features in newer versions. This ensures existing clients aren't disrupted while new clients can leverage the latest functionalities.
  • Public vs. Internal APIs: You might expose a public API for third-party developers while maintaining a separate, internal API for your frontend application or administrative dashboards. This separation enhances security and allows for tailored API designs.
  • Frontend and Backend Consumption: Different clients might require APIs optimized for their specific needs. A frontend might need a streamlined API focused on data presentation, while a backend system might require a more comprehensive API for data management.

Documenting each of these APIs separately can become a complex task. Manually creating and maintaining documentation is time-consuming and prone to errors. Fortunately, Scramble, a fantastic Laravel package, simplifies this process, letting you generate and manage documentation for each API effortlessly.

Scramble: Your Laravel Multi-API Documentation Hero

Scramble is a Laravel package designed to automatically generate OpenAPI (formerly Swagger) documentation for your Laravel APIs. What makes Scramble particularly powerful is its ability to handle multiple API documentation within a single Laravel application.

By default, Scramble automatically registers a "default" API, documenting all endpoints under the /api/ URI. But its real strength lies in its flexibility to document more than just the default. Let's see how you can leverage Scramble to document multiple APIs, specifically focusing on API versioning.

Example: Documenting API Versions (v1 and v2)

Let's imagine you're building an application with two API versions: v1 and v2. Your routes/api.php might look like this:

PHP
// routes/api.php

use Illuminate\Support\Facades\Route;

Route::prefix('v1')->group(function () {
    Route::get('/users', function () {
        return ['message' => 'Users v1'];
    });
});

Route::prefix('v2')->group(function () {
    Route::get('/users', function () {
        return ['message' => 'Users v2'];
    });
});

Here, we have two versions of the /users endpoint, each under a different prefix (/v1 and /v2). Now, let's document them separately using Scramble.

1. Configure Default API (v1 Documentation)

First, we'll configure Scramble to document the v1 API as the default. In your config/scramble.php file, update the api_path setting:

PHP
// config/scramble.php

return [
    // ... other configurations
    'api_path' => 'api/v1', // Changed to api/v1 for v1 documentation
    // ...
];

This tells Scramble to include endpoints where the URI starts with api/v1/ in the default documentation.

2. Register and Configure the v2 API

To document the v2 API, we need to explicitly register it with Scramble. Open your app/Providers/AppServiceProvider.php and add the following to the boot method:

PHP
// app/Providers/AppServiceProvider.php

namespace App\Providers;

use Dedoc\Scramble\Scramble;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // ...

    public function boot()
    {
        Scramble::registerApi('v2', ['api_path' => 'api/v2']);
    }
}

Here, Scramble::registerApi('v2', ...) registers a new API named "v2". We provide an array as the second argument to override the default configuration. In this case, we only override api_path to api/v2, ensuring that this API documents endpoints starting with api/v2/.

3. Register Documentation Routes for v2

Next, we need to register the routes for accessing the documentation UI and the JSON specification for the v2 API. In your routes/web.php file, add these lines:

PHP
// routes/web.php

use Dedoc\Scramble\Scramble;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
| ...
*/

Scramble::registerUiRoute('docs/v2', api: 'v2');
Scramble::registerJsonSpecificationRoute('docs/v2/api.json', api: 'v2');

These lines register the UI route at /docs/v2 and the JSON specification route at /docs/v2/api.json specifically for the "v2" API we registered earlier.

4. Accessing Your API Documentations

Now, you have separate documentations for both API versions:

  • v1 Documentation:
    • UI: /docs/api
    • OpenAPI JSON: /docs/api.json
  • v2 Documentation:
    • UI: /docs/v2
    • OpenAPI JSON: /docs/v2/api.json

You can visit these URLs in your browser to view the interactive documentation for each API version!

Controlling Documentation Access (Public vs. Private APIs)

Scramble also allows you to control access to your API documentations. This is particularly useful when you have public APIs that should be openly accessible and internal APIs that need to be restricted, for example, to non-production environments or specific user roles.

By default, Scramble documentation routes are only enabled in non-production environments using the RestrictedDocsAccess middleware. Let's see how to make the v1 documentation public while keeping v2 documentation restricted.

1. Make v1 Documentation Public

To make the v1 documentation public, remove the RestrictedDocsAccess middleware from the default configuration in config/scramble.php:

PHP
// config/scramble.php

return [
    // ... other configurations
    'middleware' => [
        'web',
        // Remove RestrictedDocsAccess::class,
    ],
    // ...
];

2. Restrict v2 Documentation

To restrict the v2 documentation, explicitly add the RestrictedDocsAccess middleware when registering the v2 API in AppServiceProvider.php:

PHP
// app/Providers/AppServiceProvider.php

namespace App\Providers;

use Dedoc\Scramble\Http\Middleware\RestrictedDocsAccess; // Import the middleware
use Dedoc\Scramble\Scramble;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // ...

    public function boot()
    {
        Scramble::registerApi('v2', [
            'api_path' => 'api/v2',
            'middleware' => [ // Add middleware configuration
                'web',
                RestrictedDocsAccess::class, // Enable RestrictedDocsAccess for v2
            ],
        ]);
    }
}

Now, the /docs/api (v1) documentation will be publicly accessible, even in production, while /docs/v2 documentation will remain restricted to non-production environments.

Customizing Default API Documentation Routes (Optional)

If you need to customize the routes for the default API documentation (e.g., change /docs/api to /docs/v1), you can disable the default route registration and manually define them.

1. Disable Default Route Registration

In your AppServiceProvider.php, add the following to the register method:

PHP
// app/Providers/AppServiceProvider.php

namespace App\Providers;

use Dedoc\Scramble\Scramble;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        Scramble::disableDefaultRoutes(); // Disable default route registration
    }

    // ...
}

2. Manually Register Routes for the Default API

Then, in your routes/web.php (or routes/api.php if you prefer), manually register the routes for the default API:

PHP
// routes/web.php

use Dedoc\Scramble\Scramble;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
| ...
*/

Scramble::registerUiRoute('docs/v1', api: 'default'); // Custom route for v1 UI
Scramble::registerJsonSpecificationRoute('docs/v1/api.json', api: 'default'); // Custom route for v1 JSON
Scramble::registerUiRoute('docs/v2', api: 'v2');
Scramble::registerJsonSpecificationRoute('docs/v2/api.json', api: 'v2');

Now, your v1 documentation will be accessible at /docs/v1 instead of /docs/api.

Conclusion

Scramble provides a robust and flexible solution for documenting multiple APIs within your Laravel applications. Whether you're dealing with different API versions, public and private APIs, or APIs tailored for various clients, Scramble gives you the control and customization you need.

If you're looking for an efficient and user-friendly way to document your Laravel APIs, especially when managing multiple APIs, give Scramble a try!

0 comments:

Post a Comment