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

Json Api Laravel Package

neomerx/json-api

Framework-agnostic PHP library implementing JSON:API v1.1. Builds compliant documents, relationships, compound includes, meta and errors. Parses/validates Accept/Content-Type and query params (pagination, sorting, sparse fields) to return proper 415/406 responses.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:
    • Framework-agnostic: Fits seamlessly into Laravel’s ecosystem while avoiding framework-specific bloat (e.g., no Laravel Service Provider dependency).
    • JSON API v1.1 compliance: Aligns with modern API standards, reducing frontend/backend friction (e.g., works natively with Ember Data, Apollo Client).
    • Schema-driven design: Encourages separation of concerns via Schema classes (e.g., AuthorSchema), mirroring Laravel’s Eloquent model structure.
    • Performance: 2.3–5.4x faster than v2.x (per release notes), critical for high-traffic APIs.
    • Validation: Automates Content-Type, Accept headers, and query parameter parsing (e.g., pagination, filtering), reducing boilerplate in Laravel middleware/controllers.
  • Cons:
    • No active maintenance: Last release in 2020 (3+ years stale). Risk of compatibility issues with PHP 8.x/Laravel 9+ (e.g., typed properties, attributes).
    • Laravel-specific gaps: Lacks native integration with Laravel’s:
      • Request/Response lifecycle (e.g., no built-in middleware for JSON API headers).
      • Authentication (e.g., Sanctum/Passport; requires manual integration).
      • Database layer (e.g., Eloquent relationships must be manually mapped to Schema methods).
    • Monolithic design: Tight coupling between encoding/decoding/validation may complicate partial adoption (e.g., using only the encoder without the full stack).

Integration Feasibility

  • Laravel Compatibility:
    • High for PHP 7.1–8.0: Works with Laravel 6–8.x (PHP 7.1+). PHP 8.1+ may need polyfills for deprecated features (e.g., array_column).
    • Middleware Integration: Can be wrapped in Laravel middleware to validate Content-Type/Accept headers and parse query params (e.g., include, fields).
    • Service Container: Register the package as a singleton in AppServiceProvider for global access to Encoder, Decoder, and ErrorHandler.
    • Route Binding: Useful for resourceful routes (e.g., {resource}Encoder::encodeData($resource)).
  • Database Layer:
    • Eloquent Support: Requires manual mapping of Eloquent models to Schema classes (e.g., getAttributes()model->toArray()). No ORM-specific optimizations.
    • Relationships: Supports hasMany, belongsTo, etc., but requires explicit configuration in getRelationships() (e.g., self::RELATIONSHIP_DATA => $author->comments).
  • Testing:
    • 100% test coverage: Reduces risk of edge-case bugs but doesn’t account for Laravel-specific interactions.

Technical Risk

  • Breaking Changes:
    • PHP 8.x: Potential issues with:
      • Typed properties (e.g., SchemaInterface::getType(): string may conflict with PHP 8.1’s stricter type system).
      • Deprecated functions (e.g., json_encode without JSON_THROW_ON_ERROR flag).
    • Laravel 9+: Changes to request/response handling (e.g., Symfony HTTP Message interfaces) may require adapters.
  • Performance Overhead:
    • Serialization: Context-aware encoding (e.g., ContextInterface) adds minor overhead but is negligible for most use cases.
    • Validation: Query parameter parsing (e.g., include, sort) is efficient but may slow down complex APIs with deep nesting.
  • Security:
    • No built-in auth: Requires manual integration with Laravel’s auth systems (e.g., Sanctum, Passport).
    • Error Handling: Custom errors must be manually converted to JSON API format (though ErrorCollection provides helpers).
  • Long-Term Viability:
    • Frozen at v1.1: JSON API v1.2+ features (e.g., new media types, conditional requests) are unsupported. May need a replacement in 2–3 years.
    • No Laravel-specific updates: Risk of divergence if Laravel evolves (e.g., Symfony 6+ HTTP components).

