Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

json-api

> 后端框架
Open source

A lightweight API resource for Laravel that helps you adhere to the JSON:API standard. Supports sparse fieldsets, compound documents, and more.

642 stars0 likes0 views
WebsiteGitHub

About

A lightweight API resource for Laravel that helps you adhere to the JSON:API standard. Supports sparse fieldsets, compound documents, and more.

JSON:API Resource for Laravel

A lightweight API resource for Laravel that helps you adhere to the JSON:API standard with support for sparse fieldsets, compound documents, and more baked in.

Note These docs are not designed to introduce you to the JSON:API specification and the associated concepts, instead you should head over and read the specification if you are not yet familiar with it. The documentation that follows only covers how to implement the specification via the package.

Table of contents

  • Installation
  • Getting started
    • Creating your first JSON:API resource
    • Adding attributes
    • Adding relationships
  • A note on eager loading
  • Digging deeper
    • Attributes
      • toAttributes()
      • Sparse fieldsets
      • Minimal attributes
      • Lazy attribute evaluation
    • Relationships
      • toRelationships()
      • Customising the relationship resource class guessing

Installation

You can install using composer from Packagist.

bash
composer require timacdonald/json-api

Getting started

The JsonApiResource class provided by this package is a specialisation of Laravel's Eloquent API resource. All public facing APIs are still accessible; in a controller, for example, you interact with a JsonApiResource as you would with Laravel's JsonResource class.

php
paginate();

        return UserResource::collection($users);
    }

    public function show(User $user)
    {
        $user->load([/* ... */]);

        return UserResource::make($user);
    }
}

As we make our way through the examples you will see that new APIs are introduced when interacting with the class internally, for example, the toArray() method is no longer used.

Creating your first JSON:API resource

To get started, let's create a UserResource for our User model. In our user resource will expose the user's name, website, and twitter_handle in the response.

First we will create a new API resource that extends TiMacDonald\JsonApi\JsonApiResource.

php
 UserResource::make($user));

The following JSON:API formatted data would be returned:

json
{
  "data": {
    "type": "users",
    "id": "74812",
    "attributes": {
      "name": "Tim",
      "website": "https://timacdonald.me",
      "twitter_handle": "@timacdonald87"
    }
  }
}

You have just created your first JSON:API resource

Congratulations...and what. a. rush!

We will now dive into adding relationships to your resources, but if you would like to explore more complex attribute features you may like to jump ahead:

  • toAttributes()
  • Sparse fieldsets
  • Minimal attributes
  • Lazy attribute evaluation

Adding relationships

Available relationships may be specified in a $relationships property, similar to the $attributes property, however you may use a key / value pair to provide the resource class that should be used for the given relationship.

We will make two relationships available on the resource:

  • $user->team: a "toOne" / HasOne relationship.
  • $user->posts: a "toMany" / HasMany relationship.
php
 TeamResource::class,
        'posts' => PostResource::class,
    ];
}

Assuming the key / value pair follows the convention '{myKey}' => {MyKey}Resource::class, the class may be omitted to streamline things further.

php
 **Note** Relationships are not exposed in the response unless they are requested by the calling client via the `include` query parameter. This is intended and is part of the `JSON:API` specification.

```json
{
  "data": {
    "id": "74812",
    "type": "users",
    "attributes": {
      "name": "Tim",
      "website": "https://timacdonald.me",
      "twitter_handle": "@timacdonald87"
    },
    "relationships": {
      "posts": {
        "data": [
          {
            "type": "posts",
            "id": "25240"
          },
          {
            "type": "posts",
            "id": "39974"
          }
        ]
      },
      "team": {
        "data": {
          "type": "teams",
          "id": "18986"
        }
      }
    }
  },
  "included": [
    {
      "id": "25240",
      "type": "posts",
      "attributes": {
        "title": "So what is `JSON:API` all about anyway?",
        "content": "...",
        "excerpt": "..."
      }
    },
    {
      "id": "39974",
      "type": "posts",
      "attributes": {
        "title": "Building an API with Laravel, using the `JSON:API` specification.",
        "content": "...",
        "excerpt": "..."
      }
    },
    {
      "id": "18986",
      "type": "teams",
      "attributes": {
        "name": "Laravel"
      }
    }
  ]
}

…

php
allowedIncludes(['team', 'posts'])
            ->paginate();

        return UserResource::collection($users);
    }

    public function show($id)
    {
        $user = QueryBuilder::for(User::class)
            ->allowedIncludes(['team', 'posts'])
            ->findOrFail($id);

        return UserResource::make($user);
    }
}

…

php

     */
    public function toAttributes($request)
    {
        return [
            'name' => $this->name,
            'website' => $this->website,
            'twitter_handle' => $this->twitter_handle,
            'email' => $this->when($this->email_is_public, $this->email, ''),
            'address' => [
                'city' => $this->address('city'),
                'country' => $this->address('country'),
            ],
        ];
    }
}
Example response
json
{
  "data": {
    "id": "74812",
    "type": "users",
    "attributes": {
      "name": "Tim",
      "website": "https://timacdonald.me",
      "twitter_handle": "@timacdonald87",
      "email": "",
      "address": {
        "city": "Melbourne",
        "country": "Australia"
      }
    }
  }
}

…


GET /posts?include=author&fields[posts]=title,excerpt&fields[users]=name

Note The include query parameter key is author, while the sparse fieldset parameter key is users. This is because authors are users, e.g. the Eloquent author() relationship returns a User model.

Example response
json
{
  "data": [
    {
      "id": "25240",
      "type": "posts",
      "attributes": {
        "title": "So what is `JSON:API` all about anyway?",
        "excerpt": "..."
      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "74812"
          }
        }
      }
    },
    {
      "id": "39974",
      "type": "posts",
      "attributes": {
        "title": "Building an API with Laravel, using the `JSON:API` specification.",
        "excerpt": "..."
      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "74812"
          }
        }
      }
    }
  ],
  "included": [
    {
      "type": "users",
      "id": "74812",
      "attributes": {
        "name": "Tim"
      }
    }
  ]
}

Minimal attributes

Resources return a maximal attribute payload when sparse fieldsets are not in use i.e. all declared attributes on the resource are returned. If you prefer you can make the use of sparse fieldsets required in order to retrieve any attributes.

You may call the useMinimalAttributes() method in an application service provider.

php

     */
    public function toAttributes($request)
    {
        return [
            // ...
            'avatar' => Http::get("https://avatar.example.com/{$this->id}")->body(),
        ];
    }
}

The above implementation would make a HTTP request to our microservice even when the client is excluding the avatar attribute via sparse fieldsets or minimal attributes. To improve performance when this attribute is not being returned we can wrap the value in a Closure. The Closure will only be evaluated when the avatar is to be returned.

php

     */
    public function toAttributes($request)
    {
        return [
            // ...
            'avatar' => fn () => Http::get("https://avatar.example.com/{$this->id}")->body(),
        ];
    }
}

…

php

     */
    public function toRelationships($request)
    {
        return [
            'team' => fn () => TeamResource::make($this->team),
            'posts' => fn () => $request->user()->is($this->resource)
                ? PostResource::collection($this->posts)
                : PostResource::collection($this->posts->where('published', true)),
        ];
    }
}

Customising the relationship resource class guessing

php

…

php
resource)),
            'related' => 'https://example.com/related'
        ];
    }
}

Resource Meta

[JSON:API docs: Meta](https://jsonapi.org/format/#document-meta)

To provide meta information for a resource, you can implement the toMeta($request) method...

php
 true,
        ];
    }
}

Advanced usage

Resource Identification

Customising the resource "id"

You can customise the resolution of the id by specifying an id resolver in your service provider.

php
<?php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        JsonApiResource::resolveIdUsing(function (mixed $resource, Request $request): string {
            // your custom resolution logic...
        });
    }
}

Although it is not recommended, you can also override the toId(Request $request): string method on a resource by resource basis.

Customising the resource "type"

You can customise the resolution of the type by specifying a type resolver in your service provider.

php
<?php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        JsonApiResource::resolveTypeUsing(function (mixed $resource, Request $request): string {
            // your custom resolution logic...
        });
    }
}

Although it is not recommended, you can also override the toType(Request $request): string method on a resource by resource basis.

Resource Relationships

[JSON:API docs: Inclusion of Related Resources](https://jsonapi.org/format/#fetching-includes)

Relationships can be resolved deeply and also multiple relationship paths can be included. Of course you should be careful about n+1 issues, which is why we recommend using this package in conjunction with Spatie's Query Builder.

bash
# Including deeply nested relationships
/api/posts/8?include=author.comments

# Including multiple relationship paths
/api/posts/8?include=comments,author.comments
  • Using "whenLoaded is an anti-pattern"

Credits

  • Tim MacDonald
  • Jess Archer for co-creating our initial in-house version and the brainstorming
  • All Contributors

And a special (vegi) thanks to Caneco for the logo ✨

v1 todo

  • Server implementation rethink.
  • Rethink naming of objects and properties
  • Camel case everything
  • Allow resources to specify their JsonResource class.
  • Make all caches WeakMaps.
  • Things that "must" need to be first in the __consstructor. See Links:href
  • Should it be withResourceIdentifier or mapResourceIdentifier. Feel like we are mapping. or pipeResourceIdentifier
  • Should all

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPjson-apilaravelphp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架