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

Swagger Ui Laravel Package

swagger-api/swagger-ui

Swagger UI renders interactive API documentation from your OpenAPI/Swagger spec. Let developers and consumers explore endpoints, try requests, and see schemas without backend implementation. Available as npm modules (swagger-ui, swagger-ui-dist) and Docker image.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install via npm (for frontend integration):

    npm install swagger-ui-dist --save
    

    Or use the standalone dist files from releases.

  2. Publish OpenAPI/Swagger Spec:

    • Generate a swagger.json or openapi.yaml file (use packages like darkaonline/l5-swagger or zircote/swagger-php).
    • Place it in public/docs/swagger.json or serve it via an API route (e.g., route('api.swagger')).
  3. Basic HTML Integration (in resources/views/docs.blade.php):

    <!DOCTYPE html>
    <html>
      <head>
        <link rel="stylesheet" type="text/css" href="{{ asset('vendor/swagger-ui-dist/swagger-ui.css') }}">
      </head>
      <body>
        <div id="swagger-ui"></div>
        <script src="{{ asset('vendor/swagger-ui-dist/swagger-ui-bundle.js') }}"></script>
        <script>
          const ui = SwaggerUIBundle({
            url: "{{ route('api.swagger') }}",
            dom_id: '#swagger-ui',
            presets: [
              SwaggerUIBundle.presets.apis,
              SwaggerUIStandalonePreset
            ],
          });
        </script>
      </body>
    </html>
    
  4. Route Access:

    Route::get('/docs', function () {
        return view('docs');
    })->name('docs');
    

Implementation Patterns

1. Dynamic Spec Loading

  • Use Case: Load Swagger specs dynamically from Laravel routes or storage.
  • Pattern:
    Route::get('/api/swagger', function () {
        return response()->json(file_get_contents(storage_path('app/swagger.json')));
    })->name('api.swagger');
    
  • Frontend Config:
    url: "{{ route('api.swagger') }}?version={{ config('app.version') }}",
    

2. Authentication Integration

  • OAuth2 Example (for protected APIs):
    ui.initOAuth({
        clientId: "{{ config('services.swagger.client_id') }}",
        appName: "Laravel API Docs",
        scopes: "read write",
        usePkceWithAuthorizationCodeGrant: true,
    });
    
  • API Token Auth: Add a SecurityDefinitions section to your Swagger spec:
    securityDefinitions:
      Bearer:
        type: apiKey
        name: Authorization
        in: header
    
    Then configure Swagger UI to pre-fill the header:
    ui.preauthorizeApiKey('Authorization', 'Bearer {{ auth()->token() }}');
    

3. Custom Theming

  • Override CSS in resources/sass/swagger.scss:
    // Target Swagger UI classes
    .topbar-wrapper {
      background-color: #2d3748;
    }
    
  • Compile with Laravel Mix:
    mix.sass('resources/sass/swagger.scss', 'public/css');
    

4. Plugin Extensions

  • Example: Add a custom plugin to log API calls.
    SwaggerUIBundle.plugins.SwaggerUIStandalonePreset.injectStylesheet(
        'https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css'
    );
    SwaggerUIBundle.plugins.SwaggerUIStandalonePreset.addRequestInterceptor((request) => {
        console.log('API Call:', request);
        return request;
    });
    

5. Versioned APIs

  • Route-Based:
    Route::prefix('v1')->group(function () {
        // v1 routes
    });
    Route::prefix('v2')->group(function () {
        // v2 routes
    });
    
  • Swagger Config:
    url: "{{ route('api.swagger') }}?version=v1",
    

Gotchas and Tips

1. CORS Issues

  • Problem: Swagger UI may block requests due to CORS if the API and UI are on different domains.
  • Fix:
    • Configure CORS in Laravel (app/Http/Middleware/Cors.php):
      protected $allowedMethods = ['*'];
      protected $allowedOrigins = ['http://localhost:8000', 'https://your-ui-domain.com'];
      
    • Or use a proxy route in Laravel:
      Route::get('/proxy/{path}', function ($path) {
          return response()->streamDownload(function () {
              $ch = curl_init("https://api.example.com/{$path}");
              curl_setopt($ch, CURLOPT_HEADER, false);
              curl_exec($ch);
          }, "response.json");
      });
      

2. Forbidden Headers

  • Problem: Headers like Cookie or Authorization may be stripped by browsers.
  • Workaround:
    • Use securityDefinitions in Swagger to document auth headers.
    • For cookies, use query or header parameters with in: cookie (but note browser limitations).

3. OAuth2 Client Secret Leak

  • Risk: Hardcoding clientSecret in frontend JS exposes it.
  • Solution:
    • Use usePkceWithAuthorizationCodeGrant: true to avoid client secrets.
    • For production, implement a backend proxy to handle OAuth flows.

4. Deep Linking

  • Use Case: Share specific endpoints (e.g., /docs#/pets/getPetById).
  • Tip:
    • Use Laravel route parameters to pre-fill the URL:
      Route::get('/docs/pets/{id}', function ($id) {
          return view('docs', ['initialUrl' => "pets/getPetById/{$id}"]);
      })->name('docs.pets');
      
    • Configure Swagger UI:
      url: "{{ route('api.swagger') }}",
      initialValue: "{{ $initialUrl ?? '' }}",
      

5. Performance Optimization

  • Tip: Cache the Swagger spec in Laravel:
    Route::get('/api/swagger', function () {
        return Cache::remember('swagger-spec', now()->addHours(1), function () {
            return response()->json(file_get_contents(storage_path('app/swagger.json')));
        });
    });
    

6. Debugging Tips

  • Check Console: Open browser dev tools (F12) to inspect Swagger UI errors.
  • Validate Spec: Use Swagger Editor to validate your OpenAPI spec.
  • Disable Analytics: Add to package.json:
    "scarfSettings": { "enabled": false }
    

7. Laravel-Specific Quirks

  • Asset Paths: Use Laravel Mix/Vite to bundle Swagger UI assets:
    // vite.config.js
    export default {
        build: {
            assetsDir: 'assets',
            outDir: 'public/dist',
        },
    };
    
  • Environment Variables: Pass config via Blade:
    <script>
        const swaggerConfig = @json([
            'clientId' => env('SWAGGER_CLIENT_ID'),
            'url' => route('api.swagger'),
        ]);
    </script>
    

8. Extending with Plugins

  • Example: Add a "Copy as cURL" button.
    SwaggerUIBundle.plugins.SwaggerUIStandalonePreset.addButton({
        className: 'copy-curl',
        label: 'Copy as cURL',
        onClick: (ui) => {
            const curl = ui.getOperationCurl();
            navigator.clipboard.writeText(curl);
            ui.addNotification('Copied to clipboard!');
        },
    });
    
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.
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
anil/file-picker
broqit/fields-ai