API resources, errors ແລະ OpenAPI.
ເລືອກ public fields ຊັດເຈນ ແລະເກັບ contract ຂອງ API ໃນ source code.
1. ກຳນົດ output allowlist
Resource ຄືນພຽງ flat scalar/null fields ທີ່ລະບຸ. ບໍ່ serialize model/object/nested array ອັດຕະໂນມັດ. ກວດ authorization ແລະ tenant filter ກ່ອນ query; projection ບໍ່ແທນ policy. ຖ້າຕ້ອງການ nested resource ໃຫ້ສ້າງ explicit projection ແຍກ.
use Icom\Http\Resource;
$publicUser = new Resource(['id', 'display_name']);
return $publicUser->response([
'id' => 42, 'display_name' => 'Developer',
'password_hash' => 'never exposed by this projection',
]);
// {"data":{"id":42,"display_name":"Developer"}}
// collection($rows, limit: 100) rejects more than the configured limit.
// Use cursorPaginate to bound database reads first.2. ຄຳຕອບ error ທີ່ສະໝ່ຳສະເໝີ
Problem::response ສ້າງ application/problem+json ຕາມ RFC9457 ກັບ type about:blank, title, status ແລະ optional detail/errors. ໃຊ້ public message ທີ່ເລືອກເອງ; ຢ່າສົ່ງ exception message, SQL, token ຫຼື raw input. ຟີເຈີນີ້ບໍ່ປ່ຽນ error response ເກົ່າທັງແອັບອັດຕະໂນມັດ.
use Icom\Http\Problem;
return Problem::response(422, 'Please check the submitted fields.', [
'email' => ['Enter a valid email address.'],
]);3. OpenAPI ຈາກ trusted metadata
config/openapi.php ລະບຸພຽງ public GET /api/status ແລະ /api/hello/{name}. ເປີດ /openapi.json ເພື່ອອ່ານ OpenAPI3.1.2. ບໍ່ສະແກນ private routes, .env ຫຼື source comments ມາເຜີຍແຜ່. api:spec ສ້າງ JSON ໂດຍບໍ່ bootstrap ແອັບ; api:check bootstrap ແລ້ວກວດ method/path ທີ່ເອກະສານລະບຸ.
php bin/icom api:spec > openapi.json
php bin/icom api:check
# api:check returns nonzero when a described route is missing.
# Review the JSON before publishing any additional operation.4. ກຳນົດ contract ຢ່າງຊັດເຈນ
OpenApi constructor ຮັບ title, version, operations, schemas ແລະ securitySchemes. Operation ຕ້ອງມີ method/path/operationId/responses/security; public ໃຊ້ security: []. ຖ້າ protected ໃຫ້ລະບຸ scheme ທີ່ປະກາດໄວ້. ລຸ່ນນີ້ຮອງຮັບ HTTP ແລະ header/cookie apiKey schemes, local schema references ເທົ່ານັ້ນ. ບໍ່ດຶງ external $ref ແລະບໍ່ປະກາດ OAuth flows ໃຫ້ອັດຕະໂນມັດ.
5. ສິ່ງທີ່ api:check ກວດບໍ່ໄດ້
ການມີ route ກົງເອກະສານບໍ່ພິສູດວ່າ response ທຸກອັນກົງ schema ຫຼືວ່າ authentication ຖືກຕິດຕັ້ງ. Builder ເປັນ bounded description tool, ບໍ່ແມ່ນ full JSON Schema validator/code generator. ຕ້ອງກວດ contract, auth ແລະ payload ດ້ວຍ integration tests; ໃຊ້ official schema validator ໃນ CI ຫຼັງແກ້ specification. ບໍ່ມີ Swagger UI ຫຼື remote CDN script ຖືກໂຫຼດ.