Key Questions

  1. PHP/Laravel Version Support:
    • Does your team use PHP 8.1+ or Laravel 9+? If yes, test compatibility or plan for polyfills.
    • Example: Add return_type_declaration polyfills for PHP 7.1–7.4 if using PHP 8.1+.
  2. Adoption Scope:
    • Will you use the full stack (decoder + encoder + validation) or just the encoder? Partial adoption may require custom middleware.
  3. Relationship Complexity:
    • Do you have polymorphic relationships or circular references? The package supports these but requires careful Schema configuration.
  4. Authentication:
    • How will you integrate auth? Options:
      • Middleware to validate Bearer tokens before decoding.
      • Custom ContextInterface to inject auth data (e.g., user ID).
  5. Error Handling:
    • Will you use the package’s Error class or Laravel’s HttpResponse exceptions? Plan for consistency.
  6. Performance Baseline:
    • Benchmark serialization/deserialization against alternatives like spatie/laravel-fractal or nesbot/json-api-php.
  7. Migration Path:
    • If replacing an existing API, how will you handle:
      • Legacy endpoints (e.g., /api/v1/posts vs. /api/v2/posts).
      • Non-JSON API clients (e.g., mobile apps using GraphQL)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Encoder: Replace Laravel’s Response::json() with Encoder::encodeData() for standardized responses.
    • Decoder: Use in controllers to parse requests (e.g., Decoder::decodeData($request->getContent())).
    • Validation: Replace manual Content-Type checks with the package’s MediaTypeParser.
    • Middleware: Create a JsonApiMiddleware to:
      • Validate Accept: application/vnd.api+json.
      • Parse query params (include, fields, sort).
      • Inject ContextInterface with request data (e.g., auth, URL prefix).
  • Database Layer:
    • Eloquent: Extend Schema classes to lazy-load relationships (e.g., getRelationships() uses with()).
    • Query Builder: For non-Eloquent models, manually map SQL results to Schema attributes.
  • Frontend:
    • React/Vue: Use libraries like vue-jsonapi or ember-data for seamless consumption.
    • GraphQL: If needed, add a GraphQL layer (e.g., Lighthouse) that translates to JSON API.

Migration Path

  1. Phase 1: Encoder-Only Adoption (Low Risk):
    • Replace Response::json() with Encoder::encodeData() for new endpoints.
    • Example:
      // Before
      return response()->json($post->toArray());
      
      // After
      return response()->json(Encoder::encodeData($post));
      
    • Tools: Use Laravel’s php artisan make:schema PostSchema (custom command) to generate Schema classes.
  2. Phase 2: Decoder + Validation (Medium Risk):
    • Add JsonApiMiddleware to validate incoming requests.
    • Update controllers to use Decoder::decodeData() for PATCH/PUT requests.
    • Example:
      $data = Decoder::decodeData($request->getContent());
      $post = Post::find($data['id']);
      $post->update($data['attributes']);
      
  3. Phase 3: Full JSON API Compliance (High Risk):
    • Migrate all endpoints to JSON API format.
    • Update documentation and frontend clients.
    • Deprecate legacy endpoints with X-API-Version headers.

Compatibility

  • Laravel Versions:
    Laravel Version PHP Version Compatibility Notes
    6.x 7.1–7.4 Fully compatible.
    7.x 7.2–7.4 Fully compatible.
    8.x 7.3–8.0 Test for PHP 8.0+ (e.g., union types).
    9.x 8.0+ High risk; may need Symfony HTTP adapters.
  • Dependencies:
    • PHP Extensions: None critical (uses core json, mbstring).
    • Composer: No conflicts with Laravel’s dependencies (test with composer why-not neomerx/json-api).
  • Alternatives:
    • spatie/laravel-fractal: More Laravel-native but less standards-compliant.
    • nesbot/json-api-php: Actively maintained but Symfony-focused.
    • **
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.
terminal42/code-quality-tools
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