Himanshu SharmaSoftware engineer
Let’s talk

CodeIgniter 4 · Lesson 24 of 30

CodeIgniter API contracts: validate writes and report failures

Decode and validate a proposed JSON write body through test-only routes while preserving the public API as read-only.

15 minFiles and APIsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonDecode and validate a proposed JSON write body through test-only routes while preserving the public API as read-only.

After this lesson you can define a JSON write contract, reject malformed or invalid bodies and distinguish action tests from a publicly exposed endpoint. The public book API remains read-only. We add a create method for isolated testing, without adding a production POST route before authentication and authorization are reviewed.

Specify the contract before decoding

The proposed body is a JSON object containing a title. Arrays, scalar JSON and malformed JSON are not acceptable request shapes. A valid object can still fail the title policy. These are different failure classes even if this learning method uses status 400 for each rejection.

json
{"title":"A Test Book"}

This complete JSON block was parsed during course checks. Do not manually construct JSON by concatenating unescaped strings. Clients should use their language's serializer, and the server should use its response serializer. A title can contain quotes without becoming invalid transport data when serialized correctly.

Add an unexposed action

Add this method inside the existing App\Controllers\Api\Books class. Keep the resource route restricted to index and show. The method was linted and exercised through test-only routes in the isolated application.

php
    public function create()
    {
        try {
            $decoded = json_decode($this->request->getBody(), false, 512, JSON_THROW_ON_ERROR);
        } catch (\JsonException $e) {
            return $this->fail('Malformed JSON.', 400);
        }
        if (! is_object($decoded)) {
            return $this->fail('Expected a JSON object.', 400);
        }
        $data = get_object_vars($decoded);
        $validator = service('validation');
        $validator->setRules(['title' => 'required|max_length[120]']);
        if (! $validator->run(['title' => $data['title'] ?? null])) {
            return $this->failValidationErrors($validator->getErrors());
        }
        $id = $this->model->insert(['title' => $data['title']], true);
        return $this->respondCreated(['id' => $id, 'title' => $data['title']]);
    }

The PHP manual documents json_decode and JSON_THROW_ON_ERROR. Decoding to an object preserves the distinction between an empty object and an empty array. Then get_object_vars supplies the field array for validation. A missing title reaches the validator rather than being mistaken for malformed JSON.

The current method ignores additional object keys and persists only title. That is a deliberate small contract, not a claim that all APIs should ignore unknown fields. If your API rejects unknown fields, implement and test that rule explicitly. Never pass the entire decoded object directly into a privileged model operation.

Understand the response choices

The success response uses respondCreated and returns the generated identifier with the accepted title. The verification tests observed status 201 for a valid body. The helper failValidationErrors returned status 400 with the installed response configuration. Do not assume its name implies the same status used by the HTML form's explicit 422 branch.

A malformed body and an array body were also checked and returned 400. A production API could choose a more detailed error code scheme or enforce Content-Type explicitly. This method does not implement a content-type gate, authentication, rate limiting or a complete operational error policy. Keep those boundaries visible before exposing it.

A persistence failure should not be disguised as a successful creation. The diagnostic and deployment lessons explain the broader review needed for real operations. This learning action demonstrates decoding, shape checks, title validation and response selection against the disposable database.

Test without opening the public surface

The test framework can supply a temporary route collection for a request. That lets us exercise the method while the application's actual route map remains read-only for API consumers. These tests prove action behavior; they do not prove an authentication filter or CSRF boundary because the test-only route does not include those policies.

This distinction matters when interpreting a green test. A method returning 201 in isolation is not evidence that an unauthorized external caller is denied. The final review keeps public writes unavailable until a reviewed access integration exists.

The fetched official API Responses guide, HTTP Feature Testing guide and PHP json_decode manual support the facilities used here. The proposed request schema and status contract are course decisions verified in CodeIgniter 4.7.6.

You can inspect the fictional request object with the JSON formatter. Formatting checks its structure for reading; it does not prove that an API permission policy exists.

Common mistakes

Decoding objects and arrays into the same representation can hide a shape distinction you intended to enforce. Assuming helper names dictate an unverified status leads to incorrect client expectations. Adding a POST resource route just to try the action exposes more than a test needs. Finally, treating an isolated action test as proof of authorization confuses the behavior being measured.

Exercise

Classify these bodies: a title object, an empty object and an empty array. Predict which reaches insertion. Then explain why successful test-only creation does not justify publishing a write route.

Show an answer

The title object can pass validation and insert. The empty object has the correct outer shape but fails the required title rule. The empty array fails the shape check. Only the accepted title reaches persistence. The test-only route has no reviewed identity and permission policy, so a passing action test does not establish safe external access.

Previous lesson · Next lesson · Related: explicit routes · Related: security boundaries

Key points

  • Decode JSON objects distinctly from arrays.
  • The verified response helper uses 400 for validation failures here.
  • Test-only action routes do not establish public authorization.

Check yourself

1. What does the empty JSON object fail?
2. What status did valid test creation return?
3. Is the new create method publicly routed here?

Free tools for this lesson