PHPackages                             stackmasteraliza/laravel-api-response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. stackmasteraliza/laravel-api-response

ActiveLibrary[HTTP &amp; Networking](/categories/http)

stackmasteraliza/laravel-api-response
=====================================

A clean, fluent, and consistent API response builder for Laravel 10/11/12. Features standardized JSON responses, automatic pagination metadata, built-in exception handling, validation error formatting, and a convenient trait for controllers.

v4.7.0(3mo ago)2942↓100%4MITPHPPHP ^8.1CI passing

Since Dec 29Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/stackmasteraliza/laravel-api-response-builder)[ Packagist](https://packagist.org/packages/stackmasteraliza/laravel-api-response)[ RSS](/packages/stackmasteraliza-laravel-api-response/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (42)Used By (0)

 [![Laravel API Toolkit](docs/images/logo-banner.svg)](docs/images/logo-banner.svg)

 [![Tests](https://camo.githubusercontent.com/214930dd574621ac62e96dbd4d3060592e9a26c296be4fb76e2fc63fe85546ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f54657374732d50617373696e672d627269676874677265656e)](https://camo.githubusercontent.com/214930dd574621ac62e96dbd4d3060592e9a26c296be4fb76e2fc63fe85546ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f54657374732d50617373696e672d627269676874677265656e) [![Latest Version on Packagist](https://camo.githubusercontent.com/b67738bbeae14c6f8f3f149f5c35258ea25b3f0345f082715034a607e360a83f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f737461636b6d6173746572616c697a612f6c61726176656c2d6170692d726573706f6e73652e737667)](https://packagist.org/packages/stackmasteraliza/laravel-api-response) [![Total Downloads](https://camo.githubusercontent.com/c7087ce81fe173cb6dfdda126f94b4031b2091ae13b19831429e73a4793d4478/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f737461636b6d6173746572616c697a612f6c61726176656c2d6170692d726573706f6e73652e737667)](https://packagist.org/packages/stackmasteraliza/laravel-api-response) [![DOI](https://camo.githubusercontent.com/da128ff0751a1f1864c820c9c2bd86833ecc8c685645f0b42ffecce43156a84c/68747470733a2f2f7a656e6f646f2e6f72672f62616467652f444f492f31302e353238312f7a656e6f646f2e31383230343431352e737667)](https://doi.org/10.5281/zenodo.18204415) [![License](https://camo.githubusercontent.com/aebc0ebd9757472cc53bb559f8649315f9351fef98925b6491de37dcda16ed8a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f737461636b6d6173746572616c697a612f6c61726176656c2d6170692d726573706f6e73652e737667)](https://packagist.org/packages/stackmasteraliza/laravel-api-response) [![Laravel News](https://camo.githubusercontent.com/bef61daa81d747fb7762152808d2d5e92956cbb98178967dd362ef70c744a874/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2532304e6577732d46656174757265642d6f72616e6765)](https://laravel-news.com) [![PHP Version](https://camo.githubusercontent.com/3a73e2280ec14e7ba71344d0c7bcdf21c2f95f4bd8ee037a42fdbd89da744e65/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d373737424234)](https://camo.githubusercontent.com/3a73e2280ec14e7ba71344d0c7bcdf21c2f95f4bd8ee037a42fdbd89da744e65/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d373737424234) [![Laravel Version](https://camo.githubusercontent.com/a0cfcd4ae10ce58c14aafcab200fa0c44994a20f1da44fa3ae27efbca47abb51/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d3130253230253743253230313125323025374325323031322d464632443230)](https://camo.githubusercontent.com/a0cfcd4ae10ce58c14aafcab200fa0c44994a20f1da44fa3ae27efbca47abb51/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d3130253230253743253230313125323025374325323031322d464632443230)

Laravel API Toolkit
===================

[](#laravel-api-toolkit)

### `stackmasteraliza/laravel-api-response`

[](#stackmasteralizalaravel-api-response)

> The all-in-one Laravel API solution: Standardized Responses + Auto-generated Swagger Docs + Export to Postman &amp; Insomnia

A clean and consistent API response builder for Laravel applications. This package provides a simple and elegant way to build standardized JSON responses for your APIs with zero-config OpenAPI documentation.

 [ ![Aliza Ali](https://camo.githubusercontent.com/d24e7e8cbb50c702fe6b3a2418431d7f64a19903ad1bfc4c4addfc22227b5f75/68747470733a2f2f696d616765732e7765736572762e6e6c2f3f75726c3d6769746875622e636f6d2f737461636b6d6173746572616c697a612e706e6726773d383026683d3830266669743d636f766572266d61736b3d636972636c65) ](https://github.com/stackmasteraliza)
 **Developed by [Aliza Ali](https://github.com/stackmasteraliza)**
 Creator &amp; Maintainer

Features
--------

[](#features)

- Consistent API response structure
- HTTP status code included in response body
- Fluent interface for building responses
- Built-in methods for common HTTP status codes
- Automatic pagination metadata (including cursor pagination)
- **Auto-generated OpenAPI/Swagger documentation**
- **API versioning support (v1, v2, etc.) with version switcher UI**
- **Built-in WebSocket tester in Swagger UI**
- **Export to Postman, Insomnia, JSON &amp; YAML**
- Response macros for custom response types
- Testing helpers for API assertions
- Exception handler for consistent error responses
- Facade and Trait support
- Fully customizable via config

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require stackmasteraliza/laravel-api-response
```

The package will automatically register itself.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --tag=api-response-config
```

Usage
-----

[](#usage)

### Using the Facade

[](#using-the-facade)

```
use Stackmasteraliza\ApiResponse\Facades\ApiResponse;

// Success response
return ApiResponse::success($data, 'Data retrieved successfully');

// Error response
return ApiResponse::error('Something went wrong', 400);

// Created response (201)
return ApiResponse::created($user, 'User created successfully');

// Not found response (404)
return ApiResponse::notFound('User not found');

// Validation error response (422)
return ApiResponse::validationError([
    'email' => ['The email field is required.'],
    'name' => ['The name field is required.'],
]);
```

### Using the Trait

[](#using-the-trait)

```
use Stackmasteraliza\ApiResponse\Traits\HasApiResponse;

class UserController extends Controller
{
    use HasApiResponse;

    public function index()
    {
        $users = User::paginate(15);

        return $this->success($users, 'Users retrieved successfully');
    }

    public function store(Request $request)
    {
        $user = User::create($request->validated());

        return $this->created($user, 'User created successfully');
    }

    public function show(User $user)
    {
        return $this->success($user);
    }

    public function destroy(User $user)
    {
        $user->delete();

        return $this->noContent();
    }
}
```

### Available Methods

[](#available-methods)

#### Success Responses

[](#success-responses)

MethodStatus CodeDescription`success($data, $message, $statusCode)`200General success response`created($data, $message)`201Resource created`accepted($data, $message)`202Request accepted for processing`noContent()`204No content to return#### Error Responses

[](#error-responses)

MethodStatus CodeDescription`error($message, $statusCode, $errors)`VariableGeneral error response`badRequest($message, $errors)`400Bad request`unauthorized($message)`401Unauthorized`forbidden($message)`403Forbidden`notFound($message)`404Resource not found`methodNotAllowed($message)`405Method not allowed`conflict($message, $errors)`409Conflict`unprocessable($message, $errors)`422Unprocessable entity`validationError($errors, $message)`422Validation failed`tooManyRequests($message, $retryAfter)`429Too many requests`serverError($message)`500Internal server error`serviceUnavailable($message)`503Service unavailable### Response Structure

[](#response-structure)

#### Success Response

[](#success-response)

```
{
    "status_code": 200,
    "success": true,
    "message": "Data retrieved successfully",
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    }
}
```

#### Paginated Response

[](#paginated-response)

```
{
    "status_code": 200,
    "success": true,
    "message": "Users retrieved successfully",
    "data": [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Jane Doe"}
    ],
    "meta": {
        "current_page": 1,
        "per_page": 15,
        "total": 50,
        "last_page": 4,
        "from": 1,
        "to": 15,
        "path": "http://example.com/api/users",
        "links": {
            "first": "http://example.com/api/users?page=1",
            "last": "http://example.com/api/users?page=4",
            "prev": null,
            "next": "http://example.com/api/users?page=2"
        }
    }
}
```

#### Cursor Paginated Response

[](#cursor-paginated-response)

Cursor pagination is more efficient for large datasets:

```
$users = User::cursorPaginate(15);
return ApiResponse::success($users, 'Users retrieved successfully');
```

```
{
    "status_code": 200,
    "success": true,
    "message": "Users retrieved successfully",
    "data": [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Jane Doe"}
    ],
    "meta": {
        "per_page": 15,
        "next_cursor": "eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0",
        "prev_cursor": null,
        "path": "http://example.com/api/users",
        "links": {
            "next": "http://example.com/api/users?cursor=eyJpZCI6MTUuLi4",
            "prev": null
        }
    }
}
```

#### Error Response

[](#error-response)

```
{
    "status_code": 422,
    "success": false,
    "message": "Validation failed",
    "errors": {
        "email": ["The email field is required."],
        "name": ["The name field is required."]
    }
}
```

### Exception Handling

[](#exception-handling)

To use the built-in exception handler, update your `bootstrap/app.php` (Laravel 11+):

```
use Stackmasteraliza\ApiResponse\Exceptions\ApiExceptionHandler;

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (Throwable $e, Request $request) {
        $handler = new ApiExceptionHandler();
        return $handler->handle($e, $request);
    });
})
```

Or for Laravel 10, update your `app/Exceptions/Handler.php`:

```
use Stackmasteraliza\ApiResponse\Exceptions\ApiExceptionHandler;

public function render($request, Throwable $exception)
{
    $handler = new ApiExceptionHandler();
    $response = $handler->handle($exception, $request);

    if ($response) {
        return $response;
    }

    return parent::render($request, $exception);
}
```

### Middleware

[](#middleware)

Use the `ForceJsonResponse` middleware to ensure all API responses are JSON:

```
// In your route file or middleware group
use Stackmasteraliza\ApiResponse\Http\Middleware\ForceJsonResponse;

Route::middleware([ForceJsonResponse::class])->group(function () {
    // Your API routes
});
```

### Adding Custom Data

[](#adding-custom-data)

```
return ApiResponse::success($user)
    ->withData('token', $token)
    ->withHeader('X-Custom-Header', 'value');
```

### Response Macros

[](#response-macros)

Define reusable custom response types using macros:

```
// In your AppServiceProvider boot() method
use Stackmasteraliza\ApiResponse\Facades\ApiResponse;

ApiResponse::macro('banned', function (string $reason = 'Account suspended') {
    return $this->error($reason, 403);
});

ApiResponse::macro('maintenance', function () {
    return $this->error('Service under maintenance', 503);
});
```

Usage:

```
return ApiResponse::banned('Your account has been suspended');
return ApiResponse::maintenance();
```

### Testing Helpers

[](#testing-helpers)

The package provides convenient testing assertions for your API tests:

```
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function test_can_list_users()
    {
        $response = $this->getJson('/api/users');

        $response->assertApiSuccess()
                 ->assertApiStatusCode(200)
                 ->assertApiMessage('Users retrieved successfully')
                 ->assertApiHasData()
                 ->assertApiPaginated();
    }

    public function test_validation_errors()
    {
        $response = $this->postJson('/api/users', []);

        $response->assertApiError(422)
                 ->assertApiMessage('Validation failed')
                 ->assertApiHasErrors('email');
    }

    public function test_user_data()
    {
        $response = $this->getJson('/api/users/1');

        $response->assertApiSuccess()
                 ->assertApiDataContains(['id' => 1, 'name' => 'John Doe']);
    }
}
```

#### Available Test Assertions

[](#available-test-assertions)

MethodDescription`assertApiSuccess()`Assert response has `success: true``assertApiError($statusCode)`Assert response has `success: false` and optional status code`assertApiStatusCode($code)`Assert status code in response body`assertApiMessage($message)`Assert response message`assertApiHasData($key)`Assert data exists (optionally check for specific key)`assertApiDataCount($count)`Assert data array has specific count`assertApiData($expected)`Assert data equals expected array`assertApiDataContains($expected)`Assert data contains expected subset`assertApiPaginated()`Assert response has pagination meta`assertApiCursorPaginated()`Assert response has cursor pagination meta`assertApiHasErrors($key)`Assert errors exist (optionally check for specific key)OpenAPI/Swagger Documentation
-----------------------------

[](#openapiswagger-documentation)

The package automatically generates OpenAPI 3.0 documentation from your API routes with a beautiful, modern dark-themed UI - **no additional coding required!**

[![Swagger UI Screenshot](docs/images/swagger-ui-screenshot.png)](docs/images/swagger-ui-screenshot.png)

### Export to Multiple Formats

[](#export-to-multiple-formats)

Export your API documentation to Postman, Insomnia, JSON, or YAML with a single click.

[![Export Dropdown](docs/images/swagger-ui-screenshot-export.png)](docs/images/swagger-ui-screenshot-export.png)

### Built-in Authorization

[](#built-in-authorization)

Easily configure Bearer Token or API Key authentication directly from the UI.

[![Authorization Modal](docs/images/swagger-ui-screenshot-auth.png)](docs/images/swagger-ui-screenshot-auth.png)

### WebSocket Tester

[](#websocket-tester)

Test WebSocket connections directly from the documentation with real-time message sending and receiving.

[![WebSocket Tester](docs/images/swagger-ui-screenshot-websocket.png)](docs/images/swagger-ui-screenshot-websocket.png)

### Zero-Configuration Auto-Generation

[](#zero-configuration-auto-generation)

The package intelligently generates documentation by:

- **Detecting ApiResponse method calls** - Scans your controller code for `ApiResponse::success()`, `ApiResponse::created()`, etc. and automatically determines response status codes
- **Extracting FormRequest validation rules** (optional) - If your controller methods use FormRequest classes, validation rules are automatically converted to OpenAPI request body schemas
- **Inferring from route patterns** - Resource controller methods (`index`, `show`, `store`, `update`, `destroy`) get meaningful summaries and descriptions
- **Detecting pagination** - Automatically identifies paginated responses when using `->paginate()` or `->cursorPaginate()`

**No FormRequest or PHP attributes required!** Just write your Laravel code normally and get instant API documentation.

> **Note:** FormRequest classes are completely optional. If you don't use them, the package will still generate documentation - it will just show a generic request body schema for POST/PUT/PATCH endpoints. Using FormRequest simply provides richer, more detailed request body documentation.

### View Documentation

[](#view-documentation)

Simply visit `/api-docs` in your browser to see the interactive Swagger UI:

```
http://your-app.com/api-docs

```

### Custom Swagger UI Features

[](#custom-swagger-ui-features)

The package includes a beautifully designed custom Swagger UI with:

- **Theme Support** - Dark, Light, and Auto (system preference) themes with toggle button
- **Custom Branding** - Display your app name and logo in the header
- **Hero Section** - Welcome message with live API statistics (endpoints, categories, schemas)
- **Search Bar** - Filter APIs by path, method, or description
- **Authorization Modal** - Support for Bearer Token and API Key authentication with localStorage persistence
- **Export Options** - Export API documentation in multiple formats (JSON, YAML, Postman, Insomnia)
- **Responsive Design** - Works great on desktop and mobile devices
- **Method Badges** - Color-coded HTTP method indicators (GET, POST, PUT, DELETE, PATCH)

### Export API Documentation

[](#export-api-documentation)

Export your API documentation directly from the Swagger UI to import into your preferred tools. Click the **Export** button in the header to access the following formats:

#### OpenAPI Specification

[](#openapi-specification)

- **OpenAPI JSON** - Standard JSON format compatible with any OpenAPI 3.0 tool
- **OpenAPI YAML** - Human-readable YAML format for easier editing and version control

#### API Client Collections

[](#api-client-collections)

- **Postman Collection (v2.1)** - Ready to import into Postman with:

    - Organized folders by API tags/categories
    - Pre-configured base URL as collection variable
    - Request bodies with auto-generated example data
    - Query parameters, path variables, and headers
- **Insomnia Collection (v4)** - Ready to import into Insomnia with:

    - Workspace and environment setup
    - Organized request groups by tags
    - Base URL as environment variable
    - Full request configuration

All exports are generated client-side for instant downloads with no server load.

### Customization

[](#customization)

Configure the Swagger UI appearance in your `.env` file:

```
# App branding
API_DOCS_APP_NAME=My Awesome API
API_DOCS_APP_LOGO=https://example.com/logo.png

# Theme color (default: #10b981 - green)
API_DOCS_THEME_COLOR=#10b981

# Default theme: dark, light, or auto (default: auto)
API_DOCS_DEFAULT_THEME=auto

# Enable/disable documentation
API_DOCS_ENABLED=true
```

Or in your config file:

```
// config/api-response.php

'openapi' => [
    'enabled' => env('API_DOCS_ENABLED', true),
    'title' => env('API_DOCS_TITLE', 'API Documentation'),
    'description' => 'Auto-generated API documentation',
    'version' => '1.0.0',
    'route_prefix' => 'api',
    'docs_route' => 'api-docs',

    // Custom branding
    'app_name' => env('API_DOCS_APP_NAME', env('APP_NAME', 'API')),
    'app_logo' => env('API_DOCS_APP_LOGO', null),
    'theme_color' => env('API_DOCS_THEME_COLOR', '#10b981'),
    'default_theme' => env('API_DOCS_DEFAULT_THEME', 'auto'), // dark, light, auto

    'servers' => [
        ['url' => env('APP_URL'), 'description' => 'API Server'],
    ],
],
```

### API Endpoints

[](#api-endpoints)

EndpointDescription`GET /api-docs`Interactive Swagger UI`GET /api-docs/openapi.json`Raw OpenAPI 3.0 specification### Generate Static File

[](#generate-static-file)

Generate a static OpenAPI JSON file:

```
php artisan api:docs
```

This creates `public/api-docs/openapi.json` that you can use with any OpenAPI-compatible tool.

### Enhanced Documentation with Attributes (Optional)

[](#enhanced-documentation-with-attributes-optional)

For more detailed or customized documentation, you can optionally add PHP attributes to your controller methods:

```
use Stackmasteraliza\ApiResponse\Attributes\ApiEndpoint;
use Stackmasteraliza\ApiResponse\Attributes\ApiRequest;
use Stackmasteraliza\ApiResponse\Attributes\ApiRequestBody;
use Stackmasteraliza\ApiResponse\Attributes\ApiResponse;

class UserController extends Controller
{
    #[ApiEndpoint(
        summary: 'List all users',
        description: 'Retrieve a paginated list of all users in the system',
        tags: ['Users']
    )]
    #[ApiRequest(name: 'page', type: 'integer', in: 'query', description: 'Page number')]
    #[ApiRequest(name: 'per_page', type: 'integer', in: 'query', description: 'Items per page')]
    #[ApiResponse(status: 200, description: 'Users retrieved successfully', ref: 'PaginatedResponse')]
    public function index(): JsonResponse
    {
        return ApiResponse::success(User::paginate(15));
    }

    #[ApiEndpoint(
        summary: 'Create a new user',
        description: 'Create a new user in the system',
        tags: ['Users']
    )]
    #[ApiRequestBody(
        properties: ['name' => 'string', 'email' => 'string', 'password' => 'string'],
        required: ['name', 'email', 'password'],
        example: ['name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'secret']
    )]
    #[ApiResponse(status: 201, description: 'User created successfully')]
    #[ApiResponse(status: 422, description: 'Validation error', ref: 'ValidationErrorResponse')]
    public function store(Request $request): JsonResponse
    {
        $user = User::create($request->validated());
        return ApiResponse::created($user);
    }
}
```

### Available Attributes

[](#available-attributes)

AttributeTargetDescription`#[ApiEndpoint]`MethodDefine summary, description, tags, deprecated status`#[ApiRequest]`MethodDefine query/path parameters`#[ApiRequestBody]`MethodDefine request body schema`#[ApiResponse]`MethodDefine response status, description, example### Built-in Schema References

[](#built-in-schema-references)

Use these in `#[ApiResponse(ref: '...')]`:

- `SuccessResponse` - Standard success response
- `ErrorResponse` - Standard error response
- `PaginatedResponse` - Paginated list response
- `ValidationErrorResponse` - Validation error with field errors

Configuration
-------------

[](#configuration)

```
return [
    // Default messages
    'default_success_message' => 'Success',
    'default_error_message' => 'Error',

    // Include debug info in error responses (when APP_DEBUG=true)
    'include_debug_info' => env('API_RESPONSE_DEBUG', false),

    // Include HTTP status code in response body
    'include_status_code' => env('API_RESPONSE_INCLUDE_STATUS_CODE', true),

    // Customize response keys
    'keys' => [
        'success' => 'success',
        'message' => 'message',
        'data' => 'data',
        'errors' => 'errors',
        'meta' => 'meta',
        'status_code' => 'status_code',
    ],
];
```

### Disabling Status Code in Response Body

[](#disabling-status-code-in-response-body)

If you prefer not to include the status code in the response body, you can disable it:

```
API_RESPONSE_INCLUDE_STATUS_CODE=false
```

Or in your config file:

```
'include_status_code' => false,
```

### API Versioning

[](#api-versioning)

The package supports versioned API documentation. When enabled, it auto-detects version prefixes from your routes (e.g., `api/v1/*`, `api/v2/*`) and generates separate OpenAPI specs for each version with a version switcher in the Swagger UI.

#### Enable Versioning

[](#enable-versioning)

Add to your `.env` file:

```
API_DOCS_VERSIONING=true
```

Or in your config file (`config/api-response.php`):

```
'openapi' => [
    // ... other options

    'versioning' => [
        'enabled' => true,
        'auto_detect' => true,
        'default_version' => 'v2', // Optional: set default version
    ],
],
```

#### Custom Version Definitions

[](#custom-version-definitions)

For more control, you can define custom version patterns:

```
'versioning' => [
    'enabled' => true,
    'auto_detect' => false,
    'default_version' => 'v2',
    'versions' => [
        'v1' => [
            'title' => 'API v1 (Legacy)',
            'description' => 'Legacy API version - deprecated',
            'pattern' => 'api/v1/*',
        ],
        'v2' => [
            'title' => 'API v2 (Current)',
            'description' => 'Current stable API version',
            'pattern' => 'api/v2/*',
        ],
    ],
],
```

#### Versioned Endpoints

[](#versioned-endpoints)

When versioning is enabled, the following endpoints become available:

EndpointDescription`/api-docs`Swagger UI with version switcher`/api-docs/openapi.json`Full OpenAPI spec (all versions)`/api-docs/versions`List of available versions`/api-docs/v1/openapi.json`OpenAPI spec for v1 only`/api-docs/v2/openapi.json`OpenAPI spec for v2 only### WebSocket Testing

[](#websocket-testing)

The Swagger UI includes a built-in WebSocket tester for testing real-time connections directly from the documentation.

#### Features

[](#features-1)

- Connect to any WebSocket endpoint
- Send and receive messages in real-time
- Pre-built message templates (Subscribe, Unsubscribe, Ping, Client Event)
- Message history with timestamps
- Connection state persistence

#### Configuration

[](#configuration-1)

```
'openapi' => [
    'websocket' => [
        'enabled' => true,
        'url' => env('WEBSOCKET_URL', 'ws://localhost:6001'),
        'endpoints' => [],
    ],
],
```

Click the **WebSocket** button in the Swagger UI header to open the tester.

Testing
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

45

—

FairBetter than 92% of packages

Maintenance85

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

40

Last Release

104d ago

Major Versions

v1.9.0 → v2.0.02025-12-30

v2.9.9 → v3.0.02025-12-31

3.9.1 → 4.1.02026-01-10

### Community

Maintainers

![](https://www.gravatar.com/avatar/ca494501f49ea13fff6a97045744f2b9e08481b087ec1385d233024f28a1a424?d=identicon)[stackmasteraliza](/maintainers/stackmasteraliza)

---

Top Contributors

[![stackmasteraliza](https://avatars.githubusercontent.com/u/151018015?v=4)](https://github.com/stackmasteraliza "stackmasteraliza (44 commits)")

---

Tags

apiapi-builderapi-responsecomposer-packagejsonlaravellaravel-packagelaravel10laravel11laravel12opensourcephpphp8response-builderrestrest-apirestfulstackmasteralizaresponsephpjsonapilaravelvalidationrestpaginationlaravel-packageREST APIrestfulexception handlerhttp-responseapi-responsejson-responsestackmasteraliza

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/stackmasteraliza-laravel-api-response/health.svg)

```
[![Health](https://phpackages.com/badges/stackmasteraliza-laravel-api-response/health.svg)](https://phpackages.com/packages/stackmasteraliza-laravel-api-response)
```

###  Alternatives

[guanguans/laravel-api-response

Normalize and standardize Laravel API response data structure. - 规范化和标准化 Laravel API 响应数据结构。

485.6k](/packages/guanguans-laravel-api-response)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
