🔥 CodeIgniter Intermediate

What is CI4's Content Negotiation?

Why Interviewers Ask This

This question targets practical, hands-on experience with CodeIgniter. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

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).

Pro Tip

This topic has CodeIgniter-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.