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

Auto-generate a Postman collection from your Laravel API routes. Supports Postman schema v2.1, configurable output, bearer token or basic auth for protected routes, and optional scaffolding of FormRequest rules for POST/PUT endpoints.

View on GitHub
Deep Wiki
Context7

Getting Started

  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 Export:

    php artisan export:postman
    
    • Outputs a Postman collection JSON file to storage/app/ (default: YYYY_MM_DD_HHMMSS_postman.json).
  3. Auth-Enabled Export (for protected APIs):

    php artisan export:postman --bearer="your_token_here"
    
    • Preconfigures Bearer token auth for all routes (overrides Basic Auth if both are provided).

Where to Look First

  • Config File: config/api-postman.php
    • Key settings: export_path, group_routes, enable_formdata, validation_format, continue_on_errors.
  • Route Groups: Check group_routes to organize routes by middleware (e.g., auth, api).
  • FormRequest Classes: For POST/PUT routes, ensure they extend Illuminate\Foundation\Http\FormRequest to auto-generate request bodies.
  • Route Parameters: Verify export_route_parameters to include route parameters (e.g., {id}) as path variables.

First Use Case: Onboarding New Developers

Generate a Postman collection to:

  1. Document all API endpoints in one click for new team members.
  2. Include auth headers for protected routes (e.g., --bearer).
  3. Scaffold request bodies for POST/PUT routes using FormRequest validation rules.
  4. Organize routes by middleware groups (e.g., auth:sanctum, api) for clarity.

Implementation Patterns

Workflow: API Documentation Pipeline

  1. Develop API:

    // routes/api.php
    Route::get('/users', [UserController::class, 'index'])->middleware('auth:sanctum');
    Route::post('/users', [UserController::class, 'store']);
    
    • Use FormRequest for validation:
      // app/Http/Requests/StoreUserRequest.php
      public function rules() {
          return [
              'name' => 'required|string|max:255',
              'email' => 'required|email|unique:users',
              'password' => 'required|string|min:8',
          ];
      }
      
  2. Configure Export:

    // config/api-postman.php
    return [
        'export_path' => storage_path('app/postman'),
        'group_routes' => true, // Group by middleware (e.g., "auth:sanctum")
        'enable_formdata' => true, // Scaffold request bodies
        'validation_format' => 'human', // Display rules in readable format
        'continue_on_errors' => false, // Stop on first error (default)
        'export_route_parameters' => true, // Include {id} as path variables
    ];
    
  3. Generate Collection:

    php artisan export:postman --bearer="1|abc123xyz" --basic="admin:password123"
    
    • Bearer Auth: Overrides Basic Auth if both are provided.
    • Basic Auth: Useful for legacy APIs or non-token-based auth.
  4. Integrate with CI/CD: Add to composer.json scripts:

    "scripts": {
        "post-install-cmd": [
            "php artisan export:postman --bearer=\"${BEARER_TOKEN}\""
        ]
    }
    
    • Store the generated Postman collection in a version-controlled directory (e.g., storage/app/postman).

Workflow: Testing API Endpoints

  1. Generate Collection:

    php artisan export:postman --bearer="test_token_123"
    
    • Use a test token for QA environments.
  2. Import into Postman:

    • Import the generated JSON file into Postman for manual testing or automation.
  3. Automate with Newman:

    npm install -g newman
    newman run storage/app/postman/YYYY_MM_DD_HHMMSS_postman.json --reporters cli,json
    
    • Run tests in CI/CD pipelines for regression testing.

Workflow: Extending Functionality

  1. Customize Request Bodies:

    • Override the default FormRequest scaffolding by extending the package:
      // app/Providers/PostmanGeneratorServiceProvider.php
      use AndreasElia\PostmanGenerator\PostmanGeneratorServiceProvider as BaseProvider;
      
      class PostmanGeneratorServiceProvider extends BaseProvider {
          public function register() {
              $this->app->singleton('postman-generator', function ($app) {
                  $generator = new \AndreasElia\PostmanGenerator\PostmanGenerator();
                  $generator->setCustomRequestBodyFormatter(
                      function ($request, $rules) {
                          // Custom logic to format request bodies
                          return ['custom' => 'formatted', 'data' => $rules];
                      }
                  );
                  return $generator;
              });
          }
      }
      
  2. Add Environment Variables:

    • Use the env config option to dynamically set variables:
      // config/api-postman.php
      'env' => [
          'base_url' => env('API_BASE_URL', 'http://localhost:8000'),
      ],
      
  3. Handle Errors Gracefully:

    • Set continue_on_errors to true to skip problematic routes:
      // config/api-postman.php
      'continue_on_errors' => true,
      

Integration Tips

  1. Laravel Sanctum:

    • Use Sanctum tokens for Bearer Auth:
      php artisan export:postman --bearer="1|$(php artisan sanctum:token)"
      
  2. Laravel Passport:

    • Generate tokens dynamically in a script:
      TOKEN=$(curl -X POST http://localhost:8000/oauth/token -d "grant_type=password&client_id=1&client_secret=secret&username=user&password=pass" | jq -r '.access_token')
      php artisan export:postman --bearer="$TOKEN"
      
  3. API Resources:

    • Use apiResources config to document API responses:
      // config/api-postman.php
      'api_resources' => [
          'users' => [
              'description' => 'User resource',
              'schema' => [
                  'type' => 'object',
                  'properties' => [
                      'id' => ['type' => 'integer'],
                      'name' => ['type' => 'string'],
                  ],
              ],
          ],
      ],
      
  4. Webhooks:

    • Exclude webhook routes from the collection:
      // config/api-postman.php
      'exclude_routes' => [
          'webhook.*',
      ],
      

Gotchas and Tips

Pitfalls

  1. Route Parameter Conflicts:

    • If export_route_parameters is true, ensure your Postman collection uses path variables (e.g., /users/{id}) instead of query parameters.
    • Fix: Disable export_route_parameters if your API uses query params for dynamic segments.
  2. FormRequest Issues:

    • If enable_formdata is true but request bodies aren’t generated, check:
      • The FormRequest class extends Illuminate\Foundation\Http\FormRequest.
      • The rules() method is properly defined.
    • Fix: Verify the FormRequest class is correctly imported and used in your controller.
  3. Auth Overrides:

    • Bearer Auth overrides Basic Auth if both are provided. Ensure you’re using the correct auth method for your API.
    • Fix: Test both auth methods separately to confirm behavior.
  4. Middleware Grouping:

    • If group_routes is true, routes are grouped by middleware (e.g., auth:sanctum). This may create unexpected folder structures in Postman.
    • Fix: Disable group_routes or customize the grouping logic in the service provider.
  5. Serialized Closures:

    • Older Laravel versions (e.g., 7.x) may have issues with serialized closures in routes.
    • Fix: Upgrade Laravel or use the containsSerializedClosure workaround from the package’s source.
  6. Validation Format:

    • The validation_format (human or raw) affects how rules are displayed in Postman descriptions.
    • Tip: Use human for readability in documentation; use raw for programmatic use.

Debugging

  1. Check Route Collection:

    • Inspect the routes being exported:
      php artisan route:list
      
    • Compare with the generated Postman collection to identify missing or misconfigured routes.
  2. Enable Verbose Output:

    • Run the command with -v for debugging:
      php artisan export:post
      
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