Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Swagger Ui Laravel Package

wotz/laravel-swagger-ui

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require wotz/laravel-swagger-ui
    php artisan swagger-ui:install
    

    This publishes the config (config/swagger-ui.php) and service provider (app/Providers/SwaggerUiServiceProvider.php).

  2. Configure Swagger File: Ensure your OpenAPI spec (JSON/YAML) is accessible. The package defaults to public/swagger.json or public/swagger.yaml. Update the path in config/swagger-ui.php if needed:

    'path' => 'public/swagger.json',
    
  3. First Use Case: Visit /swagger in your browser. The UI will auto-detect your Laravel environment (e.g., APP_URL) and configure the API base URL dynamically. Example: If APP_URL=http://localhost:8000, the Swagger UI will use http://localhost:8000/api as the base path.


Implementation Patterns

Core Workflows

  1. Environment-Aware API Docs:

    • The package injects APP_URL into Swagger UI, ensuring docs always reflect the current environment (dev/staging/prod).
    • Override via config:
      'base_url' => env('SWAGGER_BASE_URL', config('app.url')),
      
  2. OAuth2 Integration:

    • Configure OAuth2 in config/swagger-ui.php:
      'oauth2' => [
          'client_id' => 'your-client-id',
          'client_secret' => 'your-client-secret',
          'auth_url' => 'https://your-auth-server/oauth/authorize',
          'token_url' => 'https://your-auth-server/oauth/token',
      ],
      
    • The UI will auto-populate these fields, reducing manual setup.
  3. Dynamic Swagger File Loading:

    • Use a route closure to serve dynamic specs (e.g., generated from Laravel routes):
      Route::get('/swagger.json', function () {
          return response()->json($this->generateOpenApiSpec());
      });
      
    • Update the config path to point to this route.
  4. Middleware Integration:

    • Restrict access via middleware in SwaggerUiServiceProvider.php:
      public function boot()
      {
          $this->routes(function () {
              Route::middleware(['auth:sanctum'])->group(function () {
                  Route::get('/swagger', [SwaggerUiController::class, 'index']);
              });
          });
      }
      
  5. Theming and Assets:

    • Customize Swagger UI assets by publishing views:
      php artisan vendor:publish --tag=swagger-ui-views
      
    • Override resources/views/vendor/swagger-ui/index.blade.php to inject custom CSS/JS.

Advanced Patterns

  1. API Versioning:

    • Serve multiple Swagger files for different API versions:
      // routes/api.php
      Route::prefix('v1')->group(function () {
          Route::get('/swagger.json', [SwaggerController::class, 'v1']);
      });
      
    • Configure versioned paths in config/swagger-ui.php:
      'paths' => [
          'v1' => 'api/v1/swagger.json',
          'v2' => 'api/v2/swagger.json',
      ],
      
  2. Conditional UI Loading:

    • Disable Swagger UI in production:
      'enabled' => !app()->environment('production'),
      
  3. Webhook Integration:

    • Trigger Swagger spec regeneration on route changes (e.g., using route:list events):
      Route::macro('generateSwagger', function () {
          $spec = $this->generateSpec();
          file_put_contents(public_path('swagger.json'), json_encode($spec));
      });
      

Gotchas and Tips

Common Pitfalls

  1. CORS Issues:

    • If Swagger UI fails to load, ensure your API routes allow requests from the Swagger UI domain (e.g., localhost).
    • Add CORS headers in your API middleware:
      Header::set('Access-Control-Allow-Origin', '*');
      
  2. Environment Mismatch:

    • The UI uses APP_URL by default. If your API is behind a proxy (e.g., Nginx), set:
      'base_url' => env('API_BASE_URL', config('app.url')),
      
  3. OAuth2 Token Expiry:

    • Swagger UI caches OAuth2 tokens. Clear cache if tokens expire unexpectedly:
      // Override in custom JS (e.g., via blade injection)
      window.SwaggerUIBundle.prototype.updateToken = function() { ... };
      
  4. File Permissions:

    • Ensure the Swagger file is readable by the web server:
      chmod 644 public/swagger.json
      

Debugging Tips

  1. Validate Spec:

    • Use Swagger Editor to validate your OpenAPI spec before debugging UI issues.
  2. Check Network Requests:

    • Open DevTools (F12) and verify the Swagger UI fetches the correct spec URL (e.g., /swagger.json).
  3. Log Configuration:

    • Add debug logs in SwaggerUiServiceProvider.php:
      \Log::debug('Swagger UI config:', config('swagger-ui'));
      
  4. Clear Published Assets:

    • If UI changes don’t reflect, clear published views:
      rm -rf resources/views/vendor/swagger-ui
      php artisan vendor:publish --tag=swagger-ui-views --force
      

Extension Points

  1. Custom Controllers:

    • Extend SwaggerUiController to add logic (e.g., auth checks):
      namespace App\Http\Controllers;
      use Wotzebra\SwaggerUi\Http\Controllers\SwaggerUiController as BaseController;
      
      class SwaggerUiController extends BaseController {
          public function index() {
              if (!auth()->check()) abort(403);
              return parent::index();
          }
      }
      
    • Update SwaggerUiServiceProvider.php to bind the custom controller.
  2. Dynamic Spec Generation:

    • Use Laravel’s RouteServiceProvider to generate specs on-the-fly:
      public function boot()
      {
          $this->routes(function () {
              Route::get('/swagger.json', function () {
                  return response()->json($this->generateSpecFromRoutes());
              });
          });
      }
      
  3. Plugin Integration:

    • Load Swagger UI plugins via config:
      'plugins' => [
          'swagger-ui-bundle/plugin/swagger-ui-standalone-preset.min.js',
          'swagger-ui-bundle/plugin/swagger-ui-oauth2-grant.min.js',
      ],
      
  4. Localization:

    • Override Swagger UI language files by publishing translations:
      php artisan vendor:publish --tag=swagger-ui-translations
      
    • Edit resources/lang/vendor/swagger-ui/en.json.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope