🔥 CodeIgniter Intermediate

What is CI4's Content Negotiation?

Answer

Content Negotiation in CI4 allows the application to respond to a request in the format the client prefers, based on the Accept header. Use the negotiate service: $negotiate = service("negotiator"); $format = $negotiate->media(["application/json", "text/html"]) — returns the preferred format the client accepts. Negotiate language: $negotiate->language(["en", "fr", "de"]). Negotiate encoding, charset, and language similarly. This is particularly useful for building APIs that serve both JSON (for API clients) and HTML (for browsers) from the same controller. CI4 also provides a CodeIgniter\API\ResponseTrait for API controllers that includes helpers like $this->respond($data), $this->failNotFound("User not found"), $this->failValidationErrors($errors), and $this->respondCreated($data).