CodeIgniter4 API 響應(yīng)特性

2020-08-17 15:50 更新

現(xiàn)代化的 PHP開發(fā)都需要構(gòu)建 API ,不管它只是為了給 javascript 單頁應(yīng)用提供數(shù)據(jù)還是作為獨(dú)立的產(chǎn)品。CodeIgniter 提供了一個API響應(yīng)特性,可用于任何控制器,使公共響應(yīng)類型簡單,無需記住它的 HTTP 狀態(tài)代碼應(yīng)返回的響應(yīng)類型。

使用示例

下面的示例顯示了控制器中常見的使用模式。

<?php namespace App\Controllers;


class Users extends \CodeIgniter\Controller
{
    use CodeIgniter\API\ResponseTrait;


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


        // 響應(yīng) 201 狀態(tài)碼
        return $this->respondCreated();
    }
}

在這個例子中,響應(yīng)了 201 的HTTP狀態(tài)碼,并使用“創(chuàng)建”的通用狀態(tài)消息返回。方法存在于最常見的用例中

// 通用響應(yīng)方式
respond($data, 200);
// 通用錯誤響應(yīng)
fail($errors, 400);
// 項(xiàng)目創(chuàng)建響應(yīng)
respondCreated($data);
// 項(xiàng)目成功刪除
respondDeleted($data);
// 客戶端未授權(quán)
failUnauthorized($description);
// 禁止動作
failForbidden($description);
// 找不到資源
failNotFound($description);
// Data 數(shù)據(jù)沒有驗(yàn)證
failValidationError($description);
// 資源已存在
failResourceExists($description);
// 資源早已被刪除
failResourceGone($description);
// 客戶端請求數(shù)過多
failTooManyRequests($description);

處理響應(yīng)類型

當(dāng)您通過以下任何一種方法傳遞數(shù)據(jù)時,它們將決定基于數(shù)據(jù)類型來格式化結(jié)果:

  • 如果 $data 是一個字符串,它將被當(dāng)作 HTML 發(fā)送回客戶端。
  • 如果 $data 是一個數(shù)組,它將嘗試請求內(nèi)容類型與客戶端進(jìn)行協(xié)商,默認(rèn)為 JSON。如果沒有在 ConfigAPI.php 中配置內(nèi)容。默認(rèn)使用 $supportedResponseFormats 屬性。

需要使用格式化,請修改 Config/Format.php 文件配置。$supportedResponseFormats 包含了一個格式化響應(yīng)類型列表。默認(rèn)情況下,系統(tǒng)將會自動判斷并響應(yīng) XML 和 JSON 格式:

public $supportedResponseFormats = [
    'application/json',
    'application/xml'
];

這是在 Content Negotiation 中使用的數(shù)組,以確定返回的響應(yīng)類型。如果在客戶端請求的內(nèi)容和您支持的內(nèi)容之間沒有匹配,則返回第一個該數(shù)組中的格式。

接下來,需要定義用于格式化數(shù)據(jù)數(shù)組的類。這必須是一個完全合格的類名,類名必須實(shí)現(xiàn) CodeIgniterAPIFormatterInterface。格式化支持 JSON 和 XML

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

因此,如果您的請求在 Accept 頭中請求 JSON 格式的數(shù)據(jù),那么您傳遞的數(shù)據(jù)數(shù)組就可以通過其中任何一個 respond*fail* 方法將由 CodeIgniterAPIJSONFormatter 格式化。由此產(chǎn)生的 JSON 數(shù)據(jù)將被發(fā)送回客戶端。

引用類

respond($data[, $statusCode=200[, $message='']])

參數(shù): $data (mixed) – 返回客戶端的數(shù)據(jù)。字符串或數(shù)組。
$statusCode (int) – 返回的HTTP狀態(tài)碼。默認(rèn)為 200。
$message (string) – 返回的自定義 “reason” 消息。

這是該特征中所有其他方法用于將響應(yīng)返回給客戶端的方法。

$data 元素可以是字符串或數(shù)組。 默認(rèn)情況下,一個字符串將作為 HTML 返回,而數(shù)組將通過 json_encode 運(yùn)行并返回為 JSON,除非 Content Negotiation 確定它應(yīng)該以不同的格式返回。

如果一個 $message 字符串被傳遞,它將被用來替代標(biāo)準(zhǔn)的 IANA 標(biāo)準(zhǔn)碼回應(yīng)狀態(tài)。但不是每個客戶端都會遵守自定義代碼,并將使用 IANA 標(biāo)準(zhǔn)匹配狀態(tài)碼。

注解

由于它在活動的響應(yīng)實(shí)例上設(shè)置狀態(tài)碼和正文,所以應(yīng)該一直作為腳本執(zhí)行中的最終方法。

