API 响应特征

现代 PHP 开发的大部分工作都需要构建 API,无论是简单地为 JavaScript 重度单页应用程序提供数据,还是作为独立产品。CodeIgniter 提供了一个 API 响应特征,可以与任何控制器一起使用,使常见的响应类型变得简单,无需记住哪些 HTTP 状态代码应该返回哪些响应类型。

示例用法

以下示例展示了控制器中常见的用法模式。

<?php

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;

class Users extends Controller
{
    use ResponseTrait;

    public function createUser()
    {
        $model = new UserModel();
        $user  = $model->save($this->request->getPost());

        // Respond with 201 status code
        return $this->respondCreated();
    }
}

在这个示例中,返回了 201 的 HTTP 状态代码,以及通用的状态消息“已创建”。方法存在于最常见的用例中

<?php

// Generic response method
$this->respond($data, 200);

// Generic failure response
$this->fail($errors, 400);

// Item created response
$this->respondCreated($data);

// Item successfully deleted
$this->respondDeleted($data);

// Command executed by no response required
$this->respondNoContent($message);

// Client isn't authorized
$this->failUnauthorized($description);

// Forbidden action
$this->failForbidden($description);

// Resource Not Found
$this->failNotFound($description);

// Data did not validate
$this->failValidationError($description);

// Resource already exists
$this->failResourceExists($description);

// Resource previously deleted
$this->failResourceGone($description);

// Client made too many requests
$this->failTooManyRequests($description);

处理响应类型

当您使用这些方法传递数据时,它们将根据以下条件确定数据类型以格式化结果。

  • 如果数据是字符串,它将被视为 HTML 并发送回客户端。

  • 如果数据是数组,它将根据控制器的 $this->format 值进行格式化。如果该值为空,它将尝试使用客户端请求的内容类型协商内容类型,如果在 Config/Format.php 中没有指定其他内容,则默认为 JSON,即 $supportedResponseFormats 属性。

要定义使用的格式化程序,请编辑 Config/Format.php$supportedResponseFormats 包含应用程序可以自动格式化响应的 MIME 类型列表。默认情况下,系统知道如何格式化 XML 和 JSON 响应。

<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class Format extends BaseConfig
{
    public $supportedResponseFormats = [
        'application/json',
        'application/xml',
    ];

    // ...
}

这是在 内容协商 期间用于确定返回哪种类型响应的数组。如果在客户端请求的内容和您支持的内容之间没有找到匹配项,则将返回此数组中的第一个格式。

接下来,您需要定义用于格式化数据数组的类。这必须是完全限定的类名,并且该类必须实现 CodeIgniter\Format\FormatterInterface。格式化程序开箱即用,支持 JSON 和 XML。

<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class Format extends BaseConfig
{
    public $formatters = [
        'application/json' => \CodeIgniter\Format\JSONFormatter::class,
        'application/xml'  => \CodeIgniter\Format\XMLFormatter::class,
    ];

    // ...
}

因此,如果您的请求在 Accept 标头中请求 JSON 格式的数据,您传递给任何 respond*fail* 方法的数据数组将由 CodeIgniter\Format\JSONFormatter 类格式化。生成的 JSON 数据将被发送回客户端。

类参考

setResponseFormat($format)
参数:
  • $format (string) – 返回的响应类型,可以是 jsonxml

这定义了在响应中格式化数组时使用的格式。如果为 $format 提供 null 值,它将通过内容协商自动确定。

<?php

return $this->setResponseFormat('json')->respond(['error' => false]);
respond($data[, $statusCode = 200[, $message = '']])
参数:
  • $data (mixed) – 返回给客户端的数据。可以是字符串或数组。

  • $statusCode (int) – 返回的 HTTP 状态码。默认为 200

  • $message (string) – 返回的自定义“原因”消息。

这是此特征中所有其他方法用来向客户端返回响应的方法。

The $data 元素可以是字符串或数组。默认情况下,字符串将作为 HTML 返回,而数组将通过 json_encode 运行并作为 JSON 返回,除非 内容协商 确定它应该以其他格式返回。

如果传递了 $message 字符串,它将用于代替响应状态的标准 IANA 原因代码。不过,并非所有客户端都尊重自定义代码,并且将使用与状态代码匹配的 IANA 标准。

注意

由于它在活动 Response 实例上设置状态代码和主体,因此这始终应该是脚本执行中的最后一个方法。

fail($messages[, int $status = 400[, string $code = null[, string $message = '']]])
参数:
  • $messages (mixed) – 包含遇到的错误消息的字符串或字符串数组。

  • $status (int) – 要返回的 HTTP 状态代码。默认为 400。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

