🔥 CodeIgniter Intermediate

What is CodeIgniter 4 response API trait?

Answer

The ResponseTrait in CI4 (CodeIgniter\API\ResponseTrait) provides convenient methods for building consistent API responses when added to API controllers. Success responses: $this->respond($data, 200) (generic), $this->respondCreated($data) (201), $this->respondDeleted($data) (200), $this->respondNoContent() (204). Error responses: $this->fail("Error message", 400), $this->failNotFound("User not found") (404), $this->failUnauthorized() (401), $this->failForbidden() (403), $this->failValidationErrors($errors) (422), $this->failResourceExists() (409). All methods automatically detect the preferred format (JSON/XML) via Content Negotiation and set appropriate headers. This trait standardizes API responses and is far cleaner than manually building response arrays.