fail($messages[, int $status=400[, string $code=null[, string $message='']]])

參數(shù): $messages (mixed) – 包含遇到錯誤消息的字符串或字符串?dāng)?shù)組。
$status (int) – 返回的HTTP狀態(tài)碼。 默認(rèn)為400。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: 以客戶端的首選格式進(jìn)行多部分響應(yīng)。

這是用于表示失敗的響應(yīng)的通用方法,并被所有其他“fail”方法使用。

$messages 元素可以是字符串或字符串?dāng)?shù)組。 該 $status 參數(shù)是應(yīng)返回的HTTP狀態(tài)碼。

由于使用自定義錯誤代碼更好地提供了許多 API,因此可以在第三個參數(shù)中傳遞自定義錯誤代碼。如果沒有值,它將是一樣的 $status 【狀態(tài)碼】。

如果一個 $message 字符串被傳遞,它將被用于代替響應(yīng)狀態(tài)的標(biāo)準(zhǔn) IANA 碼。不是每個客戶端都會遵守自定義代碼,并且將使用與狀態(tài)代碼相匹配的 IANA 標(biāo)準(zhǔn)。

這個響應(yīng)是一個包含兩個元素的數(shù)組: errormessageserror 元素包含錯誤的狀態(tài)代碼。messages 元素包含一組錯誤消息。它看起來像:

$response = [
    'status' => 400,
    'code' => '321a',
    'messages' => [
        'Error message 1',
        'Error message 2'
    ]
];

respondCreated($data[, string $message = ''])

參數(shù): $data (mixed) – 返回給客戶端的數(shù)據(jù)。字符串或數(shù)組。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置創(chuàng)建新資源時使用的相應(yīng)狀態(tài)代碼,通常為201:

$user = $userModel->insert($data);
return $this->respondCreated($user);

respondDeleted($data[, string $message = ''])

參數(shù): $data (mixed) – 返回給客戶端的數(shù)據(jù)。字符串或數(shù)組
$message (string) – 自定義的“原因”消息返回。
返回: Response 對象的 send()方法的值。

設(shè)置當(dāng)通過此API調(diào)用的結(jié)果刪除新資源時使用的相應(yīng)狀態(tài)代碼(通常為200)。

$user = $userModel->delete($id);
return $this->respondDeleted(['id' => $id]);

failUnauthorized(string $description[, string $code=null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置當(dāng)用戶未被授權(quán)或授權(quán)不正確時使用的相應(yīng)狀態(tài)代碼。狀態(tài)碼為401。

return $this->failUnauthorized('Invalid Auth token');

failForbidden(string $description[, string $code=null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

不像 failUnauthorized,當(dāng)請求 API 路徑?jīng)Q不允許采用這種方法。未經(jīng)授權(quán)意味著客戶端被鼓勵再次嘗試使用不同的憑據(jù)。禁止意味著客戶端不應(yīng)該再次嘗試,因?yàn)樗粫袔椭顟B(tài)碼為403。

return $this->failForbidden('Invalid API endpoint.');

failNotFound(string $description[, string $code=null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置于在找不到請求的資源時使用的狀態(tài)碼。狀態(tài)碼為404。

return $this->failNotFound('User 13 cannot be found.');

failValidationError(string $description[, string $code=null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置于客戶端發(fā)送的數(shù)據(jù)未通過驗(yàn)證規(guī)則時使用的狀態(tài)碼。狀態(tài)碼通常為400。

return $this->failValidationError($validation->getErrors());

failResourceExists(string $description[, string $code=null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置于當(dāng)客戶端嘗試創(chuàng)建的資源已經(jīng)存在時使用的狀態(tài)碼。狀態(tài)碼通常為409。

return $this->failResourceExists('A user already exists with that email.');

failResourceGone(string $description[, string $code=null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置于當(dāng)請求的資源先前被刪除并且不再使用時使用的狀態(tài)碼。狀態(tài)碼通常為410。

return $this->failResourceGone('That user has been previously deleted.');

failTooManyRequests(string $description[, string $code=null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置于當(dāng)客戶端調(diào)用 API路徑次數(shù)過多時使用的狀態(tài)碼。這可能是由于某種形式的節(jié)流或速率限制。狀態(tài)碼通常為400。

return $this->failTooManyRequests('You must wait 15 seconds before making another request.');

failServerError(string $description[, string $code = null[, string $message = '']])

參數(shù): $description (mixed) – 顯示用戶的錯誤信息。
$code (string) – 一個自定義的API特定的錯誤代碼。
$message (string) – 返回的自定義“reason”消息。
返回: Response 對象的 send()方法的值。

設(shè)置于當(dāng)存在服務(wù)器錯誤時使用的狀態(tài)碼。

return $this->failServerError('Server error.');
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號