客户端首选格式的多部分响应。

这是用于表示失败响应的通用方法,由所有其他“fail”方法使用。

$messages 元素可以是字符串或字符串数组。

$status 参数是要返回的 HTTP 状态代码。

由于许多 API 更适合使用自定义错误代码,因此可以在第三个参数中传递自定义错误代码。如果不存在值,它将与 $status 相同。

如果传递了 $message 字符串,它将用于代替响应状态的标准 IANA 原因代码。不过,并非所有客户端都尊重自定义代码,并且将使用与状态代码匹配的 IANA 标准。

响应是一个包含两个元素的数组:errormessageserror 元素包含错误的状态代码。 messages 元素包含一个错误消息数组。它看起来像这样

<?php

$response = [
    'status'   => 400,
    'code'     => '321a',
    'messages' => [
        'Error message 1',
        'Error message 2',
    ],
];
respondCreated($data = null[, string $message = ''])
参数:
  • $data (mixed) – 返回给客户端的数据。可以是字符串或数组。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

设置创建新资源时使用的适当状态码,通常为 201。

<?php

$user = $userModel->insert($data);

return $this->respondCreated($user);
respondDeleted($data = null[, string $message = ''])
参数:
  • $data (mixed) – 返回给客户端的数据。可以是字符串或数组。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

设置删除新资源时使用的适当状态码,通常为 200。

<?php

$user = $userModel->delete($id);

return $this->respondDeleted(['id' => $id]);
respondNoContent(string $message = 'No Content')
参数:
  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

设置服务器成功执行命令但没有有意义的回复发送回客户端时使用的适当状态码,通常为 204。

<?php

sleep(1);

return $this->respondNoContent();
failUnauthorized(string $description = 'Unauthorized'[, string $code = null[, string $message = '']])
参数:
  • $description (string) – 向用户显示的错误消息。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

设置用户未经授权或授权不正确时使用的适当状态码。状态码为 401。

<?php

return $this->failUnauthorized('Invalid Auth token');
failForbidden(string $description = 'Forbidden'[, string $code=null[, string $message = '']])
参数:
  • $description (string) – 向用户显示的错误消息。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

failUnauthorized() 不同,此方法应在请求的 API 端点始终不允许时使用。未经授权意味着鼓励客户端使用不同的凭据重试。禁止意味着客户端不应该再次尝试,因为它不会有任何帮助。状态码为 403。

<?php

return $this->failForbidden('Invalid API endpoint.');
failNotFound(string $description = 'Not Found'[, string $code=null[, string $message = '']])
参数:
  • $description (string) – 向用户显示的错误消息。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

当请求的资源无法找到时,设置相应的状态码。状态码为 404。

<?php

return $this->failNotFound('User 13 cannot be found.');
failValidationErrors($errors[, string $code=null[, string $message = '']])
参数:
  • $errors (mixed) – 要向用户显示的错误消息或消息数组。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

当客户端发送的数据未通过验证规则时,设置相应的状态码。状态码通常为 400。

<?php

return $this->failValidationErrors($validation->getErrors());
failResourceExists(string $description = 'Conflict'[, string $code=null[, string $message = '']])
参数:
  • $description (string) – 向用户显示的错误消息。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

当客户端尝试创建的资源已存在时,设置相应的状态码。状态码通常为 409。

<?php

return $this->failResourceExists('A user already exists with that email.');
failResourceGone(string $description = 'Gone'[, string $code=null[, string $message = '']])
参数:
  • $description (string) – 向用户显示的错误消息。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

当请求的资源先前已被删除且不再可用时,设置适当的 状态码。状态码通常为 410。

<?php

return $this->failResourceGone('That user has been previously deleted.');
failTooManyRequests(string $description = 'Too Many Requests'[, string $code=null[, string $message = '']])
参数:
  • $description (string) – 向用户显示的错误消息。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

当客户端多次调用 API 端点时,设置适当的 状态码。这可能是由于某种形式的节流或速率限制。状态码通常为 400。

<?php

return $this->failTooManyRequests('You must wait 15 seconds before making another request.');
failServerError(string $description = 'Internal Server Error'[, string $code = null[, string $message = '']])
参数:
  • $description (string) – 向用户显示的错误消息。

  • $code (string) – 自定义的、特定于 API 的错误代码。

  • $message (string) – 返回的自定义“原因”消息。

返回值:

Response 对象的 send() 方法的值。

当出现服务器错误时,设置适当的 状态码。

<?php

return $this->failServerError('Server error.');