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 Api To Postman Laravel Package

andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API routes. Export to storage/app with an artisan command, configurable output, optional FormRequest scaffolding and rules, and support for Bearer tokens or Basic Auth for routes behind auth middleware.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require andreaselia/laravel-api-to-postman
    php artisan vendor:publish --provider="AndreasElia\PostmanGenerator\PostmanGeneratorServiceProvider"
    
    • Publishes the api-postman.php config file to config/.
  2. First Run:

    php artisan export:postman
    
    • Generates a Postman collection (postman.json) in storage/app.
  3. First Use Case:

    • Import the generated JSON into Postman to test your API endpoints interactively.
    • Useful for onboarding new developers or documenting API contracts without manual effort.

Implementation Patterns

Core Workflows

  1. API Documentation Sync:

    • Pattern: Run export:postman in your CI pipeline (e.g., post-deploy) to auto-update Postman collections.
    • Example:
      # GitHub Actions
      - name: Export Postman Collection
        run: php artisan export:postman --bearer="${{ secrets.API_TOKEN }}"
      
    • Benefit: Ensures Postman collections reflect the latest API routes, reducing documentation drift.
  2. Protected Endpoint Testing:

    • Pattern: Pass auth tokens via CLI flags:
      php artisan export:postman --bearer="1|abc123" --basic="user:pass"
      
    • Use Case: Generate collections for QA teams or internal tools with pre-configured auth.
  3. FormRequest Scaffolding:

    • Pattern: Enable enable_formdata in api-postman.php to auto-generate request bodies from validation rules.
      'enable_formdata' => true,
      'formdata_format' => 'raw', // or 'human'
      
    • Example Output:
      {
        "body": {
          "mode": "raw",
          "raw": {
            "language": "json",
            "data": {
              "email": "required|email",
              "password": "required|min:8"
            }
          }
        }
      }
      
    • Use Case: Frontend teams can copy-paste validation rules directly into their forms.
  4. CRUD Folder Structuring:

    • Pattern: Group routes by resource (e.g., /users, /orders) using group_by_resource:
      'group_by_resource' => true,
      
    • Example Output:
      /Users
        - GET /users
        - POST /users
        - GET /users/{id}
      /Orders
        - GET /orders
        ...
      
    • Use Case: Improves Postman organization for large APIs.
  5. Environment-Specific Exports:

    • Pattern: Override config per environment (e.g., config/api-postman-staging.php) and use:
      php artisan export:postman --config=api-postman-staging
      
    • Use Case: Generate staging-specific collections with different auth tokens.

Integration Tips

  1. Laravel Events:

    • Trigger exports after route changes:
      // In a service provider
      Route::macro('exportPostman', function () {
          Artisan::call('export:postman');
      });
      
    • Useful for real-time documentation updates.
  2. Custom Metadata:

    • Extend the collection with custom fields (e.g., x-api-version):
      // In a service provider
      PostmanGenerator::extend(function ($collection) {
          $collection->setInfo('version', 'v2.0.0');
      });
      
  3. Exclude Routes:

    • Filter routes via ignore_routes in config:
      'ignore_routes' => [
          'admin.*',
          'webhook.*',
      ],
      
    • Use Case: Hide internal endpoints or webhooks from public collections.
  4. Postman Variables:

    • Use {{base_url}} in Postman and set it dynamically:
      php artisan export:postman --base-url="https://api.staging.example.com"
      

Gotchas and Tips

Pitfalls

  1. Auth Precedence:

    • Gotcha: If both --bearer and --basic are provided, Bearer auth takes precedence.
    • Fix: Use --basic alone for Basic Auth-only collections.
  2. FormRequest Limitations:

    • Gotcha: Only works for POST/PUT routes using Laravel’s FormRequest class.
    • Fix: Manually add request bodies for non-FormRequest routes or use enable_formdata: false.
  3. Route Caching:

    • Gotcha: Laravel’s route caching (php artisan route:cache) may cause stale exports.
    • Fix: Run php artisan route:clear before exporting or disable caching temporarily.
  4. Nested Resources:

    • Gotcha: Deeply nested resources (e.g., /users/{user}/posts/{post}) may generate unclear folder structures.
    • Fix: Use group_by_resource: false or customize the folder_name callback in config.
  5. Special Characters in URIs:

    • Gotcha: Routes with special characters (e.g., /user/profile/{name}) may break Postman imports.
    • Fix: URL-encode dynamic segments or use uri_encoding: 'strict' in config.
  6. Large APIs:

    • Gotcha: Collections with >1000 routes may hit Postman’s import limits.
    • Fix: Split into multiple collections using split_by_folder: true.

Debugging

  1. Verbose Output:

    • Enable debug mode in api-postman.php:
      'debug' => true,
      
    • Logs route parsing details to storage/logs/laravel.log.
  2. Validate JSON:

  3. Test with curl:

    • Verify endpoints work before importing:
      curl -X GET http://your-api.com/users -H "Authorization: Bearer 1|abc123"
      

Extension Points

  1. Custom Collection Info:

    • Override the collection’s info object:
      // In a service provider
      PostmanGenerator::extend(function ($collection) {
          $collection->setInfo('name', 'My API - Staging');
          $collection->setInfo('description', 'Staging environment for My API');
      });
      
  2. Dynamic Auth Tokens:

    • Fetch tokens from environment variables:
      php artisan export:postman --bearer="$STAGING_API_TOKEN"
      
  3. Post-Processing:

    • Modify the generated JSON with a post-export script:
      $collection = json_decode(file_get_contents(storage_path('app/postman.json')), true);
      // Add custom fields...
      file_put_contents(storage_path('app/postman.json'), json_encode($collection));
      
  4. Custom Folder Names:

    • Rename folders dynamically:
      'folder_name' => function ($route) {
          return str_replace('api/', '', $route->getPrefix());
      },
      
  5. Event Listeners:

    • Listen to the postman.export event to modify the collection:
      Event::listen('postman.export', function ($collection) {
          $collection->addFolder('Custom', [
              // Add custom requests...
          ]);
      });
      

Pro Tips

  1. Versioned Collections:

    • Append a timestamp to filenames:
      'filename' => 'postman-' . date('Y-m-d') . '.json',
      
    • Useful for tracking API changes over time.
  2. Postman Environment Variables:

    • Reference variables in the collection:
      {
        "url": "{{base_url}}/users",
        "header": [
          { "key": "Authorization", "value": "{{token}}" }
        ]
      }
      
  3. API Contract Testing:

    • Combine with Pest/PHPUnit to validate Postman collections against API specs:
      public function test_postman_collection()
      {
          $collection = Artisan::call('export:postman', [], $output);
          $this->assertJson($output);
      }
      
  4. Git LFS for Large Collections:

    • Store Postman collections in Git LFS if they exceed Git’s file size limits.
  5. Postman Monitor Integration:

    • Use the generated collection in Postman Monitor for uptime checks:
      php artisan export:postman --base-url="https://api.production.example.com"
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport