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

L Swagger Laravel Package

lonban/l-swagger

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require lonban/l-swagger
    

    Publish the config and views:

    php artisan vendor:publish --provider="Lonban\Lswagger\LswaggerServiceProvider"
    
  2. Basic Configuration Edit config/lswagger.php to define:

    • api_prefix (e.g., api/v1)
    • scan_paths (e.g., ['app/Http/Controllers'])
    • auth (if API requires authentication)
    • title and description for the docs.
  3. First Use Case: Annotate a Controller Add Swagger annotations to a controller method:

    use Lonban\Lswagger\Annotation\Api;
    
    /**
     * @Api(
     *     path="/users",
     *     method="GET",
     *     summary="Get all users",
     *     tags={"Users"}
     * )
     */
    public function index()
    {
        return User::all();
    }
    
  4. Generate and View Docs Visit:

    • http://yourdomain/lswagger/api (API + docs)
    • http://yourdomain/lswagger/docs (Docs only)

Implementation Patterns

Workflows

  1. Incremental Documentation

    • Start with critical endpoints (e.g., auth, core resources).
    • Gradually annotate controllers as you build features.
    • Use @Api for routes and @Param/@Body for request validation.
  2. Integration with Laravel Routing

    • For named routes, reference them in @Api(path="route.name"):
      Route::get('/users/{id}', [UserController::class, 'show'])->name('users.show');
      /**
       * @Api(path="route.users.show", method="GET")
       */
      public function show($id) { ... }
      
  3. Request/Response Modeling

    • Define models for request/response bodies:
      /**
       * @Api(
       *     path="/users",
       *     method="POST",
       *     summary="Create a user",
       *     @Body(model=UserRequest::class)
       * )
       */
      public function store(UserRequest $request) { ... }
      
      /**
       * @model
       */
      class UserRequest {
          /**
           * @var string
           * @required
           */
          public $name;
      }
      
  4. Authentication Handling

    • Configure auth in lswagger.php:
      'auth' => [
          'type' => 'http', // or 'apiKey', 'oauth2'
          'name' => 'Authorization',
          'in' => 'header',
          'bearerFormat' => 'Bearer',
      ],
      
    • Add @Security to methods requiring auth:
      /**
       * @Api(path="/admin", method="GET")
       * @Security(scheme="http")
       */
      
  5. Grouping Endpoints

    • Use @Tag to categorize endpoints:
      /**
       * @Api(path="/users", method="GET", tags={"Users"})
       * @Api(path="/users/{id}", method="GET", tags={"Users"})
       */
      
  6. Testing Locally

    • Use php artisan lswagger:generate to regenerate docs on demand.
    • Test the /lswagger/docs endpoint in your browser or with tools like Postman.

Integration Tips

  1. CI/CD Pipeline

    • Add a step to validate Swagger annotations (e.g., using phpstan or custom scripts).
    • Example GitHub Actions snippet:
      - name: Generate Swagger Docs
        run: php artisan lswagger:generate
      - name: Upload Artifact
        uses: actions/upload-artifact@v2
        with:
          name: swagger-docs
          path: public/lswagger/docs
      
  2. Versioning

    • Use separate config files or environment-specific scan_paths for different API versions.
    • Example:
      // config/lswagger-v2.php
      'scan_paths' => ['app/Http/Controllers/V2'],
      'api_prefix' => 'api/v2',
      
  3. Custom Templates

    • Override the default Swagger UI by publishing and modifying:
      php artisan vendor:publish --tag=lswagger-views
      
    • Edit resources/views/lswagger/index.blade.php for branding or layout changes.
  4. Dynamic Paths

    • For dynamic routes, use placeholders in @Api(path):
      /**
       * @Api(path="/users/{id}", method="GET")
       */
      public function show($id) { ... }
      
    • Define parameters with @Param:
      /**
       * @Param(name="id", type="integer", required=true, description="User ID")
       */
      
  5. Error Handling

    • Document error responses with @Response:
      /**
       * @Api(path="/users", method="POST")
       * @Response(status=422, model=ValidationError::class)
       */
      

Gotchas and Tips

Pitfalls

  1. Annotation Parsing Issues

    • Problem: Annotations are ignored or cause errors.
    • Fix:
      • Ensure annotations are placed above the method/class.
      • Use /** */ (not /* */) for multi-line annotations.
      • Avoid special characters in @Api(path) (URL-encode if needed).
  2. Caching Quirks

    • Problem: Docs don’t update after adding new annotations.
    • Fix:
      • Clear the cache:
        php artisan cache:clear
        php artisan view:clear
        
      • Regenerate docs manually:
        php artisan lswagger:generate
        
  3. Route Conflicts

    • Problem: /lswagger conflicts with existing routes.
    • Fix:
      • Add middleware to the lswagger route in routes/web.php:
        Route::prefix('lswagger')->middleware(['web'])->group(function () {
            \Lonban\Lswagger\Lswagger::routes();
        });
        
  4. Model Validation Mismatches

    • Problem: @Body(model=...) doesn’t match request validation.
    • Fix:
      • Ensure the model’s properties match Laravel’s validation rules.
      • Use @Property to override defaults:
        /**
         * @Property(type="string", format="date-time", example="2023-01-01T00:00:00Z")
         */
        public $created_at;
        
  5. Authentication Gaps

    • Problem: Auth schemes are misconfigured in the docs.
    • Fix:
      • Test the /lswagger/docs endpoint with tools like Swagger UI’s "Authorize" button.
      • Verify lswagger.php auth settings match your API’s actual auth flow.
  6. Performance with Large Codebases

    • Problem: Slow doc generation due to broad scan_paths.
    • Fix:
      • Narrow scan_paths to only annotated controllers.
      • Exclude test directories (e.g., ['app/Http/Controllers', '!app/Http/Controllers/Test']).

Debugging

  1. Enable Verbose Logging Add to config/lswagger.php:

    'debug' => true,
    

    Check Laravel logs (storage/logs/laravel.log) for parsing errors.

  2. Validate Annotations Use a linter like PHPStan with the phpstan-phpdoc-parser extension to catch syntax issues.

  3. Inspect Generated JSON Visit /lswagger/api/json to see the raw Swagger JSON. Validate it with: Swagger Editor.


Extension Points

  1. Custom Annotations

    • Extend the parser by creating a custom annotation class (see Lonban\Lswagger\Annotation namespace).
    • Example:
      namespace App\Annotations;
      use Lonban\Lswagger\Annotation\Annotation;
      
      #[Attribute]
      class DeprecatedSince extends Annotation {
          public function __construct(public string $version) {}
      }
      
    • Register the namespace in config/lswagger.php:
      'annotation_namespaces' => [
          'Lonban\Lswagger\Annotation',
          'App\Annotations',
      ],
      
  2. Post-Processing Hooks

    • Use Laravel’s service provider to modify the generated spec:
      public function boot()
      {
          Lswagger::afterGenerate(function ($spec) {
              $spec['info']['x-custom'] = 'value';
              return $spec;
          });
      }
      
  3. Dynamic Documentation

    • Fetch the Swagger spec programmatically:
      $spec = Lswagger::getSpec();
      // Process $spec (e.g., export to
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor