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

Lara Swag Laravel Package

zquintana/lara-swag

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require zquintana/lara-swag dev-master
    

    Add the service provider to config/app.php:

    ZQuintana\LaraSwag\Provider\LaraSwagProvider::class
    
  2. Publish Config & Assets:

    php artisan vendor:publish --provider="ZQuintana\LaraSwag\Provider\LaraSwagProvider::class"
    

    This generates:

    • config/lara_swag.php (configuration)
    • routes/lara_swag.php (Swagger UI routes)
    • Templates (if applicable).
  3. Register Routes: Include the generated lara_swag.php in your routes/api.php (or routes/web.php if using Laravel <5.3):

    Route::group(['prefix' => 'api'], function () {
        require_once base_path('routes/lara_swag.php');
    });
    
  4. Annotate a Controller: Add PHPDoc-style annotations to your controller methods to define API endpoints:

    /**
     * @api {get} /users Retrieve a list of users
     * @apiName GetUsers
     * @apiGroup User
     * @apiSuccess {Object[]} users List of users
     */
    public function index()
    {
        return User::all();
    }
    
  5. Access Swagger UI: Visit /api/docs (or the configured path) to view the generated API documentation.


First Use Case

Generate documentation for a single controller to validate the package works. For example:

/**
 * @api {post} /users Create a new user
 * @apiName CreateUser
 * @apiGroup User
 * @apiParam {String} name User's name
 * @apiParam {String} email User's email
 * @apiSuccess {Object} user Created user
 */
public function store(Request $request)
{
    return User::create($request->all());
}

Refresh /api/docs to see the new endpoint documented.


Implementation Patterns

Workflows

  1. Annotation-Based Documentation:

    • Use @api, @apiName, @apiGroup, @apiParam, @apiSuccess, etc., in PHPDoc blocks for controllers and methods.
    • Example for a resourceful controller:
      /**
       * @api {get} /users/:id Get a user by ID
       * @apiName GetUser
       * @apiGroup User
       * @apiParam {Number} id User's ID
       * @apiSuccess {Object} user User details
       * @apiSuccessExample Success Response:
       *     HTTP/1.1 200 OK
       *     {
       *       "user": {
       *         "id": 1,
       *         "name": "John Doe"
       *       }
       *     }
       */
      public function show($id)
      {
          return User::findOrFail($id);
      }
      
  2. Grouping Endpoints:

    • Use @apiGroup to logically group related endpoints (e.g., User, Auth, Product).
    • Swagger UI will organize these groups in the sidebar.
  3. Request/Response Examples:

    • Use @apiSuccessExample and @apiErrorExample to provide sample responses:
      /**
       * @apiErrorExample Error Response:
       *     HTTP/1.1 404 Not Found
       *     {
       *       "error": "User not found"
       *     }
       */
      
  4. Authentication:

    • Annotate global auth requirements (e.g., @apiHeader for tokens):
      /**
       * @apiHeader {String} Authorization Bearer token
       */
      public function sensitiveData()
      {
          // Requires auth
      }
      
  5. Integration with Laravel Routes:

    • Ensure route names match @apiName for consistency. Use named routes:
      Route::get('/users/{id}', ['as' => 'users.show', 'uses' => 'UserController@show']);
      

Integration Tips

  1. Custom Templates:

    • Override Swagger UI templates by publishing and modifying the resources/views/vendor/lara_swag directory.
  2. Dynamic Documentation:

    • Combine with Laravel's route caching (php artisan route:cache) for better performance in production.
  3. Versioning:

    • Use route prefixes (e.g., /v1/api/docs) to document multiple API versions separately.
  4. Testing:

    • Write PHPUnit tests to validate annotations are correctly parsed:
      public function testAnnotationsAreParsed()
      {
          $reflection = new \ReflectionClass(UserController::class);
          $method = $reflection->getMethod('index');
          $docComment = $method->getDocComment();
          $this->assertStringContainsString('@api {get} /users', $docComment);
      }
      
  5. CI/CD:

    • Add a build step to validate annotations (e.g., using a custom Artisan command or GitHub Actions).

Gotchas and Tips

Pitfalls

  1. Annotation Parsing Issues:

    • Problem: Annotations may not render if PHPDoc syntax is incorrect (e.g., missing @ or malformed tags).
    • Fix: Validate annotations with tools like phpDocumentor or manually inspect the generated JSON (/api/docs/json).
  2. Route Mismatches:

    • Problem: @apiName or @api paths don’t match actual routes, causing broken links in Swagger UI.
    • Fix: Use named routes and ensure annotations reflect the exact route path (including parameters).
  3. Caching:

    • Problem: Changes to annotations aren’t reflected in Swagger UI due to route caching.
    • Fix: Clear route cache (php artisan route:clear) or disable caching in config/lara_swag.php during development:
      'cache' => env('APP_ENV') !== 'local',
      
  4. Beta Limitations:

    • Problem: The package is in beta; some features (e.g., advanced validation) may be unstable.
    • Fix: Check the NelmioApiDocBundle (mentioned in the README) for more stable alternatives if needed.
  5. Template Overrides:

    • Problem: Custom templates aren’t loading after publishing.
    • Fix: Ensure the publish command is run and templates are placed in resources/views/vendor/lara_swag. Clear view cache if necessary:
      php artisan view:clear
      

Debugging

  1. Inspect Generated JSON:

    • Visit /api/docs/json to see the raw Swagger JSON. Errors here will break Swagger UI.
    • Example error: Missing paths object due to unparsed annotations.
  2. Check Logs:

    • Enable debug mode (APP_DEBUG=true) and inspect Laravel logs (storage/logs/laravel.log) for annotation parsing errors.
  3. Validate Annotations:

    • Use a regex to search for unannotated controllers:
      grep -r "@api" app/Http/Controllers/ || echo "No annotations found!"
      

Extension Points

  1. Custom Annotations:

    • Extend the package by adding new annotation parsers. Override the ZQuintana\LaraSwag\Parser\AnnotationParser class or use Laravel’s service container to bind a custom parser.
  2. Post-Processing JSON:

    • Modify the Swagger JSON output by listening to the lara_swag.json event:
      Event::listen('lara_swag.json', function ($json) {
          $json['info']['title'] = 'Custom API Title';
          return $json;
      });
      
  3. Dynamic Tagging:

    • Use middleware to dynamically add tags or security definitions based on the request:
      public function handle($request, Closure $next)
      {
          if ($request->is('admin/*')) {
              $request->lara_swag_tags = ['Admin'];
          }
          return $next($request);
      }
      
  4. Integration with API Testing:

    • Use the generated Swagger JSON to drive API tests with tools like Pest or Laravel Dusk:
      public function testApiWithSwag()
      {
          $swagJson = file_get_contents(public_path('api/docs/json'));
          $data = json_decode($swagJson, true);
          // Assert endpoints exist, etc.
      }
      
  5. Localization:

    • Override Swagger UI translations by publishing and modifying the resources/lang/vendor/lara_swag directory.
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui