aejnsn/lapis

Laravel 5.5+ 的 API 工具包

0.2.0 2019-07-18 04:44 UTC

This package is auto-updated.

Last update: 2024-09-18 17:07:17 UTC


README

lapis

基于 Laravel API 资源的构建工具包。

Build Status Coverage Status

概念

RESTful API 端点通常需要比分页更多的功能。例如,前端或移动应用程序可能需要实现过滤方案或需要访问端点的嵌套资源。Lapis 旨在利用 Laravel 5.5 中的现有功能,提供轻量级的过滤和嵌套资源模式。

包含

假设我们有一个博客平台的端点来列出我们的 post 资源,返回如下响应
GET https://api.myrecipeblog.com/posts

{
  "posts": [
    {
      "name": "Asparagus Steak Oscar",
      "category": "food",
      "postedAt": "2017-09-12 16:04:33",
      "authorId": 14
    },
    {
      "name": "Churchill Downs Mint Julep",
      "category": "drinks",
      "postedAt": "2017-10-05 18:32:12",
      "authorId": 15
    }
  ]
}

理想情况下,我们希望在前端看到帖子的作者的详细信息。对,所以向一个假设的 users 端点发送另一个请求,引用从 posts 响应中获取的独特的作者ID列表...不,绝对不行!我们(希望)在我们的博客平台的后端花时间来建模我们的数据关系,并设置外键约束以及适当的索引。所以让我们使用这些模型。

Lapis 利用 Laravel 的 API 资源,允许我们在请求 URL 中添加 include 参数来检索嵌套的 author(用户)关系。我们的请求 URL 和响应可能如下所示

GET https://api.myrecipeblog.com/posts?include=author

{
  "posts": [
    {
      "name": "Asparagus Steak Oscar",
      "category": "food",
      "postedAt": "2017-09-12 16:04:33",
      "authorId": 14,
      "author": {
        "id": 14,
        "name": "John Doe",
        "forHire": true,
        "chefRating": 5
      }
    },
    {
      "name": "Churchill Downs Mint Julep",
      "category": "drinks",
      "postedAt": "2017-10-05 18:32:12",
      "authorId": 15,
      "author": {
        "id": 15,
        "name": "James Smith",
        "forHire": false,
        "chefRating": 1
      }
    }
  ]
}
嵌套包含

这也可以用于嵌套关系。例如,如果我们的 User 模型包含一个 favorites 关系,我们可以请求 GET https://api.myrecipeblog.com/posts?include=author.favorites,然后在 author 对象中嵌套作者的一个 favorites 数组。

过滤

让我们回到我们上面调用过的原始响应,我们调用的是 posts 端点。也许我们只想看到饮料类别的帖子。我们可以像这样修改我们的调用

GET https://api.myrecipeblog.com/posts?filter[category]=drinks

{
  "posts": [
    {
      "name": "Churchill Downs Mint Julep",
      "category": "drinks",
      "postedAt": "2017-10-05 18:32:12",
      "authorId": 15
    }
  ]
}

我们也可以使用这种结构指定多个过滤器

GET https://api.myrecipeblog.com/posts?filter[category]=drinks&filter[authorId]=15

嵌套过滤器

我们上面讨论了包含一个 author 关系。我们也可以通过发出如下请求来过滤作者详情

GET https://api.myrecipeblog.com/posts?filter[author.forHire]=true

过滤运算符

到目前为止,我们只是使用过滤器断言字段等于给定值。过滤器理解运算符的概念。以下是一些示例

列出晚于 2017 年 10 月 1 日的帖子。

GET https://api.myrecipeblog.com/posts?filter[postedAt{gte}]=2017-10-01

列出作者名字以 John 开头的帖子。

GET https://api.myrecipeblog.com/posts?filter[author.name{starts}]=John

参考实现

安装 & 使用