PHPackages                             alexfigures/symfony-jsonapi-bundle - 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. alexfigures/symfony-jsonapi-bundle

ActiveSymfony-bundle[HTTP &amp; Networking](/categories/http)

alexfigures/symfony-jsonapi-bundle
==================================

JSON:API 1.1 bundle for Symfony 7 with DX-first design

v0.1.25(6mo ago)2170[14 PRs](https://github.com/AlexFigures/jsonapi-symfony/pulls)MITPHPPHP ^8.2CI failing

Since Oct 13Pushed 4mo agoCompare

[ Source](https://github.com/AlexFigures/jsonapi-symfony)[ Packagist](https://packagist.org/packages/alexfigures/symfony-jsonapi-bundle)[ Docs](https://github.com/AlexFigures/jsonapi-symfony)[ GitHub Sponsors](https://github.com/sponsors/AlexFigures)[ RSS](/packages/alexfigures-symfony-jsonapi-bundle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (24)Versions (46)Used By (0)

JsonApiBundle
=============

[](#jsonapibundle)

[![CI](https://github.com/AlexFigures/jsonapi-symfony/workflows/CI/badge.svg)](https://github.com/AlexFigures/jsonapi-symfony/actions)[![PHPStan Level 8](https://camo.githubusercontent.com/d117944b58da8146f96b4ef7403807610a20eeb3fbcaaaf95157bbcdad1686eb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230382d627269676874677265656e2e737667)](https://phpstan.org/)[![Spec Conformance](https://camo.githubusercontent.com/30602cefb29b75318a98428cc669881c63bc156f61583ff714aedffc7272e752/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4a534f4e3a4150492d39372e382532352d627269676874677265656e2e737667)](docs/conformance/spec-coverage.md)[![PHP Version](https://camo.githubusercontent.com/962aced9b09d89716dbebf186ff899754a096ff1068b6b7988675c2d9fab9331/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c75652e737667)](https://www.php.net/)[![Symfony Version](https://camo.githubusercontent.com/5c0c7664667ae01220f4fbf07f26f4701367929827707b46056f8082013d9ad5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73796d666f6e792d253545372e312d626c75652e737667)](https://symfony.com/)[![Packagist](https://camo.githubusercontent.com/3a66a105e3d71e7a88242e21f40dd76e8c9039308be830fa760ae08c292f18d1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c6578666967757265732f73796d666f6e792d6a736f6e6170692d62756e646c652e737667)](https://packagist.org/packages/alexfigures/symfony-jsonapi-bundle)[![OpenSSF Scorecard](https://camo.githubusercontent.com/0144ee32b4f37268628fa96d853832b69e1bf8308b17851d575cba21fd3c8f98/68747470733a2f2f6170692e736563757269747973636f726563617264732e6465762f70726f6a656374732f6769746875622e636f6d2f416c6578466967757265732f6a736f6e6170692d73796d666f6e792f6261646765)](https://api.securityscorecards.dev/projects/github.com/AlexFigures/jsonapi-symfony)

**Production-ready JSON:API 1.1 implementation for Symfony with complete filtering, automatic eager loading, and zero N+1 queries.**

🚀 Quick Start
-------------

[](#-quick-start)

### Installation

[](#installation)

```
composer require alexfigures/symfony-jsonapi-bundle
```

**Requirements:**

- PHP 8.3 or higher
- Symfony 7.1 or higher
- Doctrine ORM 3.0+ (optional, for database integration)

### Basic Setup

[](#basic-setup)

1. **Register the bundle** in `config/bundles.php`:

```
return [
    AlexFigures\Symfony\Bridge\Symfony\Bundle\JsonApiBundle::class => ['all' => true],
];
```

2. **Create configuration** in `config/packages/jsonapi.yaml`:

```
jsonapi:
    route_prefix: '/api'
    pagination:
        default_size: 25
        max_size: 100
```

3. **Define your first resource**:

```
use AlexFigures\Symfony\Resource\Attribute\JsonApiResource;
use AlexFigures\Symfony\Resource\Attribute\Id;
use AlexFigures\Symfony\Resource\Attribute\Attribute;
use AlexFigures\Symfony\Resource\Attribute\Relationship;

#[JsonApiResource(type: 'articles')]
final class Article
{
    #[Id]
    #[Attribute]
    public string $id;

    #[Attribute]
    public string $title;

    #[Relationship(toMany: true, targetType: 'comments')]
    public array $comments = [];
}
```

4. **Implement data layer** (see [Doctrine Integration Guide](docs/guide/integration-doctrine.md))
5. **Start using your API**:

```
# Get all articles
curl http://localhost:8000/api/articles

# Filter, sort, and include relationships (no N+1 queries!)
curl "http://localhost:8000/api/articles?filter[status][eq]=published&sort=-createdAt&include=author,tags"

# Advanced filtering with multiple conditions
curl "http://localhost:8000/api/articles?filter[and][0][status][eq]=published&filter[and][1][viewCount][gte]=100"

# Create new article
curl -X POST \
     -H "Content-Type: application/vnd.api+json" \
     -d '{"data": {"type": "articles", "attributes": {"title": "Hello"}}}' \
     http://localhost:8000/api/articles

# Interactive API documentation
open http://localhost:8000/_jsonapi/docs
```

**📖 [Complete Getting Started Guide →](docs/guide/getting-started.md)****📊 [Interactive API Docs →](docs/guide/swagger-ui.md)**

✅ Compatibility Matrix
----------------------

[](#-compatibility-matrix)

JsonApiBundlePHPSymfonyDoctrine ORM`main` branch8.2 · 8.3 · 8.47.1 · 7.2 · 7.33.0+Latest release8.2+7.1+3.0+> CI runs the full test suite across PHP 8.2–8.4 with both stable and lowest-dependency sets to guarantee forwards and backwards compatibility inside each supported Symfony minor.

**Tested Databases:**

- PostgreSQL 16+
- MySQL 8.0+
- MariaDB 11+
- SQLite 3.x

---

🎯 Key Features
--------------

[](#-key-features)

### 🔍 **Advanced Filtering &amp; Querying**

[](#-advanced-filtering--querying)

- **Complex Filters** - Support for `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `like`, `ilike` operators
- **Logical Operators** - Combine filters with `and`, `or`, `not` for complex queries
- **Relationship Filtering** - Filter by nested relationship fields: `filter[author.name]=John`
- **Whitelist-based Security** - Only explicitly allowed fields can be filtered using `#[FilterableFields]`

```
# Complex filtering example
curl "api/articles?filter[and][0][status][eq]=published&filter[and][1][or][0][viewCount][gte]=100&filter[and][1][or][1][featured][eq]=true"
```

### 🔗 **Smart Relationship Handling**

[](#-smart-relationship-handling)

- **Zero N+1 Queries** - Automatic eager loading with optimized JOINs
- **Deep Includes** - Include nested relationships: `include=author.company,tags`
- **Relationship Linking Policies** - Control how relationships are validated (`VERIFY`, `ALLOW_ORPHANS`)
- **Path Aliases** - Expose clean API paths that map to complex Doctrine relationships

```
#[Relationship(
    toMany: true,
    targetType: 'tags',
    propertyPath: 'articleTags.tag',  // Clean API: specialTags → complex path
    linkingPolicy: RelationshipLinkingPolicy::VERIFY
)]
private Collection $specialTags;
```

### 📊 **Flexible Sorting &amp; Pagination**

[](#-flexible-sorting--pagination)

- **Multi-field Sorting** - Sort by multiple fields: `sort=title,-createdAt,author.name`
- **Relationship Sorting** - Sort by nested relationship fields
- **Cursor &amp; Offset Pagination** - Both pagination strategies supported
- **Configurable Limits** - Set default and maximum page sizes

### 🛡️ **Production-Ready Security**

[](#️-production-ready-security)

- **Strict Denormalization** - Reject unknown fields by default (`ALLOW_EXTRA_ATTRIBUTES=false`)
- **Field Whitelisting** - Explicit control over filterable/sortable fields
- **Validation Integration** - Full Symfony Validator integration
- **Error Collection** - Collect and return all validation errors at once

### 🚀 **Developer Experience**

[](#-developer-experience)

- **Attribute-Based Configuration** - No YAML/XML, everything in PHP attributes
- **Auto-Generated OpenAPI** - Interactive Swagger UI documentation
- **Custom Route Support** - Define custom endpoints with automatic JSON:API formatting
- **Response Factory** - Fluent API for building JSON:API responses in custom controllers

```
#[JsonApiResource(type: 'articles')]
#[FilterableFields(['title', new FilterableField('author', inherit: true)])]
#[SortableFields(['title', 'createdAt', new SortableField('author', inherit: true)])]
final class Article
{
    #[Id] #[Attribute] public string $id;
    #[Attribute] public string $title;
    #[Relationship(targetType: 'authors')] public Author $author;
}
```

### ⚡ **Performance Optimizations**

[](#-performance-optimizations)

- **Automatic Query Optimization** - Smart JOINs and SELECT field limiting
- **Batch Operations** - Efficient bulk create/update/delete
- **Caching Support** - HTTP caching headers and response caching
- **Database Agnostic** - Works with PostgreSQL, MySQL, MariaDB, SQLite

### 🔧 **Extensibility**

[](#-extensibility)

- **Custom Handlers** - Build complex business logic with automatic transaction management
- **Event System** - Hook into request/response lifecycle
- **Custom Serialization** - Override default serialization behavior
- **Middleware Support** - Standard Symfony middleware integration

---

📚 Documentation
---------------

[](#-documentation)

### For New Users

[](#for-new-users)

- **[Getting Started Guide](docs/guide/getting-started.md)** - Build your first API in 5 minutes
- **[Swagger UI &amp; OpenAPI](docs/guide/swagger-ui.md)** - Interactive API documentation
- **[Configuration Reference](docs/guide/configuration.md)** - Complete configuration options
- **[Doctrine Integration](docs/guide/integration-doctrine.md)** - Production-ready data layer
- **[Examples &amp; Recipes](docs/guide/examples.md)** - Real-world code examples
- **[Custom Routes](docs/guide/custom-routes.md)** - Define custom endpoints with attributes
- **[Response Factory](docs/guide/response-factory.md)** - Build JSON:API responses in custom controllers

### For Advanced Users

[](#for-advanced-users)

- **[Path Aliases](docs/guide/path-aliases.md)** - Expose clean API paths that map to complex Doctrine relationships
- **[Advanced Features](docs/guide/advanced-features.md)** - Profiles, hooks, events, caching
- **[Custom Handlers](docs/guide/custom-handlers.md)** - Handler-based custom routes with automatic transaction management
- **[Public API Reference](docs/api/public-api.md)** - Stable API documentation
- **[Troubleshooting Guide](docs/guide/troubleshooting.md)** - Common issues and solutions

### For Contributors

[](#for-contributors)

- **[Contributing Guide](CONTRIBUTING.md)** - How to contribute
- **[Testing Guide](TESTING.md)** - Running tests (unit, functional, integration with Docker)
- **[Architecture Review](docs/architecture/review.md)** - Design and extensibility
- **[BC Policy](docs/api/bc-policy.md)** - Backward compatibility guarantees

**📖 [Complete Documentation Index →](docs/guide/README.md)**

---

🆕 Recent Updates
----------------

[](#-recent-updates)

### New Features

[](#new-features)

- **🆕 Path Aliases** - Expose clean API paths that map to complex Doctrine relationships using `propertyPath` parameter ```
    #[Relationship(
        toMany: true,
        targetType: 'tags',
        propertyPath: 'articleTags.tag'  // API: specialTags → Doctrine: articleTags.tag
    )]
    private Collection $specialTags;
    ```
- **Custom Route Handlers** - Build custom endpoints with automatic transaction management and JSON:API response formatting ([docs](docs/guide/custom-handlers.md))
- **Response Factory** - Fluent API for building JSON:API responses in custom controllers ([docs](docs/guide/response-factory.md))
- **Criteria Builder** - Add custom filters and conditions to JSON:API queries in custom route handlers ([docs](docs/guide/custom-routes.md#advanced-filtering-sorting-and-pagination-in-custom-routes))
- **Custom Route Attributes** - Define custom endpoints using `#[JsonApiCustomRoute]` attribute ([docs](docs/guide/custom-routes.md))
- **Media Type Configuration** - Configure different media types for different endpoints (e.g., docs, sandbox)
- **Docker-based Integration Tests** - Run integration tests against real databases using Docker ([docs](TESTING.md))

### Testing Improvements

[](#testing-improvements)

- **Docker Test Environment** - Integration tests now run in Docker with PostgreSQL, MySQL, and MariaDB
- **Conformance Tests** - Snapshot-based tests ensure JSON:API specification compliance
- **Mutation Testing** - Infection configured with 70% MSI threshold
- **Quality Gates** - PHPStan level 8, Deptrac architecture rules, BC checks

Run tests with:

```
make test              # Unit and functional tests
make docker-test       # Integration tests in Docker
make qa-full          # Full QA suite (tests, static analysis, mutation testing)
```

See [TESTING.md](TESTING.md) for complete testing documentation.

---

✨ Features
----------

[](#-features)

### Production-Ready Features ⭐

[](#production-ready-features-)

✅ **Complete Filtering System** - All operators (eq, ne, lt, lte, gt, gte, like, in, isnull, between) with SQL injection protection ✅ **Automatic Eager Loading** - Zero N+1 queries with automatic JOINs for includes ✅ **Generic Doctrine Repository** - Works out of the box, no custom code needed ✅ **Relationship Pagination** - Proper pagination for all relationship endpoints ✅ **PostgreSQL Optimized** - Tested and optimized for PostgreSQL ✅ **Custom Route Handlers** - Build custom endpoints with automatic transaction management and JSON:API formatting

### Core Features

[](#core-features)

✅ **JSON:API 1.1 Compliance** - 97.8% specification coverage (132/135 requirements) ✅ **Attribute-Driven** - No XML/YAML configuration needed ✅ **Auto-Generated Endpoints** - No controller boilerplate ✅ **Configurable Route Naming** - Choose between snake\_case and kebab-case ✅ **Custom Route Attributes** - Define custom endpoints with PHP attributes ✅ **Query Parameters** - `include`, `fields`, `sort`, `page`, `filter`✅ **Relationships** - To-one and to-many with full CRUD ✅ **Write Operations** - POST, PATCH, DELETE with validation ✅ **Atomic Operations** - Batch operations in single transaction ✅ **Interactive Docs** - Swagger UI / Redoc integration ✅ **Response Factory** - Build JSON:API responses in custom controllers

### Read Operations

[](#read-operations)

- `GET /api/{type}` - Collection with pagination, sorting, filtering
- `GET /api/{type}/{id}` - Single resource with sparse fieldsets
- `GET /api/{type}/{id}/relationships/{rel}` - Relationship linkage
- `GET /api/{type}/{id}/{rel}` - Related resources
- Query parsing: `include`, `fields[TYPE]`, `sort`, `page[number]`, `page[size]`
- Pagination with `self`, `first`, `prev`, `next`, `last` links
- Compound documents with `included` array
- Sparse fieldsets for performance optimization

### Write Operations

[](#write-operations)

- `POST /api/{type}` → `201 Created` with Location header
- `PATCH /api/{type}/{id}` → `200 OK` with updated resource
- `DELETE /api/{type}/{id}` → `204 No Content`
- Transactional execution via `TransactionManager`
- Client-generated ID support (configurable per type)
- Strict input validation with detailed error responses
- Relationship modification endpoints (optional)

### Advanced Features

[](#advanced-features)

- **Profiles (RFC 6906)** - Extend JSON:API with custom semantics
- **Hooks System** - Intercept and modify request processing
- **Event System** - React to resource changes
- **HTTP Caching** - ETag, Last-Modified, surrogate keys
- **Custom Operators** - Extend filtering capabilities
- **Cache Invalidation** - CDN/reverse proxy support
- **Media Type Configuration** - Configure different media types for different endpoints
- **Criteria Builder** - Add custom filters and conditions to JSON:API queries in custom handlers

**📖 [See all features →](docs/guide/advanced-features.md)**

---

🔒 Backward Compatibility
------------------------

[](#-backward-compatibility)

JsonApiBundle follows [Semantic Versioning](https://semver.org/):

- **MAJOR** versions may contain breaking changes
- **MINOR** versions add features in a backward-compatible manner
- **PATCH** versions contain bug fixes only

### Public API (Stable)

[](#public-api-stable)

The following are guaranteed to maintain backward compatibility:

- ✅ **Contract Interfaces** (`src/Contract/`) - Data layer contracts
- ✅ **Resource Attributes** (`src/Resource/Attribute/`) - `#[JsonApiResource]`, `#[Attribute]`, etc.
- ✅ **Configuration Schema** - All `jsonapi:` configuration options

**📖 [Public API Reference →](docs/api/public-api.md)****📖 [BC Policy →](docs/api/bc-policy.md)****📖 [Upgrade Guide →](docs/api/upgrade-guide.md)**

### Pre-1.0 Notice

[](#pre-10-notice)

⚠️ Versions 0.x may introduce breaking changes in MINOR versions. Pin to exact MINOR version:

```
{
    "require": {
        "jsonapi/symfony-jsonapi-bundle": "~0.1.0"
    }
}
```

---

📖 Interactive API Documentation
-------------------------------

[](#-interactive-api-documentation)

The bundle provides automatic OpenAPI 3.1 documentation with interactive UI:

### Access Documentation

[](#access-documentation)

**Swagger UI (Interactive):**

```
http://localhost:8000/_jsonapi/docs

```

**OpenAPI Specification (JSON):**

```
http://localhost:8000/_jsonapi/openapi.json

```

### Features

[](#features)

- 🎨 **Two themes**: Swagger UI (default) or Redoc
- 🔍 **Try it out**: Test endpoints directly from browser
- 📖 **Auto-generated**: Reflects all resources and relationships
- 🔒 **Environment-aware**: Disable in production

### Configuration

[](#configuration)

```
# config/packages/jsonapi.yaml
jsonapi:
    docs:
        generator:
            openapi:
                enabled: true
                title: 'My API'
                version: '1.0.0'
        ui:
            enabled: true
            route: '/_jsonapi/docs'
            theme: 'swagger'  # or 'redoc'
```

**Production:** Disable in `config/packages/prod/jsonapi.yaml`:

```
jsonapi:
    docs:
        ui:
            enabled: false
```

**📖 [Swagger UI Documentation →](docs/guide/swagger-ui.md)**

---

📊 Example Response
------------------

[](#-example-response)

```
{
  "jsonapi": { "version": "1.1" },
  "links": {
    "self": "http://localhost/api/articles?page[number]=1&page[size]=10",
    "first": "http://localhost/api/articles?page[number]=1&page[size]=10",
    "last": "http://localhost/api/articles?page[number]=3&page[size]=10",
    "next": "http://localhost/api/articles?page[number]=2&page[size]=10"
  },
  "data": [
    {
      "type": "articles",
      "id": "1",
      "attributes": {
        "title": "Getting Started with JSON:API",
        "createdAt": "2025-10-07T10:00:00+00:00"
      },
      "relationships": {
        "author": {
          "links": {
            "self": "http://localhost/api/articles/1/relationships/author",
            "related": "http://localhost/api/articles/1/author"
          },
          "data": { "type": "authors", "id": "1" }
        }
      },
      "links": {
        "self": "http://localhost/api/articles/1"
      }
    }
  ],
  "included": [
    {
      "type": "authors",
      "id": "1",
      "attributes": { "name": "Alice" },
      "links": { "self": "http://localhost/api/authors/1" }
    }
  ],
  "meta": {
    "total": 25,
    "page": 1,
    "size": 10
  }
}
```

---

🛠️ Development &amp; Testing
----------------------------

[](#️-development--testing)

### Quick Commands

[](#quick-commands)

```
# Install dependencies
composer install
# or
make install

# Run tests
make test              # Unit and functional tests (no Docker required)
make docker-test       # Integration tests with real databases
make test-all          # All test suites

# Code quality
make stan              # PHPStan static analysis (level 8)
make cs-fix            # Fix code style (PSR-12)
make rector            # Automated refactoring
make mutation          # Mutation testing (70% MSI threshold)
make deptrac           # Architecture rules validation
make bc-check          # Backward compatibility check

# Full QA pipeline
make qa-full           # Run all quality checks
```

See [TESTING.md](TESTING.md) for detailed testing documentation.

---

🤝 Community &amp; Governance
----------------------------

[](#-community--governance)

- 📮 **Need help?** Read our [Support guide](SUPPORT.md) for documentation links, discussion forums, and escalation paths.
- 📋 **Contributions welcome!** See the [CONTRIBUTING.md](CONTRIBUTING.md) for coding standards and workflow.
- ❤️ **Be excellent to each other.** Participation is governed by the [Code of Conduct](CODE_OF_CONDUCT.md).
- 🛡 **Report vulnerabilities privately.** Follow the steps in [SECURITY.md](SECURITY.md).
- 🧭 **Stay up to date.** Watch [Discussions](https://github.com/AlexFigures/jsonapi-symfony/discussions) and subscribe to release drafts for roadmap updates.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance71

Regular maintenance activity

Popularity17

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

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

28

Last Release

193d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/45813731?v=4)[Aleksandr](/maintainers/alexfigures)[@AlexFigures](https://github.com/AlexFigures)

---

Top Contributors

[![AlexFigures](https://avatars.githubusercontent.com/u/45813731?v=4)](https://github.com/AlexFigures "AlexFigures (84 commits)")

---

Tags

apisymfonyrestspecificationjsonapiSymfony Bundle

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/alexfigures-symfony-jsonapi-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/alexfigures-symfony-jsonapi-bundle/health.svg)](https://phpackages.com/packages/alexfigures-symfony-jsonapi-bundle)
```

###  Alternatives

[api-platform/core

Build a fully-featured hypermedia or GraphQL API in minutes!

2.6k48.1M236](/packages/api-platform-core)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[nelmio/api-doc-bundle

Generates documentation for your REST API from attributes

2.3k63.6M233](/packages/nelmio-api-doc-bundle)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

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